question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
How to get the id of a specific edge with two of its vertex?
Example:
egde id=4 with vertex 2 and 3, using id 2 and 3 vertex how to get the id=4 of that edge?
|
igraph_get_eidis the function you are looking for.
|
I'm trying to figure out how to compile Python modules in C (http://docs.python.org/extending/extending.html), but the Python.h header file appears to be missing.
I've installed all the python development headers (I have Python-dev, python2.7-dev, python2.6-dev, python-all-dev) but gcc is still reutrning the error:
... |
You need to usepython-configto determine the compile time and link time flags.
When compiling:
```
gcc -c `python-config --cflags` somefile.c
```
When linking:
```
gcc -o libfoo.so -shared `python-config --ldflags`
```
Though you really ought to think about using distutils as described inBuilding C and C++ Extens... |
C is like chinese to me but i got to work with some code
```
struct Message {
unsigned char state;
};
char state [4][4] = { "OFF", "ON", "IL1", "IL2" };
```
This is a simple server that receives a message. The Struct part of it is obvious, but then theres that char array thing. Does this say theres 4 dif... |
It means thatstateis an array of 4 char arrays, each of them is an array of 4 char, and they are initialized with the values "OFF\0", "ON\0", "IL1\0" and "IL2\0"
```
+----+----+----+----+
state => |OFF |ON |IL1 |IL2 |
+----+----+----+----+
^state[0]
^state[1]
^state... |
I've stumbled accross:
```
sprintf(buffer, "%!ld ", date);
```
I understand the ld is for long integer, but what is the purpose of the!? I can't find any reference on this, and the output seems similar to the classical%ldfor me
edit : apparently on my system it appends to the variable the string+to_date('01/01/1904... |
As far as I know, this won't be valid for printf - or would just be ignored. The only situation I know of, where you use something like%!is FormatMessage on Windows, seehttp://msdn.microsoft.com/en-us/library/aa908810.aspx
|
I am trying to create a tag file manually for C sources (*.cand*.h) usingctagscommand. Unfortunately the tag file is not having entries of all files, specially the header files.
I am using following command on the command prompt:
```
find . -name \*.[ch] -exec ctags {} \;
```
Kindly point out if I am missing some f... |
If you execute (your version):
```
find . -name \*.[ch] -exec ctags {} \;
```
thenfindexecutesctagsonce for each file that is found. Thetagsfile is overwritten each time, and only the tags for the last file remain.
Instead, you need to tellfindto executectagsexactly once, and specifyallthe matching files in one cal... |
Is there a way I can compile code with OpenMP to C code (With OpenMP part translated to plain C), so that I can know what kind of code is being generated by OpenMP. I am using gcc 4.4 compiler.
|
Like the other commenters pointed out gcc doesn't translate OpenMP directives to plain C.
But if you want to get an idea of what gcc does with your directives you can compile with the-fdump-tree-optimizedoption. This will generate the intermediate representation of the program which is at least C-like.
There are sev... |
I'm trying to implement a generic linked list. The struct for the node is as follows -
```
typedef struct node{
void *data;
node *next;
};
```
Now, when I try to assign an address to the data, suppose for example for an int, like -
```
int n1=6;
node *temp;
temp = (node*)malloc(sizeof(node));
... |
You must first typecast thevoid*to actual valid type of pointer (e.gint*) to tell the compiler how much memory you are expecting to dereference.
|
Code like this can work fine:
```
char str[] = {'a', 'b', '\0'};
```
The left is an auto variable(array).
Code like this canNOTwork:
```
char *str = {'a', 'b', '\0'};
```
The left side is a pointer. The pointer points to an unknown space, so this will fail.
My question is, what is the type of the right side?
In... |
In C++03 a brace-enclosed initializer is just a syntactic device that can be used to initialize aggregates (such as arrays or certain types of classes or structs). It does not have a 'type' and can only be used for those specific kinds of initializers.
8.5.1/2 "Aggregates":When an aggregate is initialized the initia... |
In C, declaring a char pointer like this
```
char* p="Hello";
```
allocates some memory for a string literalHello\0. When I do this afterwards
```
p="FTW";
```
what happens to the memory allocated toHello\0? Is the address p points to changed?
|
There is no dynamic memory allocation in either statement.
Those strings are stored in your executable, loaded in a (likely read-only) section of memory that will live as long as your process does.
The second assignment only changes whatppoints to. Nothing else happens.
|
I'm working on a program where I need to know the exact boundaries on signed integers in C. My question is, if you compile a program that depends on this boundary, do you have to check the local environment to see how many bits are used to hold the value?
I'll try to explain this better. Whenever I write a C program ... |
((sizeof(n) + sizeof(int) - 1) & ~(sizeof(int) - 1))
This should give you the limit
|
I want to extract the base name from a string, like
```
/opt/home/etc/sample
```
That is, I want to parse a string of large length returningsample, or the substring
after the last/character. The string can be of any length.
How could this be done?
|
```
char *input = "/opt/home/etc/sample";
char *output = NULL;
output = strrchr(input, '/');
if(output != NULL)
{
printf("%s\n", output);
}
```
Or otherway is that you can try to parse it all by yourself (Below code is just a sample and doesn't handle all error and boundary conditions, which you can try and lea... |
Is it possible to overload operators (such as operators of comparison) in C?
If so, how do you do it? I did a quick search, but all I found was for C++, and what I want is for C.
Anyone have any ideas?
Edit1: The idea is: I have a struct, and I need to do a comparison (based on a member of the struct). And for t... |
No, it is not possible. C does not support operator overloading by the developer.
|
How to get the id of a specific edge with two of its vertex?
Example:
egde id=4 with vertex 2 and 3, using id 2 and 3 vertex how to get the id=4 of that edge?
|
igraph_get_eidis the function you are looking for.
|
I'm trying to figure out how to compile Python modules in C (http://docs.python.org/extending/extending.html), but the Python.h header file appears to be missing.
I've installed all the python development headers (I have Python-dev, python2.7-dev, python2.6-dev, python-all-dev) but gcc is still reutrning the error:
... |
You need to usepython-configto determine the compile time and link time flags.
When compiling:
```
gcc -c `python-config --cflags` somefile.c
```
When linking:
```
gcc -o libfoo.so -shared `python-config --ldflags`
```
Though you really ought to think about using distutils as described inBuilding C and C++ Extens... |
C is like chinese to me but i got to work with some code
```
struct Message {
unsigned char state;
};
char state [4][4] = { "OFF", "ON", "IL1", "IL2" };
```
This is a simple server that receives a message. The Struct part of it is obvious, but then theres that char array thing. Does this say theres 4 dif... |
It means thatstateis an array of 4 char arrays, each of them is an array of 4 char, and they are initialized with the values "OFF\0", "ON\0", "IL1\0" and "IL2\0"
```
+----+----+----+----+
state => |OFF |ON |IL1 |IL2 |
+----+----+----+----+
^state[0]
^state[1]
^state... |
I've stumbled accross:
```
sprintf(buffer, "%!ld ", date);
```
I understand the ld is for long integer, but what is the purpose of the!? I can't find any reference on this, and the output seems similar to the classical%ldfor me
edit : apparently on my system it appends to the variable the string+to_date('01/01/1904... |
As far as I know, this won't be valid for printf - or would just be ignored. The only situation I know of, where you use something like%!is FormatMessage on Windows, seehttp://msdn.microsoft.com/en-us/library/aa908810.aspx
|
I am trying to create a tag file manually for C sources (*.cand*.h) usingctagscommand. Unfortunately the tag file is not having entries of all files, specially the header files.
I am using following command on the command prompt:
```
find . -name \*.[ch] -exec ctags {} \;
```
Kindly point out if I am missing some f... |
If you execute (your version):
```
find . -name \*.[ch] -exec ctags {} \;
```
thenfindexecutesctagsonce for each file that is found. Thetagsfile is overwritten each time, and only the tags for the last file remain.
Instead, you need to tellfindto executectagsexactly once, and specifyallthe matching files in one cal... |
Is there a way I can compile code with OpenMP to C code (With OpenMP part translated to plain C), so that I can know what kind of code is being generated by OpenMP. I am using gcc 4.4 compiler.
|
Like the other commenters pointed out gcc doesn't translate OpenMP directives to plain C.
But if you want to get an idea of what gcc does with your directives you can compile with the-fdump-tree-optimizedoption. This will generate the intermediate representation of the program which is at least C-like.
There are sev... |
I'm trying to implement a generic linked list. The struct for the node is as follows -
```
typedef struct node{
void *data;
node *next;
};
```
Now, when I try to assign an address to the data, suppose for example for an int, like -
```
int n1=6;
node *temp;
temp = (node*)malloc(sizeof(node));
... |
You must first typecast thevoid*to actual valid type of pointer (e.gint*) to tell the compiler how much memory you are expecting to dereference.
|
Code like this can work fine:
```
char str[] = {'a', 'b', '\0'};
```
The left is an auto variable(array).
Code like this canNOTwork:
```
char *str = {'a', 'b', '\0'};
```
The left side is a pointer. The pointer points to an unknown space, so this will fail.
My question is, what is the type of the right side?
In... |
In C++03 a brace-enclosed initializer is just a syntactic device that can be used to initialize aggregates (such as arrays or certain types of classes or structs). It does not have a 'type' and can only be used for those specific kinds of initializers.
8.5.1/2 "Aggregates":When an aggregate is initialized the initia... |
In C, declaring a char pointer like this
```
char* p="Hello";
```
allocates some memory for a string literalHello\0. When I do this afterwards
```
p="FTW";
```
what happens to the memory allocated toHello\0? Is the address p points to changed?
|
There is no dynamic memory allocation in either statement.
Those strings are stored in your executable, loaded in a (likely read-only) section of memory that will live as long as your process does.
The second assignment only changes whatppoints to. Nothing else happens.
|
I'm working on a program where I need to know the exact boundaries on signed integers in C. My question is, if you compile a program that depends on this boundary, do you have to check the local environment to see how many bits are used to hold the value?
I'll try to explain this better. Whenever I write a C program ... |
((sizeof(n) + sizeof(int) - 1) & ~(sizeof(int) - 1))
This should give you the limit
|
I want to extract the base name from a string, like
```
/opt/home/etc/sample
```
That is, I want to parse a string of large length returningsample, or the substring
after the last/character. The string can be of any length.
How could this be done?
|
```
char *input = "/opt/home/etc/sample";
char *output = NULL;
output = strrchr(input, '/');
if(output != NULL)
{
printf("%s\n", output);
}
```
Or otherway is that you can try to parse it all by yourself (Below code is just a sample and doesn't handle all error and boundary conditions, which you can try and lea... |
I know that in h264 we can detect a NAL Unit by the bit pattern0x000001.
Is there an equivalent method to detect a slice header in a NAL Unit? How does one handle multi-slice NAL units?
Currently I'm using parsing code for h264 and get the slice header in a respective structure.
|
The slice header syntax is discussed on page 36 (section 7.3.3) of theH.264 standard.
It might be worth having a look at thereference software.
|
While mentioning the size of a structure to a malloc call, is it better to mention the name of the structure or the dereferenced structure pointer variable?
Example:
```
struct ExampleStruct
{
int x;
char arr[40];
};
int main()
{
struct ExampleStruct *Y = NULL;
Y = malloc(sizeof(struct ExampleStruct)); //... |
I definitely prefer the 2nd. If the declared type ofYevery changes, the line will still work correctly.
|
I've got about 12000 pre known values that I need to place in an array early in the program. Given certain circumstances, I will later need to resize this array with realloc. Is there any way to initialize an array with malloc/calloc with values, or fill an array with several other values?
|
You cannot initialize amalloced array this way, your best chance is to have it statically in your program, and copy it to amalloced array at the beginning of the run, e.g.:
```
static int arr[] = {1,2,3,4};
static int * malloced_arr;
// in the init function
malloced_arr = malloc(sizeof(arr));
if (malloced_arr)
{
... |
When I read some disassembly code, for I am not up on AT&T syntax, I do not know what some code like (%esp,1) means.
```
11 printf("%x", a);
0x401386 <main+182>: movl $0x1,0x4(%esp,1)
0x40138e <main+190>: movl $0x40300d,(%esp,1)
0x401395 <main+197>: call 0x401810 <printf>
```
C... |
This wikibook seems to have some information about the GNU assembler and its AT&T syntax:
http://en.wikibooks.org/wiki/X86_Assembly/GAS_Syntax
I also found these two sources of documentation on Gas, but they don't seem to be very clear or useful:
http://webster.cs.ucr.edu/AsmTools/Gas/GasDoc/as_toc.htmlhttp://sourc... |
I've a homework that I have to do, but I'm wondering if in C we have some function that will actually convert the8 bitbinary like for example01010111which is87and in letter isW
I'm going to be given a big set and I just have to store binary number in one array and convert after that I will combine all of them and ret... |
Yes, thestrtolfunction can be used to parse a textual representation of a binary string by providing2as the last argument (indicating the string is representing a number in base 2).
|
I'm trying to use message queue in Linux, is it possible to do the below
process 1 has message queue named one
producer 1 & 2 send message to one with no lock mechanism, is that ok ?
|
Sys V message queues provide priority, so that a particular queue recipient can be specified and can get messages "aimed" at it. With no contention. Queue readers can access any message as well depending on the mtype value inmsgrcv(). POSIX message queues are a little different. Generally you can employ Sys V que... |
I'm trying to make a simple reader/writer program using POSIX named semaphores, its working, but on some systems, it halts immediately on the first semaphore and thats it ... I'm really desperate by now. Can anyone help please? Its working fine on my system, so i can't track the problem by ltrace. (sorry for the comme... |
POSIX semaphores are not well suited for application code since they are interruptible. Basically any sort of IO to your processes will mess up your signalling. Please have a look atthis post.
So you'd have to be really careful to interpret all error returns from thesem_functions properly. In the code that you posted... |
I'm trying to create a 2D array from the data read from .txt file.The data in 'data.txt' look like belows:
```
A;B;4
A;C;5
B;C;8
```
Assume it is symmetry.Is there any way to create a 2D matrix [i][j] and print in d[i][j] = value?
Appreciate your comments/suggestion.
|
2D arrays are useful when the dimensions are known at compile time. If this is the case, other answers can be useful. If not, a 2D array isn't for you.
I suggest using a simple 1D array, allocated (malloc) to have n*n entries.Then, to access cell i/j, usearray[i*n+j].
Another approach is to allocate an array of poin... |
I was wondering if someone could clarify the following: if I'm not mistaken fd is a pointer to the next malloc_chunk structure in the bin but I've also seen it specified as a pointer to the fd field in the malloc_chunk structure. So does it point to the beginning of the malloc_chunk struct or the fd field in the struc... |
It's type is astruct malloc_chunk *, so it should point to a malloc_chunk structure, the next one. If it pointed to the fd field, it would be a pointer to a pointer to a pointer, ...., which could be stored as avoid *
|
InCcomponent selection, what is the benefit of structure-returning function? for example:
```
struct S {
int a, b;
} x;
```
Why is it that I can assign the above struct as a function as shown below, Is there any benefit of doing this?
```
extern struct S f(); /* Why is this neccesary? */
x = f(); /* Is this accu... |
It's just a function that happens to return astruct. There's nothing more to it than that. You wouldn't be surprised to see a function return anint, why be surprised when one returns a struct?
As an aside, theexternis superfluous here because that is the default storage class for functions.
|
I use the following to split my strings into usable information
```
sscanf(last, "%*[^:]:%*[^:]:%*[^:]:%127[^:]:", field_x);
```
which would grab the fourth field of a string separated by colons, but now I need to use it to split a string separated by spaces, but I have no clue how to do it as doing throwing " "'s i... |
Contrary to what you believe,
```
sscanf(last, "%*[^ ] %*[^ ] %*[^ ] %127[^ ] ", field_x);
```
indeeddoes what you want
|
In C, if I allocate a memory usingmallocand during the execution, the program encounters an exception/error and exits with a manually incorporatedexit(1)statement in the program, does C compiler automatically frees the memory before making the unexpected exit or do I have to manually do this just before theexit(1)line... |
Once you callexit, OS takes all the allocated memory back. So no need to callfree.
Edit:
But It's generally good practice to free memory you allocated in your program as you may overlook it the call to free when you modify it in the future.
|
```
char *pStrBuffer;
unsigned char data;
unsigned int Address;
/* pStrBuffer reading from a file data in file of the form
WriteByte(0xDE04,0x20)
WriteByte(0xFE08,0x50) ....
*/
/* in a loop */
sscanf(pStrBuffer,"%x%x",&Address,&data);
```
Compiler is gnu gcc 4.5 in Windows XP
However ... |
To read a single unsigned byte, use the%hhxmodifier.%hxis for anunsigned short,%xis for anunsigned int,%lxis for anunsigned long, and%llxis for an `unsigned long long.
|
I am developing a backup utility and I am getting the error:
Too many open files in system
after it runs for a while. The error is returned bystat().
Since I am not actually opening any files (fopen()), my question is if any of the following functions (which I am using) take up a file descriptor, and if so, what ca... |
The functions you listed are safe; none of them return anything that you could "close".
To find out more, run the commandlsof -p+ PID of your backup process. That will give you a list of files which the process has opened which in turn will give you an idea what is going on.
See:lsofmanual page.
|
I want to use this library for cross platform networking.
http://lacewing-project.org/
It works with OSX, Linux, Windows and has specific code for Android. What I do not know is if it will work (as a client) on iOS. (meaning I will not host a server on iOS)
Since it uses POSIX sockets internally does that make it c... |
Without trying it, my guess would be that it would work. You will need to write your UI in Objective-C, but you should be able to use Objective-C++ to bind your libraries to the UI. Before you start into the Objective-C++ path be aware of the limitations (see:How well is Objective-C++ supported?).
|
I was thinking today about the try/catch blocks existent in another languages. Googled for a while this but with no result. From what I know, there is not such a thing as try/catch in C. However, is there a way to "simulate" them?Sure, there is assert and other tricks but nothing like try/catch, that also catch the ra... |
C itself doesn't support exceptions but you can simulate them to a degree withsetjmpandlongjmpcalls.
```
static jmp_buf s_jumpBuffer;
void Example() {
if (setjmp(s_jumpBuffer)) {
// The longjmp was executed and returned control here
printf("Exception happened here\n");
} else {
// Normal code execut... |
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question
What is the precedence level ofpointing to ->operator wrt to the arthmetic, bitwise and other pointer refer... |
"High". See theoperator precedence table. Note that the linked-to table includes C++ too, so you need to read it carefully.
Here's another table, which is C only. You can see that the only operators that share the precedence level of->are()(function call),[](array indexing) and.(element selection).
|
I have the following C statement:
```
int res = x & (x ^ y);
```
Is there a way to do the same thing, but usingxandyonly one time each?
For example:
```
x | (~x & y) == x | y
```
|
Yes, by expanding the xor (a ^ b == (a & ~b) | (~a & b)), and then simplifying the result, one gets:
```
res = x & ~y;
```
|
```
#include <stdio.h>
int main(void) {
for (int i = 0; i < 5; i++) {
int arr[5] = {0};
// arr gets zeroed at runtime, and on every loop iteration!
printf("%d %d %d %d %d\n", arr[0], arr[1], arr[2], arr[3], arr[4]);
// overwrite arr with non-zero crap!
arr[0] = 3;
a... |
You are creating anewarray at each iteration, so there is no re-initialization.
|
I need a library to list files in archives and to extract archive files. The library should support archive types as much as possible. Do you have any suggestion ?
Any help would be appreciated.
|
This sounds like you are looking for libarchivehttp://libarchive.github.com/
|
I need to convert my string into int array. so i make a loop over string, and callint atoi(char *p)function fromstdlib.h, but it doesn`t working on mac (some times ago i tryed it on Windows, and it workong well). simple loop:
```
for(p = buff; *p; p++)
printf("%d", atoi(p));
```
whats the problem with work of th... |
The function is working perfectly fine. For instance ifbuffcontains"123", your code will print123233.
However it seems you want to just print the value of individual digits, in which caseatoihas nothing to do with your problem. Try:
```
for(p = buff; *p; p++)
printf("%d", *p-'0');
```
|
I was wondering if someone could clarify the following: if I'm not mistaken fd is a pointer to the next malloc_chunk structure in the bin but I've also seen it specified as a pointer to the fd field in the malloc_chunk structure. So does it point to the beginning of the malloc_chunk struct or the fd field in the struc... |
It's type is astruct malloc_chunk *, so it should point to a malloc_chunk structure, the next one. If it pointed to the fd field, it would be a pointer to a pointer to a pointer, ...., which could be stored as avoid *
|
InCcomponent selection, what is the benefit of structure-returning function? for example:
```
struct S {
int a, b;
} x;
```
Why is it that I can assign the above struct as a function as shown below, Is there any benefit of doing this?
```
extern struct S f(); /* Why is this neccesary? */
x = f(); /* Is this accu... |
It's just a function that happens to return astruct. There's nothing more to it than that. You wouldn't be surprised to see a function return anint, why be surprised when one returns a struct?
As an aside, theexternis superfluous here because that is the default storage class for functions.
|
I use the following to split my strings into usable information
```
sscanf(last, "%*[^:]:%*[^:]:%*[^:]:%127[^:]:", field_x);
```
which would grab the fourth field of a string separated by colons, but now I need to use it to split a string separated by spaces, but I have no clue how to do it as doing throwing " "'s i... |
Contrary to what you believe,
```
sscanf(last, "%*[^ ] %*[^ ] %*[^ ] %127[^ ] ", field_x);
```
indeeddoes what you want
|
In C, if I allocate a memory usingmallocand during the execution, the program encounters an exception/error and exits with a manually incorporatedexit(1)statement in the program, does C compiler automatically frees the memory before making the unexpected exit or do I have to manually do this just before theexit(1)line... |
Once you callexit, OS takes all the allocated memory back. So no need to callfree.
Edit:
But It's generally good practice to free memory you allocated in your program as you may overlook it the call to free when you modify it in the future.
|
```
char *pStrBuffer;
unsigned char data;
unsigned int Address;
/* pStrBuffer reading from a file data in file of the form
WriteByte(0xDE04,0x20)
WriteByte(0xFE08,0x50) ....
*/
/* in a loop */
sscanf(pStrBuffer,"%x%x",&Address,&data);
```
Compiler is gnu gcc 4.5 in Windows XP
However ... |
To read a single unsigned byte, use the%hhxmodifier.%hxis for anunsigned short,%xis for anunsigned int,%lxis for anunsigned long, and%llxis for an `unsigned long long.
|
I am developing a backup utility and I am getting the error:
Too many open files in system
after it runs for a while. The error is returned bystat().
Since I am not actually opening any files (fopen()), my question is if any of the following functions (which I am using) take up a file descriptor, and if so, what ca... |
The functions you listed are safe; none of them return anything that you could "close".
To find out more, run the commandlsof -p+ PID of your backup process. That will give you a list of files which the process has opened which in turn will give you an idea what is going on.
See:lsofmanual page.
|
I want to use this library for cross platform networking.
http://lacewing-project.org/
It works with OSX, Linux, Windows and has specific code for Android. What I do not know is if it will work (as a client) on iOS. (meaning I will not host a server on iOS)
Since it uses POSIX sockets internally does that make it c... |
Without trying it, my guess would be that it would work. You will need to write your UI in Objective-C, but you should be able to use Objective-C++ to bind your libraries to the UI. Before you start into the Objective-C++ path be aware of the limitations (see:How well is Objective-C++ supported?).
|
I was thinking today about the try/catch blocks existent in another languages. Googled for a while this but with no result. From what I know, there is not such a thing as try/catch in C. However, is there a way to "simulate" them?Sure, there is assert and other tricks but nothing like try/catch, that also catch the ra... |
C itself doesn't support exceptions but you can simulate them to a degree withsetjmpandlongjmpcalls.
```
static jmp_buf s_jumpBuffer;
void Example() {
if (setjmp(s_jumpBuffer)) {
// The longjmp was executed and returned control here
printf("Exception happened here\n");
} else {
// Normal code execut... |
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question
What is the precedence level ofpointing to ->operator wrt to the arthmetic, bitwise and other pointer refer... |
"High". See theoperator precedence table. Note that the linked-to table includes C++ too, so you need to read it carefully.
Here's another table, which is C only. You can see that the only operators that share the precedence level of->are()(function call),[](array indexing) and.(element selection).
|
I have the following C statement:
```
int res = x & (x ^ y);
```
Is there a way to do the same thing, but usingxandyonly one time each?
For example:
```
x | (~x & y) == x | y
```
|
Yes, by expanding the xor (a ^ b == (a & ~b) | (~a & b)), and then simplifying the result, one gets:
```
res = x & ~y;
```
|
I use the following to split my strings into usable information
```
sscanf(last, "%*[^:]:%*[^:]:%*[^:]:%127[^:]:", field_x);
```
which would grab the fourth field of a string separated by colons, but now I need to use it to split a string separated by spaces, but I have no clue how to do it as doing throwing " "'s i... |
Contrary to what you believe,
```
sscanf(last, "%*[^ ] %*[^ ] %*[^ ] %127[^ ] ", field_x);
```
indeeddoes what you want
|
In C, if I allocate a memory usingmallocand during the execution, the program encounters an exception/error and exits with a manually incorporatedexit(1)statement in the program, does C compiler automatically frees the memory before making the unexpected exit or do I have to manually do this just before theexit(1)line... |
Once you callexit, OS takes all the allocated memory back. So no need to callfree.
Edit:
But It's generally good practice to free memory you allocated in your program as you may overlook it the call to free when you modify it in the future.
|
```
char *pStrBuffer;
unsigned char data;
unsigned int Address;
/* pStrBuffer reading from a file data in file of the form
WriteByte(0xDE04,0x20)
WriteByte(0xFE08,0x50) ....
*/
/* in a loop */
sscanf(pStrBuffer,"%x%x",&Address,&data);
```
Compiler is gnu gcc 4.5 in Windows XP
However ... |
To read a single unsigned byte, use the%hhxmodifier.%hxis for anunsigned short,%xis for anunsigned int,%lxis for anunsigned long, and%llxis for an `unsigned long long.
|
I am developing a backup utility and I am getting the error:
Too many open files in system
after it runs for a while. The error is returned bystat().
Since I am not actually opening any files (fopen()), my question is if any of the following functions (which I am using) take up a file descriptor, and if so, what ca... |
The functions you listed are safe; none of them return anything that you could "close".
To find out more, run the commandlsof -p+ PID of your backup process. That will give you a list of files which the process has opened which in turn will give you an idea what is going on.
See:lsofmanual page.
|
I want to use this library for cross platform networking.
http://lacewing-project.org/
It works with OSX, Linux, Windows and has specific code for Android. What I do not know is if it will work (as a client) on iOS. (meaning I will not host a server on iOS)
Since it uses POSIX sockets internally does that make it c... |
Without trying it, my guess would be that it would work. You will need to write your UI in Objective-C, but you should be able to use Objective-C++ to bind your libraries to the UI. Before you start into the Objective-C++ path be aware of the limitations (see:How well is Objective-C++ supported?).
|
I was thinking today about the try/catch blocks existent in another languages. Googled for a while this but with no result. From what I know, there is not such a thing as try/catch in C. However, is there a way to "simulate" them?Sure, there is assert and other tricks but nothing like try/catch, that also catch the ra... |
C itself doesn't support exceptions but you can simulate them to a degree withsetjmpandlongjmpcalls.
```
static jmp_buf s_jumpBuffer;
void Example() {
if (setjmp(s_jumpBuffer)) {
// The longjmp was executed and returned control here
printf("Exception happened here\n");
} else {
// Normal code execut... |
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question
What is the precedence level ofpointing to ->operator wrt to the arthmetic, bitwise and other pointer refer... |
"High". See theoperator precedence table. Note that the linked-to table includes C++ too, so you need to read it carefully.
Here's another table, which is C only. You can see that the only operators that share the precedence level of->are()(function call),[](array indexing) and.(element selection).
|
I have the following C statement:
```
int res = x & (x ^ y);
```
Is there a way to do the same thing, but usingxandyonly one time each?
For example:
```
x | (~x & y) == x | y
```
|
Yes, by expanding the xor (a ^ b == (a & ~b) | (~a & b)), and then simplifying the result, one gets:
```
res = x & ~y;
```
|
```
#include <stdio.h>
int main(void) {
for (int i = 0; i < 5; i++) {
int arr[5] = {0};
// arr gets zeroed at runtime, and on every loop iteration!
printf("%d %d %d %d %d\n", arr[0], arr[1], arr[2], arr[3], arr[4]);
// overwrite arr with non-zero crap!
arr[0] = 3;
a... |
You are creating anewarray at each iteration, so there is no re-initialization.
|
I need a library to list files in archives and to extract archive files. The library should support archive types as much as possible. Do you have any suggestion ?
Any help would be appreciated.
|
This sounds like you are looking for libarchivehttp://libarchive.github.com/
|
I need to convert my string into int array. so i make a loop over string, and callint atoi(char *p)function fromstdlib.h, but it doesn`t working on mac (some times ago i tryed it on Windows, and it workong well). simple loop:
```
for(p = buff; *p; p++)
printf("%d", atoi(p));
```
whats the problem with work of th... |
The function is working perfectly fine. For instance ifbuffcontains"123", your code will print123233.
However it seems you want to just print the value of individual digits, in which caseatoihas nothing to do with your problem. Try:
```
for(p = buff; *p; p++)
printf("%d", *p-'0');
```
|
I hope someone is able to help me.
I have the following algorithm that works both if I have two positive numbers or a positive and a negative number. It doesn't works, however, if both numbers are negative.
Can someone explain me how is it possible?
```
void sum (int p, int q) {
int sum, carry;
carry = 1;
while ... |
The sum of two negative numbers is negative (unless an overflow occurs, as pointed out in a comment). But this code:
```
p = p << 1;
p = p >> 1;
```
is essentially clearing the topmost bit, i.e. the sign bit, so the result of this will never be negative.
|
Where is the definition of thestruct ap_conf_vector_tin Apache sources? Is it generated, where?
|
ap_conf_vector_t seems to be an opaque datatype. This is usually used inthe old daysto define astableapi which the possibility to later change the implementation without changes to the api.
ap_conf_vector_t is only used as a parameter to the api functions like:
ap_get_module_configap_parse_htaccess
You are not supp... |
I came across the below declaration ; what will be the scope of this MACRO ?
```
typedef struct Hdr_s {
#define MACRO1 1
#define MACRO2 2
#define MACRO3 3
unsigned char Flag;
unsigned char Offset;
unsigned short cpy_len_offset;
unsigned char cpy_offset;
}Hdr_t;
```
|
A macro definition remains for the whole remainder of the compilation, and macros aren't scoped.
|
What Windows API function can I use to check to see if the current user running my application has administrative privileges?
Here are my OS details : WINDOWS XP, VISTA and WINDOWS 7Language to be used : C
|
Even if theuserhas administrative privileges it does not meanyour programdoes - it needs to be elevated. This can be done by the user explicitly asking to run it as an administrator, but usually it is requested by the program itself through a manifest that is embedded into the executable. Once the manifest asks for th... |
Once the extra bytes are added for referencing what will happen to these extra bytes while execution. Are these extra bytes empty or what data will be contained in them?
Any help on this is appriciated. Thanks!!!
|
ISO 9899:2011 6.2.6.1/6When a value is stored in an object of structure or union type,
including in a member object, the bytes of the object representation
that correspond to any padding bytes take unspecified values.
It is unspecified behavior, meaning that the compiler may put any value there, including garbage, as... |
I have a serious issue, I want to boot my stm32 discovery board (STM32L152RBT6) using usart. I have tried going into system memory boot mode by putting BOOT0=HIGH and BOOT1=LOW. Then i tried to send my .BIN file using hyperterminal (Nothing happens). I also tried Flash loader utility by ST(It hangs on detecting the ta... |
Download "STMicroelectronics Flash Loader" supposedly this is the software used for programming using USART -I think so- but I wasn't lucky enough as it couldn't connect to my custom board
|
I have the following code:
```
std::string cmd = "sudo chmod a+x file";
int r = system(cmd.c_str());
```
which works correctly.
How can I do the same thing without calling the system() function?
What I can get to is:
```
#include <sys/stat.h>
int r = chmod("file", S_IXUSR | S_IXGRP | S_IXOTH);
```
How can I use ... |
You can't. Unless your program is suid root which is most likely not the case - otherwise you wouldn't use sudo.
However, depending on what your program does, giving it setuid-root might indeed be the way to go. You need to perform operations that require root privileges and sudo access tochmod, especially on arbitra... |
I needed to execute a loop and a condition in every second or in the interval of a few milliseconds. What can I do to achieve this?
|
```
#include <unistd.h>
```
usleepfor POSIX platform (hight precision sleep)
|
Wheneven I go through some tutorials/notes for C, I quite come across the term "objects". I was always wondering what does the object got to do with the procedural language. Going a bit deep I could understand that something occupying a piece of memory is termed as an "object" in c.
My question is whether my understa... |
From thedraft of the C99 Standard:
3.14objectregion of data storage in the execution environment, the contents of which can represent
values
So, you're basically right.
Notes:
an object can have a name:int object = 42;an object can be a part of a larger object:struct tm x; /* (x) and (x.tm_year) are objects */an... |
I'm trying to create/open a file using c. I enter the name using the fgets command, so I can not overflow the buffer, like this:
```
void main() {
printf("Enter file name: ");
char * fileName = (char *) calloc(MAX_BUFFER_SIZE, sizeof(char));
fgets(fileName, MAX_BUFFER_SIZE, stdin);
FILE *inputFile = f... |
The string read byfgetsmight have a newline at the end. You'll have to remove it before you use the string infopen.
How to remove the newline at the end?
|
If I have a macro like:
```
#define MAX_SIZE ((1<<18)-1)
```
I can rest assured that by runtime this math has been done already and MAX_SIZE is a literal.
My question is, what if I use a __builtin function such as:
```
#define BIT_OFFSET (__builtin_clz(MAX_SIZE))
```
does this turn into a constant by run time as ... |
For some values, some machines, and some versions of some compilers, __builtin_clz(constant) will be evaluated at compile time. But there is no guarantee that it will be evaluated at compile time for all values, all machines, and all compilers. Use gcc -S to see what your compiler does on your target machine.
|
I'd like your help with understanding why this function does not stop when I enter any other number than 1.
```
int main(void) {
double sum,v;
while (scanf("%lf",&v)==1) {
printf("\t%.2f\n", sum += v);
}
```
It looks like it's suppose to stop whenever the input would be different from 1. I believe that it is ... |
The functionscanfreturns the number of items matched and filled, not the actual value it read.
Upon successful completion, these functions shall return the number of
successfully matched and assigned input items; this number can be zero
in the event of an early matching failure. If the input ends before
the fir... |
I only seem to be able to receive a max stream size of 8k bytes. It craps out after that. How can I enlarge this? thx
```
host = gethostbyname("xxx");
memcpy(&(sin.sin_addr), host->h_addr, host->h_length);
sin.sin_family = host->h_addrtype;
sin.sin_port = htons(4000);
s = socket(AF_INET, SOCK_ST... |
Here's code to read 64KiB:
```
char* buffer = malloc(65536);
int len = 0;
while (len < 65536)
{
int rc = recv(s, buffer + len, 65536 - len, 0);
if (rc == 0)
break; // connection closed
else if (rc > 0)
len += rc;
else if (errno != EINTR)
{
// handle error
break;
... |
I'm not looking to use something big like QT or wxWidgets' APIs. I just want simple sockets that will work on Android, iOS, Windows, Mac, Linux.
I'm making an event driven card game so TCP would be best.
Essentially, I just want to connect and authenticate clients. After that I just need to be able to send them mess... |
Perhaps try BOOST Asio
http://www.boost.org/doc/libs/1_49_0/doc/html/boost_asio.html
Is that light weight enough?
|
Is it possible to hack the Chrome (more precisely the Webkit's), through an extension, in order to use my own media server instead of Google's one?
It's needed to make realtime voice interactive app and I'm looking to an alternatives instead of doing this in flash or a Java Applet.
|
I found (for my projects) that usingVideoIO.swfandRTMPLiteis far easier and more portable solution.
|
I need to use IP address of the eth0 interface of a PC (Linux OS - IPv4). How can I define it as a constant variable without knowing the IP address in advance?
|
If you have them as pointer to an address buffer you can. Export a pointer toconstqualified type
```
extern your_address_type const*const addr;
```
You'd have to have your library code see something like
```
static your_address_type my_address;
your_address_type const*const addr = &my_address;
```
Inside your libr... |
If I wanted to make a function which takes the name of a struct as an argument, what would the method signature look like?
```
typedef struct Class{
} Class;
main()
{
Class *a = malloc(Class);
return instanceOf(a, Class);
}
```
What would the declaration ofinstanceOflook like?
|
You can't pass types to functions in C. However, you can simulate this behaviour using macros:
```
#define new_instance(t) (malloc(sizeof(t)))
Class *instance = new_instance(Class);
```
|
Where is definition of memcpy function located? It is declared in wchar.h where I can find that
```
/* memcpy and memmove are defined just for use in wmemcpy and wmemmove */
```
then I find only the wmemcpy_s.c on my computer and there is a definition of wmemcpy_s function there, which useswmemcpyfunction which uses... |
It depends on compiler being used. For gcc, a generic memcpy is located at libgcc.a, usually a rep movsb. if optimization is turned on the compiler will try to emit inline version instead, and there are multiple versions of built-in memcpy that is optimized for different situations.
|
How to include jar files of the Android platform when using the javah tool to create a C/C++ .h header file ???
|
Assuming:
your android SDK is installed in C:\android\sdk (and you have downloaded Android 1.5 platform)your android NDK is installed in C:\android\ndk
Open command line window. Go to C:\android\ndk\samples\hello-jni folder. And execute the following:
```
javah -classpath C:\android\sdk\platforms\android-3;src com.... |
I have a problem as stated below:
i have an array(say) a[]={10,24,56,33,22,11,21}
i have something like this
```
for(i=0;i<100;i++){
if(a[i]==10)
// do something
}
```
next when i=1
```
if(a[i]==10 && a[i+1]==24)
```
so on so at each iteration the arguments / conditions within if should be varying
now ... |
You have to have a cumulative "boolean" variable that checks a[i] at the i-th iteration and update that variable:
```
int a[] = {...}; /* array with some values to verify */
int v[] = {...}; /* these are the actual desired values in a[] */
/* the verifying loop */
int i;
int cond = 1;
for (i = 0; i < 100; i++)
{... |
I knowgetppidretrieves the parent pid of the underlying program, but how can you tell this out of that program? I can't find anything useful in/proc/[pid], or is there any useful API that i can use?
UPDATE
I mean , i'm inspecting these procress with another process , so getppid won't work here
|
It is the fourth field in /proc/[pid]/stat. It is documented in the man pageproc(5).
|
I knowpscommand can see this , but given the pid , how can one know which user started that program ? I see aloginuidin /proc/[pid]/ , but that seems to be a complemental-code of the real uid , not sure.
|
How aboutstatus?
```
cnicutar@lemon:/proc/self$ cat status
Name: bash
State: S (sleeping)
#....
Uid: 1000 1000 1000 1000
Gid: 1000 1000 1000 1000
```
There are 4 UIDs: Real, effective, saved set, and file system. It's all described inproc(5).
|
I am trying tommapsome large files but failed : I can't mmap any file that's larger than around 2.7 GB.
By doingulimit -a, it says my virtual memory is unlimited. I then didcat /proc/meminfoit says my system has 3GB Memfree and 2GB Swapfree.
I am assuming I could mmap a file up to 5GB. I tried everything I learned o... |
You need to use 64 bit OS, because 32bit os does not have enough address space.Edit: Although your system has some physical memory available, but a 32 bit process only address up to 4GB, kernel reserve about 1-2GB for kernel driver..., so user space usually has 2GB for 32 bit applications.
|
I'm writing a service in "C" and I'd like to display a warning window once the user tries to stop the service ( With "OK" and "Cancel" Buttons ).
Is there any specific windows API available to achieve this?
Any other simple ways are there to achieve??
|
No, this is not possible. Windows services are unable to interact directly with the user's desktop, so they will be unable to show a user interface of any kind.
This shouldn't really be a big deal, though. You have to have adequate permissions to stop and start a service, and by default, only Administrators have thos... |
I know some difference between char* and char[].char x[] = "xxxx"Is an array of chars;char *y = "xxxx"is a pointer to the literal (const) string;
Andx[4]=='\0', and*(y+4) == '\0'too.
So whysizeof(x)==5andsizeof(y)==4?
|
char x[] = "xxxx"is an array of size 5 containing x x x x and \0.
char *y = "xxxx"is a pointer to a string. It's length is 4 bytes, because that is the length of the pointer, not the string.
|
One of my questions, as I'm pretty new to C is about ways to avoid getting the duplication error. Basically, when I build the project in Netbeans if I have the file in the project and also include it, I get that error.
Defining the functions static, is a correct way to avoid it? What other solutions are there? Thanks... |
.c/.cppfiles shouldn't be included.
Move declarations to a common header file and include that.
|
Say I have this file:http://www.example.com/somepic.png
Is there a cross platform C or C++ library that could easily allow me to download it to a specified directory?
Thanks
|
You can uselibcurlto do this.
|
I knowgetppidretrieves the parent pid of the underlying program, but how can you tell this out of that program? I can't find anything useful in/proc/[pid], or is there any useful API that i can use?
UPDATE
I mean , i'm inspecting these procress with another process , so getppid won't work here
|
It is the fourth field in /proc/[pid]/stat. It is documented in the man pageproc(5).
|
I knowpscommand can see this , but given the pid , how can one know which user started that program ? I see aloginuidin /proc/[pid]/ , but that seems to be a complemental-code of the real uid , not sure.
|
How aboutstatus?
```
cnicutar@lemon:/proc/self$ cat status
Name: bash
State: S (sleeping)
#....
Uid: 1000 1000 1000 1000
Gid: 1000 1000 1000 1000
```
There are 4 UIDs: Real, effective, saved set, and file system. It's all described inproc(5).
|
I am trying tommapsome large files but failed : I can't mmap any file that's larger than around 2.7 GB.
By doingulimit -a, it says my virtual memory is unlimited. I then didcat /proc/meminfoit says my system has 3GB Memfree and 2GB Swapfree.
I am assuming I could mmap a file up to 5GB. I tried everything I learned o... |
You need to use 64 bit OS, because 32bit os does not have enough address space.Edit: Although your system has some physical memory available, but a 32 bit process only address up to 4GB, kernel reserve about 1-2GB for kernel driver..., so user space usually has 2GB for 32 bit applications.
|
I'm writing a service in "C" and I'd like to display a warning window once the user tries to stop the service ( With "OK" and "Cancel" Buttons ).
Is there any specific windows API available to achieve this?
Any other simple ways are there to achieve??
|
No, this is not possible. Windows services are unable to interact directly with the user's desktop, so they will be unable to show a user interface of any kind.
This shouldn't really be a big deal, though. You have to have adequate permissions to stop and start a service, and by default, only Administrators have thos... |
I know some difference between char* and char[].char x[] = "xxxx"Is an array of chars;char *y = "xxxx"is a pointer to the literal (const) string;
Andx[4]=='\0', and*(y+4) == '\0'too.
So whysizeof(x)==5andsizeof(y)==4?
|
char x[] = "xxxx"is an array of size 5 containing x x x x and \0.
char *y = "xxxx"is a pointer to a string. It's length is 4 bytes, because that is the length of the pointer, not the string.
|
One of my questions, as I'm pretty new to C is about ways to avoid getting the duplication error. Basically, when I build the project in Netbeans if I have the file in the project and also include it, I get that error.
Defining the functions static, is a correct way to avoid it? What other solutions are there? Thanks... |
.c/.cppfiles shouldn't be included.
Move declarations to a common header file and include that.
|
Say I have this file:http://www.example.com/somepic.png
Is there a cross platform C or C++ library that could easily allow me to download it to a specified directory?
Thanks
|
You can uselibcurlto do this.
|
I don't know very much about template programming, and I currently use gsl. I'm interested in seeing if Eigen can be use in C. Has anybody used Eigen in C before? Is there something I can test to find out if it will be easy?
|
Since Eigen is a C++ template library, it cannot be directly used with C.
Hypothetically, one could wrap the C++ templates into a C API, and use that. However, that's bound to involve a lot of work and would strike me as a bit pointless (one might as well use existing C libraries for linear algebra).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.