question
stringlengths
25
894
answer
stringlengths
4
863
I am trying to generate some numbers with the rand() function like below: ``` int main() { int i=0 for(i=0;i<20;i++) { printf("%f\n",rand_md()); } return 0; } float rand_md() { return (float)rand()/(RAND_MAX+1.0); } ``` But when I run gcc rand.c, I get the error like below: rand.c: In function ‘main’: rand.c:21: warning: format ‘%f’ expects type ‘double’, but argument 2 has type ‘int’ rand.c: At top level: rand.c:36: error: conflicting types for ‘rand_md’ rand.c:21: error: previous implicit declaration of ‘rand_md’ was here What's wrong with my code? Best Regards,
When you use a function without declaring it first, C will assume it returns anint. To fix this, you have to declare the method signature forrand_mdbefore you call it inmain(). Add something like this beforemainor in a header file: ``` float rand_md(); ```
When I use chdir() to change the current working directory, why doesn't the getenv("PWD") give the present working directory? Do I need to setenv("PWD",newDir,1) also? ``` void intChangeDir(char *newDir) { if( chdir(newDir)==0 ) { printf("Directory changed. The present working directory is \"%s\" \"%s\"\n",getenv("PWD"),getcwd(NULL,0)); } else { printf("Error changing dir %s\n",strerror(errno)); } } ``` Output: (location of the executable is /home/user) changedir /boot Directory changed. The present working directory is "/home/user" "/boot"
Yes, if you want to change the environment variable, you have to explicitly do that. It's shell that sets and updatesPWDin the normal run of events, so it only reflects changes of the current directory known to the shell.
Can I compare anintand asize_tvariable like this: ``` int i = 1; size_t y = 2; if (i == y) { // Do something } ``` Or do I have to type cast one of them?
It's safe provided theintis zero or positive. If it's negative, andsize_tis of equal or higher rank thanint, then theintwill be converted tosize_tand so its negative value will instead become a positive value. This new positive value is then compared to thesize_tvalue, which may (in a staggeringly unlikely coincidence) give a false positive. To be truly safe (and perhaps overcautious) check that theintis nonnegative first: ``` /* given int i; size_t s; */ if (i>=0 && i == s) ``` and to suppress compiler warnings: ``` if (i>=0 && (size_t)i == s) ```
I'm not able to understand some typecasting syntaxes. For eg. ``` float f=7.0; short s=*(short *)&f; ``` What's happening hereshort s=*(short *)&f? Looks like we're castingsomethingas a pointer to a short and then initializingsto value stored in the address pointed to bysomething. Now, thissomethinglooks like the address of variablef. So ifsomething=address of f, it appears to me that we are makingaddress of fas a pointer to some short and then de-referencing it. I know that what I've stated is wrong, but I just can't seem to visualize it. Thanks.
This syntax would make the most sense ifshortwas the same size asfloatand even so, there would remain a problem with "strict aliasing rules". It is used to interpret the bits of thefloatf as representing an integer. It is used to circumvent the fact thats = (short) f;would be interpreted as aconversionto integer. Truncation, I believe.
I want to basically create a light that will make it so that its very bright around the player then gets progressively darker. Sort of like a fire torch. How can I get this effect? I can only seem to get an ambient light? How can it follow the camera? Thanks
It sounds like what you are looking for is known as a point light. If you are using fixed function, the following tutorial may be use to you:http://jerome.jouvie.free.fr/OpenGl/Tutorials/Tutorial13.php Just note that this tutorial appears to use jogl with Java, but the conversion to C++ should be relatively straightforward. For a glsl implementation, Lighthouse3d has a tutorial for GLSL 1.2 implementation of point lights.
Below are 2 programs First ``` #include<stdio.h> void main() { int a[5]={1,2,3,4,5}; int *p; p=&a; printf("%u %u",p,p+1); } ``` Second ``` #include<stdio.h> void main() { int a[5]={1,2,3,4,5}; printf("%u %u",&a,&a+1); } ``` Now, in the two programs..I have printed the values of &a using p in first code and directly in the second.. Why are the results different? the answer i m getting are. ``` for first 3219048884 3219048888 for second 3219048884 3219048904 ```
The type of&aisint (*) [5]. Therefore&a+1is a pointer that's 5ints further on thana. However the type ofpisint *, thereforep+1is a pointer that's 1intfurther on thanp.
``` #include<stdio.h> void main() { char *p="nyks"; p[2]='n'; printf("%s",p); } ``` This crashes with aSEGMENTATION FAULT. Can someone explain why?
It is undefined behavior to try to overwrite a string literal. C99 §6.4.5/6: If the program attempts to modify such an array, the behavior is undefined. This is restated in Appendix J.2 (undefined behavior). If you instead do: ``` char p[] = "nyks"; ``` you can allocate and initialize an automatic (stack) character array. In that case, it is perfectly fine to modify elements.
``` int main() { ... if(!fork()) { execvp(cmdName,cmdParam); } printf("In main()..."); return(0); } ``` Assuming I have correctly passed the cmdName & cmdParam arguments, how do I wait for the process created by execvp to finish, before resuming the execution of main()?Does the execvp() create a process which is a child of the newly fork()ed process?
In the parent process,forkreturns the PID of the child process, so you can store that in a variable, and then usewaitpidto wait for the child process to terminate.Not really - the new child process created byforkis a duplicate of the parent, andexecvpthen replaces its process image with a new image. Effectively you initially have two 'copies' of the parent, one of which then 'becomes' the new program.
I am looking for existing implementations of different types of DES in C/C++/C##. My running platform is Windows XP/Vista/7. I am trying to write a C# program which will encrypt and decrypt using the DES algorithm. I need some implementations with which i can verify my code output to see if i did the things in right order. For the implementations the code along with the executable will be good however not a must.
Nearly all open source C/C++ crypto libraries implement DES. You could for instance use OpenSSL, PolarSSL, LibTomCrypt, Crypto++, or any other library of your choosing for testing/experimentation. In C# there seem to be fewer options, simply because the default .NET crypto libraries somewhat inhibit the desire for anyone else to compete in this space, butBouncyCastle's C# code(http://www.bouncycastle.org/csharp/index.html) does contain an implementation (in src/crypto/engines/DesEngine.cs).
how can i use POSIX header files in system programming? i used in C. what are other header files i can used?
POSIX is a standard implemented by Unix-like systems to give code portability between similar systems. You include their headers like you do any other C header. These headers should be available in the libraries on your Unix-like machine. You can then have access to the data structures in them. Here is a (partial?) list of POSIX headers:http://en.wikipedia.org/wiki/C_POSIX_library Hopefully this helps. Your question is very poorly worded.
While reading about memmove I read that it can handleMEMORY OVERLAPSbut I am unable to get how a memmory overlap can occur between two strings and how can this function still copy the block of memory correctly.
"Memory overlap" does not occur by itself. It is you who can supply thememmovefunction with memory regions that overlap. Take two pointers intothe samearray and you can easily end up with overlapping memory regions. Of course, you can also easily create overlapping objects through unions. It is not clear what you mean by the second part of the question ("how can this function still copy the block of memory correctly"). Where do you see the problem here?
I have been trying to figure out how can we print a array hellically but i am stuck on how to get started.Any algorithms or ideas will be very helpful.ThanksHELLICALLYmeans printing the array in concentric circular shape
If I'm interpreting what you're saying correctly, you want to print the contents of an array, but in a spiral. I would start by allocating a big rectangular block of memory (a 2-D array) and initializing it to zero. This represents the screen. Then devise a function for determining the coordinates of the next point in the circle and make some coordinate variables initialized to the origin point. Fill the screen by dropping array members wherever they go. Print out the screen-array, one row at a time, but substitute space for zero. Screen size and next-coordinate-function are left as exercises for the reader.
This question already has answers here:Closed13 years ago. Possible Duplicate:How would you set a variable to the largest number possible in C? Can we find the maximum size of a data type in C langauge?
If you want to know the maximum and minimum values you can store in a variable of a given data type, you can check with these different constants: LONG_MIN, LONG_MAX, seehere, for the rest.
Is there a way that you can assign memory from heap without a call to malloc? Can the following call be affective for it? ``` void* loc = (void*) &heap[end_of_heap]; ```
No. The C language itself provides no such functionality. If you only care about Unix systems conforming to a deprecated feature of an old version of the Unix standard (SUSv2 or earlier, if I remember correctly), thebrkandsbrkfunctions provide this functionality. But you really should not use it unless you're writing very low-level code that will never need to be portable.
I have a number of arrays ``` double foo[][2] = { {1.0,3.0}, {2.6,10.0}, {0.0,0.0} }; double bar[][2] = { {1.4,3.2}, {2.1,9.9}, {2.1,9.9}, {2.1,9.9}, {0.0,0.0} }; ``` So these are both of type: ``` double (*)[2] ``` I want to make an array of these so I need to declare an array of type pointer to array[2] ``` double ((*array)[2])[] = {foo, bar}; ``` This syntax doesn't work - is it possible to do this in C. I also tried to create a type but this didn't work either: ``` typedef double *mytype[2] ; mytype array[] = {foo, bar}; ```
The two arrays are not of typedouble(*)[2].foois of typedouble [3][2]and bar is of typedouble [5][2]. The outer array size is implied, not absent. To create an array of these, use them as pointers, thus: ``` typedef double (*mytype)[2]; mytype array[] = { foo, bar }; ```
This question already has answers here:Closed13 years ago. Possible Duplicate:C preprocessor and concatenation can anybody explain with example ?
It allows to construct indentifiers from their parts. Eg: ``` #define CLASS_NAME(name) CLASS__ ## name ``` would expandCLASS_NAME(alpha)toCLASS__alpha. It is vastly used in tricks used by the boost preprocessor library, eg. ``` #define IF0(a, b) b #define IF1(a, b) a #define IF(cond, a, b) IF ## cond(a, b) ``` which would expandIF(0, a, b)toaandIF(1, a, b)tob. Also, sometimes, it is used to generate struct and function names (akin to c++ templates).
What is a platform-independent way of specifying the largest representablenegativefloating-point number? We found an algorithm that broke when run on a PS3's SPU, but worked fine when compiled for the PPU: ``` float x = -FLT_MAX; /* stuff */ if (x > 0.0f) { // If x is unchanged, code is executed on SPU } ``` Essentially, is there a well-defined negative equivalent ofFLT_MAX?
You wantstd::numeric_limits::lowest(), but it is c++0x only, so not very cross platform at the moment. You definitely don't wantstd::numeric_limits::min()- that is smallest magnitude, not furthest negative. If you want something that will always be less than all other doubles, use-numeric_limits<double>::infinity().
Right now I'm panning by glRotating before rendering everything, and i'm moving the camera by gltranslating. I feel as if this is wrong since im essentially moving the scene, not the camera. What is the proper way to move the camera? Thanks
Actually 'moving the scene around the camera' is the proper way in OpenGL. This is due to the fact that OpenGL combines the view and model matrices into the modelview matrix. (lookherefor more details) Obvious the lookat function (as mentioned above) is an easy way to move a (virtual) camera but i found that it doesn't work for OpenGL3. I'd suggest to use the excellentglm libraryto setup the transformation matrices for OpenGL3. Kind Regards, Florian
Trying to use make from cygwin using g++ I was getting Access Denied error messages. Googling the error message I found a positing referring to g++-3 and gcc-3http://www.linuxquestions.org/questions/linux-software-2/cygwin-g-3-exe-gcc-3-exe-corrupted-to-g-3-exe-dam-and-gcc-3-exe-dam-769722/)... Changing the compiler to g++-3 seems to fix the problem although I cannot find much information about both g++-3 and gcc-3. Any ideas where I can find more information about them>
To answer your point in the comment to Pete's answer, thegccyou type on the terminal is just a symlink to the actual gcc binary. It makes it easy to upgrade since you can just point the symlink to something else. ``` $ which gcc /usr/bin/gcc $ ll /usr/bin/gcc lrwxrwxrwx 1 root root 7 2010-09-01 11:10 /usr/bin/gcc -> gcc-4.4* ```
I need to kill such user processes that are taking longer time than a said expected interval on UNIX (Solaris) operating system. This needs to be done inside the process that is currently being executed. Please suggest how this can be achieved in C or in UNIX?
See thealarm()system call. It provides you with aSIGALRMsignal which your process can handle, and use to quit.
the following code: ``` signed char sc = ~0xFC; unsigned char uc = ~0xFC; ``` when compiled gives me the following warnings: ``` integer conversion resulted in truncation integer conversion resulted in truncation ``` why do i get these warningshow do i write my code, so that i dont get these warnings (without using #pragmas) thanx, i'm using IAR Compiler for 8051, do you get similar warnings when compiling using other compilers?
Because hexadecimal literals are considered int when written like you did0xFC.. to avoid the warning just cast them to truncate the number to just 1 byte: ``` ~((char) 0xFC) ``` 0xFCis considered0x000000FCon a 32 bit architecture, so when you apply not you obtain0xFFFFFF03, this means that when you assign this result to a char the 3 most relevant bytes are just discarded and the compiler warns you about it.
I'm looking for an R-Tree implementation, in C, Objective-c and even C++, which shall be efficient for searching the 2d rectangle in which a point falls ( memory efficiency would also be great, but I can sacrifice a bit more memory for time even while I am on an iPhone ). A good documentation will be appreciated too
Check outthis page, it provides implementations (in C, C++, Java, etc.) for several variants (R*, R+, etc.).
When I use chdir() to change the current working directory, why doesn't the getenv("PWD") give the present working directory? Do I need to setenv("PWD",newDir,1) also? ``` void intChangeDir(char *newDir) { if( chdir(newDir)==0 ) { printf("Directory changed. The present working directory is \"%s\" \"%s\"\n",getenv("PWD"),getcwd(NULL,0)); } else { printf("Error changing dir %s\n",strerror(errno)); } } ``` Output: (location of the executable is /home/user) changedir /boot Directory changed. The present working directory is "/home/user" "/boot"
Yes, if you want to change the environment variable, you have to explicitly do that. It's shell that sets and updatesPWDin the normal run of events, so it only reflects changes of the current directory known to the shell.
Can I compare anintand asize_tvariable like this: ``` int i = 1; size_t y = 2; if (i == y) { // Do something } ``` Or do I have to type cast one of them?
It's safe provided theintis zero or positive. If it's negative, andsize_tis of equal or higher rank thanint, then theintwill be converted tosize_tand so its negative value will instead become a positive value. This new positive value is then compared to thesize_tvalue, which may (in a staggeringly unlikely coincidence) give a false positive. To be truly safe (and perhaps overcautious) check that theintis nonnegative first: ``` /* given int i; size_t s; */ if (i>=0 && i == s) ``` and to suppress compiler warnings: ``` if (i>=0 && (size_t)i == s) ```
I'm not able to understand some typecasting syntaxes. For eg. ``` float f=7.0; short s=*(short *)&f; ``` What's happening hereshort s=*(short *)&f? Looks like we're castingsomethingas a pointer to a short and then initializingsto value stored in the address pointed to bysomething. Now, thissomethinglooks like the address of variablef. So ifsomething=address of f, it appears to me that we are makingaddress of fas a pointer to some short and then de-referencing it. I know that what I've stated is wrong, but I just can't seem to visualize it. Thanks.
This syntax would make the most sense ifshortwas the same size asfloatand even so, there would remain a problem with "strict aliasing rules". It is used to interpret the bits of thefloatf as representing an integer. It is used to circumvent the fact thats = (short) f;would be interpreted as aconversionto integer. Truncation, I believe.
I want to basically create a light that will make it so that its very bright around the player then gets progressively darker. Sort of like a fire torch. How can I get this effect? I can only seem to get an ambient light? How can it follow the camera? Thanks
It sounds like what you are looking for is known as a point light. If you are using fixed function, the following tutorial may be use to you:http://jerome.jouvie.free.fr/OpenGl/Tutorials/Tutorial13.php Just note that this tutorial appears to use jogl with Java, but the conversion to C++ should be relatively straightforward. For a glsl implementation, Lighthouse3d has a tutorial for GLSL 1.2 implementation of point lights.
Below are 2 programs First ``` #include<stdio.h> void main() { int a[5]={1,2,3,4,5}; int *p; p=&a; printf("%u %u",p,p+1); } ``` Second ``` #include<stdio.h> void main() { int a[5]={1,2,3,4,5}; printf("%u %u",&a,&a+1); } ``` Now, in the two programs..I have printed the values of &a using p in first code and directly in the second.. Why are the results different? the answer i m getting are. ``` for first 3219048884 3219048888 for second 3219048884 3219048904 ```
The type of&aisint (*) [5]. Therefore&a+1is a pointer that's 5ints further on thana. However the type ofpisint *, thereforep+1is a pointer that's 1intfurther on thanp.
``` #include<stdio.h> void main() { char *p="nyks"; p[2]='n'; printf("%s",p); } ``` This crashes with aSEGMENTATION FAULT. Can someone explain why?
It is undefined behavior to try to overwrite a string literal. C99 §6.4.5/6: If the program attempts to modify such an array, the behavior is undefined. This is restated in Appendix J.2 (undefined behavior). If you instead do: ``` char p[] = "nyks"; ``` you can allocate and initialize an automatic (stack) character array. In that case, it is perfectly fine to modify elements.
``` int main() { ... if(!fork()) { execvp(cmdName,cmdParam); } printf("In main()..."); return(0); } ``` Assuming I have correctly passed the cmdName & cmdParam arguments, how do I wait for the process created by execvp to finish, before resuming the execution of main()?Does the execvp() create a process which is a child of the newly fork()ed process?
In the parent process,forkreturns the PID of the child process, so you can store that in a variable, and then usewaitpidto wait for the child process to terminate.Not really - the new child process created byforkis a duplicate of the parent, andexecvpthen replaces its process image with a new image. Effectively you initially have two 'copies' of the parent, one of which then 'becomes' the new program.
I am looking for existing implementations of different types of DES in C/C++/C##. My running platform is Windows XP/Vista/7. I am trying to write a C# program which will encrypt and decrypt using the DES algorithm. I need some implementations with which i can verify my code output to see if i did the things in right order. For the implementations the code along with the executable will be good however not a must.
Nearly all open source C/C++ crypto libraries implement DES. You could for instance use OpenSSL, PolarSSL, LibTomCrypt, Crypto++, or any other library of your choosing for testing/experimentation. In C# there seem to be fewer options, simply because the default .NET crypto libraries somewhat inhibit the desire for anyone else to compete in this space, butBouncyCastle's C# code(http://www.bouncycastle.org/csharp/index.html) does contain an implementation (in src/crypto/engines/DesEngine.cs).
how can i use POSIX header files in system programming? i used in C. what are other header files i can used?
POSIX is a standard implemented by Unix-like systems to give code portability between similar systems. You include their headers like you do any other C header. These headers should be available in the libraries on your Unix-like machine. You can then have access to the data structures in them. Here is a (partial?) list of POSIX headers:http://en.wikipedia.org/wiki/C_POSIX_library Hopefully this helps. Your question is very poorly worded.
While reading about memmove I read that it can handleMEMORY OVERLAPSbut I am unable to get how a memmory overlap can occur between two strings and how can this function still copy the block of memory correctly.
"Memory overlap" does not occur by itself. It is you who can supply thememmovefunction with memory regions that overlap. Take two pointers intothe samearray and you can easily end up with overlapping memory regions. Of course, you can also easily create overlapping objects through unions. It is not clear what you mean by the second part of the question ("how can this function still copy the block of memory correctly"). Where do you see the problem here?
I have been trying to figure out how can we print a array hellically but i am stuck on how to get started.Any algorithms or ideas will be very helpful.ThanksHELLICALLYmeans printing the array in concentric circular shape
If I'm interpreting what you're saying correctly, you want to print the contents of an array, but in a spiral. I would start by allocating a big rectangular block of memory (a 2-D array) and initializing it to zero. This represents the screen. Then devise a function for determining the coordinates of the next point in the circle and make some coordinate variables initialized to the origin point. Fill the screen by dropping array members wherever they go. Print out the screen-array, one row at a time, but substitute space for zero. Screen size and next-coordinate-function are left as exercises for the reader.
This question already has answers here:Closed13 years ago. Possible Duplicate:How would you set a variable to the largest number possible in C? Can we find the maximum size of a data type in C langauge?
If you want to know the maximum and minimum values you can store in a variable of a given data type, you can check with these different constants: LONG_MIN, LONG_MAX, seehere, for the rest.
Is there a way that you can assign memory from heap without a call to malloc? Can the following call be affective for it? ``` void* loc = (void*) &heap[end_of_heap]; ```
No. The C language itself provides no such functionality. If you only care about Unix systems conforming to a deprecated feature of an old version of the Unix standard (SUSv2 or earlier, if I remember correctly), thebrkandsbrkfunctions provide this functionality. But you really should not use it unless you're writing very low-level code that will never need to be portable.
I have a number of arrays ``` double foo[][2] = { {1.0,3.0}, {2.6,10.0}, {0.0,0.0} }; double bar[][2] = { {1.4,3.2}, {2.1,9.9}, {2.1,9.9}, {2.1,9.9}, {0.0,0.0} }; ``` So these are both of type: ``` double (*)[2] ``` I want to make an array of these so I need to declare an array of type pointer to array[2] ``` double ((*array)[2])[] = {foo, bar}; ``` This syntax doesn't work - is it possible to do this in C. I also tried to create a type but this didn't work either: ``` typedef double *mytype[2] ; mytype array[] = {foo, bar}; ```
The two arrays are not of typedouble(*)[2].foois of typedouble [3][2]and bar is of typedouble [5][2]. The outer array size is implied, not absent. To create an array of these, use them as pointers, thus: ``` typedef double (*mytype)[2]; mytype array[] = { foo, bar }; ```
This question already has answers here:Closed13 years ago. Possible Duplicate:C preprocessor and concatenation can anybody explain with example ?
It allows to construct indentifiers from their parts. Eg: ``` #define CLASS_NAME(name) CLASS__ ## name ``` would expandCLASS_NAME(alpha)toCLASS__alpha. It is vastly used in tricks used by the boost preprocessor library, eg. ``` #define IF0(a, b) b #define IF1(a, b) a #define IF(cond, a, b) IF ## cond(a, b) ``` which would expandIF(0, a, b)toaandIF(1, a, b)tob. Also, sometimes, it is used to generate struct and function names (akin to c++ templates).
What is a platform-independent way of specifying the largest representablenegativefloating-point number? We found an algorithm that broke when run on a PS3's SPU, but worked fine when compiled for the PPU: ``` float x = -FLT_MAX; /* stuff */ if (x > 0.0f) { // If x is unchanged, code is executed on SPU } ``` Essentially, is there a well-defined negative equivalent ofFLT_MAX?
You wantstd::numeric_limits::lowest(), but it is c++0x only, so not very cross platform at the moment. You definitely don't wantstd::numeric_limits::min()- that is smallest magnitude, not furthest negative. If you want something that will always be less than all other doubles, use-numeric_limits<double>::infinity().
Right now I'm panning by glRotating before rendering everything, and i'm moving the camera by gltranslating. I feel as if this is wrong since im essentially moving the scene, not the camera. What is the proper way to move the camera? Thanks
Actually 'moving the scene around the camera' is the proper way in OpenGL. This is due to the fact that OpenGL combines the view and model matrices into the modelview matrix. (lookherefor more details) Obvious the lookat function (as mentioned above) is an easy way to move a (virtual) camera but i found that it doesn't work for OpenGL3. I'd suggest to use the excellentglm libraryto setup the transformation matrices for OpenGL3. Kind Regards, Florian
Trying to use make from cygwin using g++ I was getting Access Denied error messages. Googling the error message I found a positing referring to g++-3 and gcc-3http://www.linuxquestions.org/questions/linux-software-2/cygwin-g-3-exe-gcc-3-exe-corrupted-to-g-3-exe-dam-and-gcc-3-exe-dam-769722/)... Changing the compiler to g++-3 seems to fix the problem although I cannot find much information about both g++-3 and gcc-3. Any ideas where I can find more information about them>
To answer your point in the comment to Pete's answer, thegccyou type on the terminal is just a symlink to the actual gcc binary. It makes it easy to upgrade since you can just point the symlink to something else. ``` $ which gcc /usr/bin/gcc $ ll /usr/bin/gcc lrwxrwxrwx 1 root root 7 2010-09-01 11:10 /usr/bin/gcc -> gcc-4.4* ```
I need to kill such user processes that are taking longer time than a said expected interval on UNIX (Solaris) operating system. This needs to be done inside the process that is currently being executed. Please suggest how this can be achieved in C or in UNIX?
See thealarm()system call. It provides you with aSIGALRMsignal which your process can handle, and use to quit.
the following code: ``` signed char sc = ~0xFC; unsigned char uc = ~0xFC; ``` when compiled gives me the following warnings: ``` integer conversion resulted in truncation integer conversion resulted in truncation ``` why do i get these warningshow do i write my code, so that i dont get these warnings (without using #pragmas) thanx, i'm using IAR Compiler for 8051, do you get similar warnings when compiling using other compilers?
Because hexadecimal literals are considered int when written like you did0xFC.. to avoid the warning just cast them to truncate the number to just 1 byte: ``` ~((char) 0xFC) ``` 0xFCis considered0x000000FCon a 32 bit architecture, so when you apply not you obtain0xFFFFFF03, this means that when you assign this result to a char the 3 most relevant bytes are just discarded and the compiler warns you about it.
I'm looking for an R-Tree implementation, in C, Objective-c and even C++, which shall be efficient for searching the 2d rectangle in which a point falls ( memory efficiency would also be great, but I can sacrifice a bit more memory for time even while I am on an iPhone ). A good documentation will be appreciated too
Check outthis page, it provides implementations (in C, C++, Java, etc.) for several variants (R*, R+, etc.).
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed8 years ago.Improve this question Are there any open source C Library (not c++) for Windows Driver Development ? I am developing a network device driver that need some functionality such as RegEx, string manipulation, Object Oriented by C and XML and so on... thanks.
Not aware of any real regular expression libraries. However, depending on what you needFsRtlIsNameInExpressionmay be of some interest. There's plenty of string manipulation functions in theSafe String Libraries, they just have names that are different to the libc equiavalents.
I have written a source code with a time delay.In unix I have used the #include <unistd.h>header file andusleepfunction. What is the equivalent to this on windows? What library and function should I use if I write the same code on windows.
``` #include <windows.h> ``` and ``` ::Sleep( 1000 /* milliseconds */ ); ```
In Linux if we call blockingrecvfrom one thread and close for the same socket from another thread,recvdoesn't exit. Why?
The "why" is simply that that's how it works, by design. Within the kernel, therecv()call has calledfget()on thestruct filecorresponding to the file descriptor, and this will prevent it from being deallocated until the correspondingfput(). You will simply have to change your design (your design is inherently racy anyway - for this to happen, you must have no locking protecting the file descriptor in userspace, which means that theclose()could have happened justbeforetherecv()call - and the file descriptor even been reused for something else). If you want to wake up another thread that's blocking on a file descriptor, you should have it block onselect()instead, with a pipe included in the file descriptor set that can be written to by the main thread.
What are some common general purpose library as Boost is to C++ but for C? It should be a cross-platform library and include collections such as trees, linked-lists, queues, etc... What are the advantages/disadvantages to those libraries?
glibis pretty nice because: liberally licensed (LGPL)constant developmenttons of data structurestreeslistsqueuescachesetc.good documentationlots of sample codedevelopment "assistance"loggingthread abstractionthread poolstest frameworktimersUnicode supportmany supported platformsregular expressionstons more...
I see a lot of templates and complicated data structures for implementing a circular buffer. How do I code a simple integer circular buffer for 5 numbers? I'm thinking in C is the most straightforward? Thanks.
Have an array,buffer, of 5 integers. Have an indexindto the next element. When you add, do ``` buffer[ind] = value; ind = (ind + 1) % 5; ```
How to complete disable Drag'n Drop from a GtkEntry ?
I'd discovered that if you set the propertygtk-dnd-drag-thresholdto a value larger than the screen size, it will block the DnD for the whole application.
This question already has answers here:Closed13 years ago. Possible Duplicate:Smart pointers/safe memory management for C? I have an embedded application where I am allocating an object in dynamic memory and passing it around to other modules. I would like to create a smart pointer to this object. There are many examples in C++ for using and implementing smart pointers. I am looking for a C language only implementation of a smart pointer. Thanks.
Yes, I think it's impossible (or at least, not as useful) because of what @KennyTM says. Smart pointers are possible because of constructors and destructors being automatically called. Otherwise you'll have to call reference() and unreference() yourself. Still useful? Also, see this previous, very related SO question:Smart pointers/safe memory management for C?
I wrote a Python extension in C, and my python program uses that extension. In order for it to work, I would have to install the extension on the user's system before my program can run. Is there a way to bypass that installation step and somehow just have the extension in my python package? The only compiled part obviously is the extension (since it's in C).
You can avoid having some one to install it independently but you can not avoid installation completely. If his computing platform differs from yours, he will have to build the extension. What can be done is that you setup a package distribution using distutils. This way the package could be installed or built. You can include the "C" extension in your package. For some standard platform, you can then provide binary package distribution. The user should have the ability to rebuild, if the binary package is not working out for him.
I have learnt C and Assembly(IA32) on Linux and I will also be learning a few more languages this year. I want to make my fundamentals strong and for that I need some tips from you guys as in,where will I find programs for practice?so that I solve them and get more and more experience. Any goodweb linksthat would help a novice programmer to improve and be confident about the language he/she is learning. I try looking up for questions on websites but they are either too difficult or not meant for beginners.I want some source which would help me to be more clear fundamentally and conceptually. Thankyou.
You could start by coding some of the simplerProject Eulerproblems in C, and then translate them to assembly. The problems get progressively more challenging as you go.
I have a "pointer" which keeps incrementing and I need to return the "head" of the pointer finally. I am in a dilemma to use either "pointer[0]" or have another variable called "head" and initialize it and return at the end. The former I feel makes the code looks soiled and later costs little memory. Any clean suggestion?
You will always need two variables: ``` Foo *head = getSomeList(); Foo *tail = head; while (tail->isValid()) ++tail; // You have head and tail here ``` You cannot really implement it much differently becausetail[0] != head(unless the list is empty). Showing the code and telling us what exactly you try to achieve might lead to better answers.
I have to write a program in C which, given the name of a day, returns all of the dates in this month that the day will be on. For example, if the input is "Sunday" the output should be:5,12,19,26(which are the days Sunday will be on this month.) Does any one have any idea how to do this? I have tried a lot.
You can use the time() function to get the current time. Then use the localtime() function to get a struct (struct tm) with the information (year, month, day, ...) of the current time. From the "struct tm" get the tm_mday and the tm_wday. Use these fields to determine the next or previous sunday. e.g. if tm_mday is 12, and tm_wday is 3 (wednesday), then we now that the 9th of this month is a sunday (12-3 = 9). From that number simply add or subtract 7 to get all other sundays.
I am of late working on gcc compiler. whenevr i m compiling my code, m encountering problem with declaration of structure. How to tackle this problem. Do i need to write the syntax differently in gcc?. if yes, how? please suggest something.
I am reasonably sure gcc conforms to C standards, for a more succinct explanation than one found in the standard, please, turn to pages 148-150 ofC: A Reference Manual. So something simple like this linked list element: ``` struct foo { int a; float b; char *s; struct foo *next; } my_struct; ``` should work. If your needs are more complex.. then you should post your non-working example. EDIT: If you don't have access to CAR then this will suffice for now:http://publications.gbdirect.co.uk/c_book/chapter6/structures.html(obviously not C99)
I wonder in which language Chromium OS is written.I guess they have used C/C++ but did they put something different (Go)? Did they used Assembly for low level code as I know that they had to change some things to make booting a lot faster?
Poke around/etc/in Chromium, and you'll quickly see it is mostly Ubuntu; Google contracted with Canonical to do the majority of the work. It boots quickly because it doesn't do much. :) I'm sure there's more to it than that, but restricting what the system can do is a great way to reduce the boot speed problem to something more tractable.
C parent program does some processing and allocates memory, then calls execvp(). What will happen with all the allocated but not freed memory? Is it automatically freed or stays as a garbage?
exec*()replaced the memory of the old process completely with the new program. This includes all allocated memory, so there is no garbage staying behind. But note that other resources like file descriptors are not automatically freed or closed.
I'm newbie. I want to make the client program to receive input from keyboard and data from server. I don't want if while user type something (scanf) and its block to receive data from server. How to write the code in C ? Thank you.
Welcome :) I suggest grabbing a copy ofAdvanced Programming in the Unix Environment, 2nd Editionas soon as you can. It has excellent examples on usingselect()(and everything else, too). The source code package on the page above includes an excellent example,calld/loop.cthat shows more or less exactly what you want -- a server loop that accepts connections, adds the connections to the select mask of file descriptors, and handles file descriptors in turn. If you'd like a friendlier interface, investigatelibevent. Libevent can give you higher performance on a wide range of platformsanda nice interface. Great for production code, maybe less great for learning how the kernel works.
When I write ``` mkdir("~/folder1" , 0777); ``` in linux, it failed to create a directory. If I replace the~with the expanded home directory, it works fine. What is the problem with using~? Thanks
~is known only to the shell and not to themkdirsystem call. But if you try: ``` system("mkdir ~/foo"); ``` this works as the"mkdir ~/foo"is passed to a shell and shell expands~to$HOME If you want to make use of the$HOMEwithmkdir, you can make use of thegetenvfunction as: ``` char path[MAX]; char *home = getenv ("HOME"); if (home != NULL) { snprintf(path, sizeof(path), "%s/new_dir", home); // now use path in mkdir mkdir(path, PERM); } ```
I'd like to read the logic code of=, but can't find it. UPDATE: I found thetest_multimethod text/ruby/test_assignment.rb. It's Ruby code, but seems will let me to the destination. The reason I want to check the code is find how it handles multi-assignment. Likea,b,c = [1,2,3]. UPDATE: I found keywords "MASGN" and led me to compile_massign(rb_iseq_t *iseq, LINK_ANCHOR *ret, NODE *node, int poped)in compile.c http://github.com/ruby/ruby/commit/e39eb9dab50eaa681467e51145b37cdc11667830#diff-2
I don't think you'll find any code for=. The=will be part of the grammar rules which define the Ruby language and the parser(written in C) will make use of the grammar.
I'm using C# to consume a C library using the following syntax: [DllImport("clib.so") static extern int func(char* foo); I'd like to know if there's any way to catch an exit(#) that happens in the C code so I can reload the library if a critical error ever happens. Thanks!
I believe exit() will terminate the process without ever re-entering managed code. Possibly you could register a function to notify you when this happens using a prior call to atexit() via P/Invoke. But the process will still exit if you return from this. I imagine not returning will leave the process in an indeterminate state. You may need to implement some form of process isolation and watch for process exit of your moribund library. http://msdn.microsoft.com/en-us/library/6wdz5232.aspx
I want to write regular expression for constants in C language. So I tried this: Let digit -> 0-9,digit_oct -> 0-7,digit_hex -> 0-9 | a-f | A-F Then: RE = digit+ U 0digit_oct+ U 0xdigit_hex+ I want to know whether I have written correct R.E. Is there any other way of writing this?
There is another type of integer constants, namelyinteger character constantssuch as'a'or'\n'. In C99 these are constants and their type is justint. The best regular expressions for all these are found in the standard, section 6.4,http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf
i'm looking for a ready-made grammar and parser for php (at least 5.2), ideally an utility/library that can parse php code into a readable AST, e.g. xml. The parser itself doesn't have to be written in php, the source language doesn't matter much.
To answer my own question I've managed to compilephcon my OSX box, the parser part seems to work well ``` phc --dump-xml=ast foo.php > bar.xml ``` creates an xml representation of the AST.
What are C based services and Java based services in Android? What is similarity and dissimilarity between them ? Are C based services available in Android?
The System C-library is a BSD-derived implementation of the standard C system library (libc), tuned for embedded Linux-based devices. Meaning, this is the operating system (ref "What is Android?". The Application framework is written in Java, and it is these frameworks you as a programmer mostly use. Here you have ActivityManager and ContentProvider to work with. More to read:What is Android?
Question is simple, i have a object file and i want to read the symbols of the object file via code. I am aware that the linux command "nm" would be able to do this, but i want to be able to do it inside code. Also note id like to do this either via C or Python. Regards Paul
It would be nice to provide more details. For some pointers: http://sourceforge.net/projects/python-elf/http://www.grant-olson.net/python/pyasm
I have a cuda program like this : ``` for (int i=0;i<100000;i++) { if (i%2 == 0) { bind_x(x) // bind x to texture kernel_code<<A,B>>(M,x,y) // calculate y = M*x } else { bind_x(y) kernel_code<<A,B>>(M,y,x) // calculate x = M*y } cudaThreadSynchronize(); if (i%2 == 0) unbind_x(x) else unbind_x(y) // unbind x from texture } ``` I heard that if I do not putcudaThreadSynchronize();cpu will continue to run without waiting for the kernel to end so ... Should I callcudaThreadSynchronize()before unbind_x(). I try to run with& without, the result is the same ?!? (And in theory It shouldn't)
Any CUDA operation (except special asynchronious operations) will causecudaThreadSynchronize()automatically. So, results should be the same.
This question already has answers here:Closed13 years ago. Possible Duplicate:C fopen vs open What is the difference between open() and fopen() in C language?
One is part of the standard c library (fopen) so you can expect it to be present on all hosted c compiler setups. This function returns aFILE*which can be operated on by the functions in<stdio.h>. The other (open) is a system call/function not specified by the c standard (however, i believe it is part of the POSIX standard) and therefore only guaranteed to exist on select platforms which claim to support it. This returns anintwhich represents a file, this can be operated on usingread/writeand other similar functions.
This function prints every number starting from 0000 to 1000. ``` #include <stdio.h> int main() { int i = 0; while ( i <= 1000 ) { printf( "%04d\n", i); i = i + 1; } return 0; } ``` The output looks like this: 000000010002etc.. How can I make this more presentable using three different columns (perhaps using \t ) to have the output look like this: 0000 0001 00020003 0004 0005etc..
This is how I'd do it, to eliminate the potentially expensiveif/?:statement: ``` char nl[3] = {' ', ' ', '\n'}; while ( i <= 1000 ) { printf("%04d%c", i, nl[i%3]); ++i; } ``` Note that the modulo division may be much more expensive than the branching anyhow, but this depends on your architecture.
What happens when two threads of the same process running on different logical cpu hit a seg fault?
Default action is for the process to exit. If you handle the segfault, I suppose you could try to arrange for just the thread where it happened to terminate. However, since the only things which cause a segfault to occur naturally (as opposed toraiseorkill) stem from undefined behavior, the program is in an indeterminate state and you can't rely on being able to recover anything.
I'm writing a program that reads a stream of data and parses it into some values: either integers, floats, characters, or a compound value that contains a set of values (can be nested). How could I represent that in C? I was thinking of an union ofint,float,char, then having an array of pointers to such unions for the compound value, but that can't be nested.
(I'm imagining that you are parsing an Xml file) We'll assume that you have a bunch of nodes. Each node can have a value, it can be one of a set of sibling, and it could have children. That would give you a struct like: ``` struct Node { DATA Value; DATATYPE Type; Node* nextSibling; Node* firstChild; }; ``` DATAcould be a union like you described, or separate variables. However, since you will reading values from it in the same form as you stored them, a union should be fine.DATATYPEshould be an enum.
How can I verify two CRC implementations will generate the same checksums? I'm looking for an exhaustive implementation evaluating methodology specific to CRC.
You can separate the problem into edge cases and random samples. Edge cases. There are two variables to the CRC input, number of bytes, and value of each byte. So create arrays of 0, 1, and MAX_BYTES, with values ranging from 0 to MAX_BYTE_VALUE. The edge case suite will be something you'll most likely want to keep within a JUnit suite. Random samples. Using the ranges above, run CRC on randomly generated arrays of bytes in a loop. The longer you let the loop run, the more you exhaust the inputs. If you are low on computing power, consider deploying the test to EC2.
Does anyone know of an efficient implementation of a memcspn function?? It should behave like strcspn but look for the span in a memory buffer and not in a null terminated string. The target compiler is visualC++ . Thanks, Luca
One near-optimal implementation: ``` size_t memcspan(const unsigned char *buf, size_t len, const unsigned char *set, size_t n) { size_t i; char set2[1<<CHAR_BIT] = {0}; while (n--) set2[set[n]] = 1; for (i=0; i<len && !set2[buf[i]]; i++); return i; } ``` It might be better to use a bit array instead of a byte array forset2, depending on whether arithmetic or a little bit more cache thrashing is more expensive on your machine.
I'm writing some C where I'm going to need to store a very large graph as an adjacency matrix. I was going to hack up a quick graph implementation, but wanted to ask first if there are any good graph libraries for C (not c++) that people like. I'm going to import the graph in some standard format (probably GML, but thats not a make or break requirement), store it as an adjacency matrix, and then do some computations. Any thoughts? Thanks! EDIT: as an FYI, I have no interest in drawing the graph at all
You can have a look atigraph. It also has support for reading and writing GML files.
I have a little problem with a C library: Byte Flood Cryptography. (http://bfcrypt.sourceforge.net). I would create a program which use both linux sockets and Byte Flood Cryptography (the Byte Flood Cryptography functions are near from those provided from stdio.h, and this, I have understand). I don't know how to'bind'the two stream. I would encrypt data directly to the network.How can I do?? (I don't want to use temporary array or files)
Don't use that library. Use only ciphers and protocols that were designedand reviewedby professional cryptographers, not crackpots who talk about "non-mathematical" approaches to cipher design. I'd reach forGnuTLS(for C programs) orBotan(if C++ is okay), myself. OpenSSL is popular but has a weird license and should not be used for new code.
I am working on an application wherein i need to compare 10^8 entries(alphanumeric entries). To retrieve the entries from file( file size is 1.5 GB) and then to compare them, i need to take less than 5 minutes of time. So, what would b the effective way to do that, since, only retrieving time is exceeding 5 min. And i need to work on file only. please suggest a way out. I m working on windows with 3GB RAM n 100Gb hard disk.
Read a part of the file, sort it, write it to a temporary file.Merge-sort the resulting files.
I need a C rounding function which rounds numbers like MATLAB's round function. Is there one? If you don't know how MATLAB's round function works see this link: MATLAB round function I was thinking I might just write my own simple round function to match MATLAB's functionality. Thanks, DemiSheep
This sounds similar to theround()function from math.h These functions shall round their argument to the nearest integer value in floating-point format, rounding halfway cases away from zero, regardless of the current rounding direction. There's alsolrint() which gives you an int return value, though lrint() and friends obey the current rounding direction - you'll have to set that usingfesetround() , the various rounding directions are foundhere.
This question already has answers here:Closed13 years ago. Possible Duplicate:C fopen vs open What is the difference between open() and fopen() in C language?
One is part of the standard c library (fopen) so you can expect it to be present on all hosted c compiler setups. This function returns aFILE*which can be operated on by the functions in<stdio.h>. The other (open) is a system call/function not specified by the c standard (however, i believe it is part of the POSIX standard) and therefore only guaranteed to exist on select platforms which claim to support it. This returns anintwhich represents a file, this can be operated on usingread/writeand other similar functions.
This function prints every number starting from 0000 to 1000. ``` #include <stdio.h> int main() { int i = 0; while ( i <= 1000 ) { printf( "%04d\n", i); i = i + 1; } return 0; } ``` The output looks like this: 000000010002etc.. How can I make this more presentable using three different columns (perhaps using \t ) to have the output look like this: 0000 0001 00020003 0004 0005etc..
This is how I'd do it, to eliminate the potentially expensiveif/?:statement: ``` char nl[3] = {' ', ' ', '\n'}; while ( i <= 1000 ) { printf("%04d%c", i, nl[i%3]); ++i; } ``` Note that the modulo division may be much more expensive than the branching anyhow, but this depends on your architecture.
What happens when two threads of the same process running on different logical cpu hit a seg fault?
Default action is for the process to exit. If you handle the segfault, I suppose you could try to arrange for just the thread where it happened to terminate. However, since the only things which cause a segfault to occur naturally (as opposed toraiseorkill) stem from undefined behavior, the program is in an indeterminate state and you can't rely on being able to recover anything.
I'm writing a program that reads a stream of data and parses it into some values: either integers, floats, characters, or a compound value that contains a set of values (can be nested). How could I represent that in C? I was thinking of an union ofint,float,char, then having an array of pointers to such unions for the compound value, but that can't be nested.
(I'm imagining that you are parsing an Xml file) We'll assume that you have a bunch of nodes. Each node can have a value, it can be one of a set of sibling, and it could have children. That would give you a struct like: ``` struct Node { DATA Value; DATATYPE Type; Node* nextSibling; Node* firstChild; }; ``` DATAcould be a union like you described, or separate variables. However, since you will reading values from it in the same form as you stored them, a union should be fine.DATATYPEshould be an enum.
How can I verify two CRC implementations will generate the same checksums? I'm looking for an exhaustive implementation evaluating methodology specific to CRC.
You can separate the problem into edge cases and random samples. Edge cases. There are two variables to the CRC input, number of bytes, and value of each byte. So create arrays of 0, 1, and MAX_BYTES, with values ranging from 0 to MAX_BYTE_VALUE. The edge case suite will be something you'll most likely want to keep within a JUnit suite. Random samples. Using the ranges above, run CRC on randomly generated arrays of bytes in a loop. The longer you let the loop run, the more you exhaust the inputs. If you are low on computing power, consider deploying the test to EC2.
Does anyone know of an efficient implementation of a memcspn function?? It should behave like strcspn but look for the span in a memory buffer and not in a null terminated string. The target compiler is visualC++ . Thanks, Luca
One near-optimal implementation: ``` size_t memcspan(const unsigned char *buf, size_t len, const unsigned char *set, size_t n) { size_t i; char set2[1<<CHAR_BIT] = {0}; while (n--) set2[set[n]] = 1; for (i=0; i<len && !set2[buf[i]]; i++); return i; } ``` It might be better to use a bit array instead of a byte array forset2, depending on whether arithmetic or a little bit more cache thrashing is more expensive on your machine.
I'm writing some C where I'm going to need to store a very large graph as an adjacency matrix. I was going to hack up a quick graph implementation, but wanted to ask first if there are any good graph libraries for C (not c++) that people like. I'm going to import the graph in some standard format (probably GML, but thats not a make or break requirement), store it as an adjacency matrix, and then do some computations. Any thoughts? Thanks! EDIT: as an FYI, I have no interest in drawing the graph at all
You can have a look atigraph. It also has support for reading and writing GML files.
I have a little problem with a C library: Byte Flood Cryptography. (http://bfcrypt.sourceforge.net). I would create a program which use both linux sockets and Byte Flood Cryptography (the Byte Flood Cryptography functions are near from those provided from stdio.h, and this, I have understand). I don't know how to'bind'the two stream. I would encrypt data directly to the network.How can I do?? (I don't want to use temporary array or files)
Don't use that library. Use only ciphers and protocols that were designedand reviewedby professional cryptographers, not crackpots who talk about "non-mathematical" approaches to cipher design. I'd reach forGnuTLS(for C programs) orBotan(if C++ is okay), myself. OpenSSL is popular but has a weird license and should not be used for new code.
I am working on an application wherein i need to compare 10^8 entries(alphanumeric entries). To retrieve the entries from file( file size is 1.5 GB) and then to compare them, i need to take less than 5 minutes of time. So, what would b the effective way to do that, since, only retrieving time is exceeding 5 min. And i need to work on file only. please suggest a way out. I m working on windows with 3GB RAM n 100Gb hard disk.
Read a part of the file, sort it, write it to a temporary file.Merge-sort the resulting files.
I need a C rounding function which rounds numbers like MATLAB's round function. Is there one? If you don't know how MATLAB's round function works see this link: MATLAB round function I was thinking I might just write my own simple round function to match MATLAB's functionality. Thanks, DemiSheep
This sounds similar to theround()function from math.h These functions shall round their argument to the nearest integer value in floating-point format, rounding halfway cases away from zero, regardless of the current rounding direction. There's alsolrint() which gives you an int return value, though lrint() and friends obey the current rounding direction - you'll have to set that usingfesetround() , the various rounding directions are foundhere.
When my code is in a blocking recv call, if the other side reboots, then this side recv call doesn't get to know about it and just goes into a hung state. How to avoid this?
By default, if the other side of the connection disappears without terminating the connection properly, the OS on your side has no way of knowing that no further data will be coming. That's whyrecv()will block forever in this situation. If you want to have a timeout, then set the socket to non-blocking and useselect()to wait for it to become readable.select()allows you to specify a timeout. Alternatively, you can set theSO_KEEPALIVEsocket option withsetsockopt(). This will enable the sending of TCP "keepalives", that will allow your side to detect a stale connection. (Do note that with the default settings, it can take alongtime to detect that the connection has gone).
I am confused with this program. ``` #include <stdio.h> int main(void) { char* ptr="MET ADSD"; *ptr++; printf("%c\n", ptr); ptr++; printf("%c\n", ptr); } ``` Here's the output. ET ADSDT ADSD My question is how does the pointer display the rest of the characters?
You are passing a wrong combination of parameters toprintf: the%cformat specification requires acharparameter, not achar*. So the result is undefined - in your caseprintfseems to print the whole char array, but this is just by pure chance. Use either ``` printf("%c\n", *ptr); ``` or ``` printf("%s\n", ptr); ```
For instance: ``` Bool NullFunc(const struct timespec *when, const char *who) { return TRUE; } ``` In C++ I was able to put a/*...*/comment around the parameters. But not in C of course, where it gives me the error: error: parameter name omitted
I usually write a macro like this: ``` #define UNUSED(x) (void)(x) ``` You can use this macro for all your unused parameters. (Note that this works on any compiler.) For example: ``` void f(int x) { UNUSED(x); ... } ```
How can I load the batch file console to my C console? I know in batch The command isShowme.bat /Band it'll load the console into whatever console you called that file from. What would that be inC? ``` ShellExecute(NULL,"open","Showme.bat",NULL,NULL,SW_SHOW); ``` Also, doing that... How could I also add additional arguments such as >>LogTheConsoleTo-a-File.log Is that possible?
Use the POSIX function "popen". With MSVC/MinGW you can use "_popen" instead. This give you the needed control.
How to set an environment variable and start a process in ANSI C for Windows? If possible I want to avoid using any Windows API for this.
In pure ANSI C, it is not possible. There is neither of the functionssetenvnorputenv, and even theexecv*family of functions is missing. Instead, I suggest that you write a little interface in the way you want (which possibly looks likeexecve) and is system-dependent. That way, you can change the wrapper easily when you port your program to a non-Windows environment.
gcc 4.4.3 c89 pthreads I use valgrind for checking memory errors. I am just wondering if there is any tool for linux that can detect running threads that haven't been terminated after the program finishes. I am running a multi-thread application and need a tool to make sure all threads have finished. Many thanks for any suggestions,
If the program has terminated (because the initial thread returned frommain(), some thread calledexit(), or a fatal signal was recieved by the process) then you are guaranteed that all threads have been terminated with extreme prejudice. If you want to write your program so that itensuresthat all its threads have exited beforemain()exits, then you need to loop over all your threads at the end ofmain(), callingpthread_join()on each one. (This also means that you shouldn't create your threads detached, or detach them).
I want to set the maximum of connection. If it more than the maximum, tell the client now server is full and close the socket. How to write code in C ? Thank you.
Simple. At the point where you callaccept(), something like this: ``` new_conn = accept(listen_sock, &addr, addr_len); if (new_conn > 0) { if (total_connections < max_connections) { total_connections++; register_connection(new_conn); } else { send_reject_msg(new_conn); close(new_conn); } } ``` (and of course decrementtotal_connectionsat the point where you lose a connection).
I have a Bison rule ``` block: LBRACE { some code } decls stmts RBRACE {more code } ; ``` The issue is in the "more code" section, I have ``` $$ = $3 ; ``` Basically, I want the return value of block to be stmts. When I do this, Bison says "$3 of block has no type." If I remove the code block containing some code and stick it into the latter block, bison does not complain. I have stmts and all of its derivatives declared as types. So is this not allowed by Bison? I can make changes to the grammar to accommodate this, but it will be tedious and much easier to just use the above.
Use$4to refer tostmts. Since you have amid-rule action, all proceeding symbol numbers are offset as the action itself can have a value. The corresponding component numbers are:$1LBRACE$2{ some code }$3decls$4stmts$5RBRACE$6{ more code }
For some reason I can't seem to catch the WM_LBUTTONDOWN event on a label ("STATIC" window). When monitoring with Winspector it appears the message always arrives to the parent window. However, according to thedocs, the message should be posted to the Window beneath the cursor. Does anyknow have an idea why the message does not arrive in the WindowProc function of the label?
Check if the 'Notify' property(SS_NOTIFY) of the label is checked. This means that the label notifies its parent about the mouse events.http://msdn.microsoft.com/en-us/library/bb760773(VS.85).aspx
``` #define int_p int* int_p p1,p2,p3; // only p1 is a pointer ! ``` can somebody exlplain why it is so.
#defineis just a textual substitution. The code above is equivalent to ``` int *p1, p2, p3; ``` so onlyp1is a pointer. You need ``` typedef int* int_p; ``` instead.
I need to do the following equation floor(e%100000) where e is a double. I know mod only accepts int values, how do I go about achieving this same result? Thanks
Use thefmod()function instead of%. It acceptsdoubleparameters, and returns adoubleresult.
If I make a function that returns more than 1 values to the same variable like in the example: ``` char *strstr(char *s1,char *s2) { int flag=1; char i,j; for(i=0;*s1;i++) { if(s1[i]==s2[0]) for(j=i;*s2;j++) { if(s1[j]!=s2[j]) flag=0; } } return i; return 0; } ``` What will be the actual value returned by the function?Will the last returned value overlap the first returned value?
The first return hit (return i;here) will be what is actually returned. A good compiler will tell you that thereturn 0;is dead code since it is unreachable (i.e. there is no way for control flow to reach that statement). Unless you create your own tuple or pair structure (or some other more semantic structure), the only reasonable way to return multiple values (without using globals or something else unmaintainable) in C is to do it with pointers as out parameters, though you say you don't want to do this.
Why exactly do we need a "Circular Linked List" (singly or doubly) data structure? What problem does it solve that is evident with simple Linked Lists (singly or doubly)?
A simple example is keeping track of whose turn it is in a multi-player board game. Put all the players in a circular linked list. After a player takes his turn, advance to the next player in the list. This will cause the program to cycle indefinitely among the players. To traverse a circular linked list, store a pointer to the first element you see. When you see that element again, you have traversed the entire list. ``` void traverse(CircularList *c) { if (is_empty(c)) { return; } CircularList start = c; do { operateOnNode(c); c = c->next; } while(c != start); } ```
I am trying to add an int to a float. My code is: ``` int main() { char paus[2]; int millit = 5085840; float dmillit = .000005; float dbuffer; printf("(float)milit + dmillit: %f\n",(float)millit + dmillit); dbuffer = (float)millit + dmillit; printf("dbuffer: %f\n",dbuffer); fgets(paus,2,stdin); return 0; } ``` The output looks like: (float)millit + dmillit: 5085840.000005dbuffer: 5085840.000000 Why is there a difference? I've also noticed that if I change dmillit = .5, then both outputs are the same (5085840.5), which is what I would expect. Why is this? Thanks!
(float)millit + dmillitevaluates to adoublevalue. When you print the value, it displays correctly, but when you store it in afloatvariable, the precision is lost.