question
stringlengths
25
894
answer
stringlengths
4
863
I've been learning flex recently (not adobe flex), and I've been using the flex output file with success (just compiling the lex file generated and that's it). Now I've come across bison, and I've read that bison uses the lex file to get the tokens from the input. But now I have a problem: I am sitting in front of gcc and I have no idea of how I link the flex file (lex one) and the bison one together. My question is, how do I link them together in gcc?
You just compile both c programs together. Yes, the lex part could generate a .h file, but you only have to care about C files on compilation: ``` lex example4.l yacc -d example4.y gcc lex.yy.c y.tab.c -o example4 ``` You can learn more about lex & yacc, in (for example) here: http://westes.github.io/flex/manual/ http://www.gnu.org/software/bison/manual/
My question is whether or not it is possible to directly pass the parsed stuff from (s)scanf to a function call. In other words whether I have to initialise the variables which I want to pass to the function (and read via scanf) or not.
sscanfreturns the number of successful conversions. It does not return the converted values. So, you wouldn't be passing in the newly converted data when passing the return value ofsscanfdirectly into another function (if that is what you are asking).
I'm having trouble on this... I have this header: ``` #ifndef PESSOA_H #define PESSOA_H typedef struct pa{ int idade; int atend; }pessoa; void inicPessoa(pessoa *ps, int id); #endif ``` and, in filaC.h: ``` #ifndef FILAC_H #define FILAC_H #include "pessoa.h" typedef struct pessoa elem_t; typedef struct no{ elem_t info; struct no *prox, *ant; } No; typedef No * Fila; #endif ``` but compiler says fiel info on filaC.h has an incomplete type. changingelem_t info;tostruct elem_t into;had no effect.
You have no type calledstruct pessoa. You havestruct pa, and you havepessoa(a typedef). So you need to change this: ``` typedef struct pessoa elem_t; ``` into one of: ``` typedef struct pa elem_t; typedef pessoa elem_t; ```
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed12 years ago.Improve this question How does (exactly) utility like UNIXfilecommand guess the file type? Are there any source-codes?
It uses various heuristics, mainly signatures which are described in a configuration file. ``` man -s 5 magic ``` will gives the file format.
Just a quick question: Is there a way to duplicate a file pointer (those returned byfopen()), similar to howdup()duplicates a file handlers returned by functions likeopen()? Basically, I want to be able to do something like this: ``` FILE *fp = fopen("some_file", "r"); FILE *fp2 = /* do something to duplicate the file pointer */; fclose(fp); // fp2 is still open /* do something with fp2 */ fclose(fp2); ```
``` FILE *fp2 = fdopen (dup (fileno (fp)), "r"); ```
Let me explain what the 'which' function does: From GNU-R help: which indices are TRUE?Give the ‘TRUE’ indices of a logical object, allowing for array indices. or showing some code: (GNU-R starts counting indices with 1) ``` > x <- c(1,2,3,1,3,5); > which(x == 1); [1] 1 4 > which(x == 3); [1] 3 5 > ll <- c(TRUE,FALSE,TRUE,NA,FALSE,FALSE,TRUE); > which(ll); [1] 1 3 7 ``` Does anyone know a similar function in C/C++? Thanks for your help rinni
You have to understand thatRis vectorised, whereas C first and foremost works on individual atomistic data pieces: a singleint,double, ... With C++, you can look into STL algorithms with which you approach this. Lastly, at the R and C++ intersection, ourRcpppackage has some vectorized operations in C++ which mimic some operations; see theRcpp-sugarpdf vignette for more (and/or some of our talks on Rcpp).
I have an application which starts 5 threads. After starting those threads nothing happens in main(). ``` main(){ `start thread 1..5 } ``` How do I loop infinitely in main() so my program will run continuously until it gets a signal. I don't want to use ``` while(true) ``` because it will eat CPU cycle. (As I think ) Edit: I am using gcc 4 Thread Api :pthread OS : Linux
the simplest would be: ``` while (true) sleep(1000); ``` and the best would be tojoin()all the five threads.
suppose I have a Unicode codepoint c (auint32). Is there a way to print this integer to console (as a wide character) without usinglocale.horwchar.h? Thanks.
You can try to use ``` printf("%lc", c); ``` though you really need to make sure thatcis awint_t(which requireswchar.h) rather than auint32_t, even though the two are most likely the same type...
Assuming I have C function with variable length argument list: ``` int some_func(int arg1 , ... ); ``` Is it possible (easy?) to call this function from python using ctypes? Update: Implemented suggestion from cedric and that worked like charm: ``` libc = ctypes.CDLL( "/lib64/libc.so.6" , ctypes.RTLD_GLOBAL ) printf = getattr( libc , "printf") printf("String1:%s int:%d String2:%s double:%lg\n" , "Hello" , 10 , "World" , ctypes.c_double( 3.1415 )) ``` With the ctypes.c_double( ) function as the only minor nuisance. So - all in all this was easier than I though; however I guess the possiblity to fxxx up with va_args remains the same.
Assuming you can bind thelibc printf function, that is a really good example of va_args using, I think you'll be able to create a binding with any function.
When i use GnuGK/Openh323gk from its telnet session how can i do makecall? ``` $ telnet localhost 7000 ; makecall alias1 alias2 $ ./gnugk -c config.ini -ttt 2011/05/23 11:10:48.957 1 MakeCall.cxx(55) MakeCallEndpoint: Error registering with gatekeeper at "<my public ip>" 2011/05/23 11:10:49.458 1 SoftPBX.cxx(483) GK SoftPBX: MakeCall registration of pseudo-endpoint failed ```
GnuGk uses an internal endpoint to initiate calls. This endpoint is treated exactly like any other external endpoint and needs to register with GnuGk. Your quoted trace lines indicate that this registration fails. Make sure it is not blocked by any authorization rule and that it is using an alias that isn't already used by something else: ``` [CTI::MakeCall] Endpoint=<free alias name> ``` In a level 3 trace you should be able to see the registration of this internal endpoint and the confirm or reject message from GnuGk.
This question already has an answer here:Programmatically obtain DNS servers of host(1 answer)Closed9 years ago. I want to use in my code local DNS addresses and am looking for a library that would produce it. Is there anything like it or do I have to parse /etc/resolv.conf myself? Thanks
You can usethe resolver functionsas described in the answer tothis questionor read the addresses of name servers from the file/etc/resolv.confwhich is a simple text file, such as ``` # Generated by NetworkManager nameserver x.x.x.x nameserver y.y.y.y ``` wherex.x.x.xandy.y.y.yare ip addresses.
hello everyone I have this snippet of the code: ``` void writer(void* param){ if(NULL == param){ return; } param = (param_t*)param; ... } ``` is it safe code, or not, param is from type param_t*, but I'm sick doing every time casting when I use it in function, do Somebody have another elegant solution? thanks in advance
That is a strange no-op. When you define the function you say param is of typevoid*.Then, with the cast, you explicitly convert it toparam_t*And the compiler implicitly converts thatparam_t*tovoid*with the assignment. You need another variable ``` void writer(void *param) { param_t *internal_param; if (NULL == param) return; internal_param = param; /* ... */ } ```
This question already has answers here:Closed12 years ago. Possible Duplicate:What is the difference between sigaction and signal? It seems to me that both of them can be used to register a callback for a specific signal. How do you choose which one to use?
TLPI UNIX systems provide two ways of changing the disposition of a signal:signal()andsigaction(). The sigaction() system call is an alternative to signal() for setting the disposition of a signal. Although sigaction() is somewhat more complex to use than signal(), in return it provides greater flexibility. sigactionis also more portable thansignal. Also, withsigactionyou can specify signal handlers that receive additional arguments (sa_sigactionversussa_handler). ``` /* can be installed by signal / sigaction */ void(*) (int); /* can be installed by sigaction only */ void(*) (int, siginfo_t *, void *); ```
This question already has answers here:Closed12 years ago. Possible Duplicate:Best way to detect integer overflow in C/C++ If I have an expressionx + y(in C or C++) wherexandyare both of typeuint64_twhich causes an integer overflow, how do I detect how much it overflowed by (the carry), place than in another variable, then compute the remainder?
The remainder will already be stored in the sum of x + y, assuming you are using unsigned integers. Unsigned integer overflow causes a wrap around ( signed integer overflow is undefined ). See standards reference from Pascal in the comments. The overflow can only be 1 bit. If you add 2 64 bit numbers, there cannot be more than 1 carry bit, so you just have to detect the overflow condition. For how to detect overflow, there was a previous question on that topic:best way to detect integer overflow.
I've been learning flex recently (not adobe flex), and I've been using the flex output file with success (just compiling the lex file generated and that's it). Now I've come across bison, and I've read that bison uses the lex file to get the tokens from the input. But now I have a problem: I am sitting in front of gcc and I have no idea of how I link the flex file (lex one) and the bison one together. My question is, how do I link them together in gcc?
You just compile both c programs together. Yes, the lex part could generate a .h file, but you only have to care about C files on compilation: ``` lex example4.l yacc -d example4.y gcc lex.yy.c y.tab.c -o example4 ``` You can learn more about lex & yacc, in (for example) here: http://westes.github.io/flex/manual/ http://www.gnu.org/software/bison/manual/
My question is whether or not it is possible to directly pass the parsed stuff from (s)scanf to a function call. In other words whether I have to initialise the variables which I want to pass to the function (and read via scanf) or not.
sscanfreturns the number of successful conversions. It does not return the converted values. So, you wouldn't be passing in the newly converted data when passing the return value ofsscanfdirectly into another function (if that is what you are asking).
I'm having trouble on this... I have this header: ``` #ifndef PESSOA_H #define PESSOA_H typedef struct pa{ int idade; int atend; }pessoa; void inicPessoa(pessoa *ps, int id); #endif ``` and, in filaC.h: ``` #ifndef FILAC_H #define FILAC_H #include "pessoa.h" typedef struct pessoa elem_t; typedef struct no{ elem_t info; struct no *prox, *ant; } No; typedef No * Fila; #endif ``` but compiler says fiel info on filaC.h has an incomplete type. changingelem_t info;tostruct elem_t into;had no effect.
You have no type calledstruct pessoa. You havestruct pa, and you havepessoa(a typedef). So you need to change this: ``` typedef struct pessoa elem_t; ``` into one of: ``` typedef struct pa elem_t; typedef pessoa elem_t; ```
This question already has answers here:Closed12 years ago. Possible Duplicate:Why are there sometimes meaningless do/while and if/else statements in C/C++ macros? Hello, in many C macros programmers use special one-loop, for example: ``` #define do_something(a) do { execute(a); count(a); } while(0) ``` because of when you want to do this macro in loop and you don't use "{}". Why they aren't using simple block instead? I mean, doesn't ``` #define do_something(a) { execute(a); count(a); } ``` have the very same effect?
Because ``` if( something ) do_something(a); else something_else(); ``` expands to: ``` if( something ) do { execute(a); count(a); } while(0); else something_else(); ``` which is correct, but: ``` if( something ) { execute(a); cout(a); }; else something_else(); ``` would not be correct (the superfluous ";").
I am trying to use GSL for least square fitting, but I can't even make theexamplerun properly. It compiles, but when running the program it gives the error dyld: lazy symbol binding failed: Symbol not found: _cblas_dnrm2Referenced from: /usr/local/lib/libgsl.0.dylibExpected in: dynamic lookup I believe I have narrowed down the problem to the line gsl_multifit_fdfsolver_set (s, &f, &x.vector); but I have not the slightest clue why. I am running it on OSX with GSL 1.15 (though I innitially insalled the wrong version, 1.9). I compile it in the terminal using:gcc unchanged_example.c -o examplefitter -lgsl -lm EDIT: solution was foundhere. adding '-lgslcblas' when compiling sorted it out
For anyone coming across this you need to link against two libraries... ``` gcc -Wall -O3 -g -lgslcblas -lgsl -std=c11 -pedantic-errors ```
I am working on a HTTPS client and I managed to establish a secure connection and get the X509 certificate using:X509 *cert = SSL_get_certificate(ssl);(ssl is SSL*).How do I save the certificate to a file? Also, I need to get "Subject DN" and "Issuer DN" fields from the certificate.
--How do I save the certificate to a file? ``` #include <openssl/pem.h> int PEM_write_X509(FILE *fp, X509 *x); ``` --Also, I need to get "Subject DN" and "Issuer DN" fields from the certificate. ``` #include <openssl/x509.h> X509_NAME * X509_get_issuer_name(X509 *a); X509_NAME * X509_get_subject_name(X509 *a); ```
Though its document says this function is MUST, but I saw two examples, one has it, the other doesn't. http://curl.haxx.se/libcurl/c/persistant.html http://curl.haxx.se/libcurl/c/multi-app.html Is this function necessary at all?
If it is designed it will be necessary. Thedocumentationsays: This function must be called at least once within a program (a program is all the code that shares a memory space) before the program calls any other function in libcurl. The environment it sets up is constant for the life of the program and is the same for every program, so multiple calls have the same effect as one call. But please note that in documentation ofcurl_easy_init: If you did not already call curl_global_init(3), curl_easy_init(3) does it automatically. This may be lethal in multi-threaded cases, since curl_global_init(3) is not thread-safe, and it may result in resource problems because there is no corresponding cleanup.
The given code compiles in C but fails in C++. ``` int main() { const int x; /* uninitialized const compiles in C but fails in C++*/ } ``` What is the rationale and the reason behind the change from C to C++?
See the spec, in the compatibility appendix C.1.6: 7.1.6 [see also 3.5]Change:const objects must be initialized in C++ but can be left uninitialized in CRationale:A const object cannot be assigned to so it must be initialized to hold a useful value.Effect on original feature:Deletion of semantically well-defined feature.Difficulty of converting:Semantic transformation.How widely used:Seldom.
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.Closed2 years ago.Improve this question I want a image loader library to help me load images (bmp, jpg, gif, png, and other common format) in Ubuntu using C. I'm writing a opengl program and want to load image to textures. Is there any good choice?
How about OpenCV? This open source project already realise many algorithm and support C/C++ and python. My classmates have done Object recognition project with OpenCV. easy to use~
Does incrementing or decrementing a restrict qualified pointer preserve no aliasing assumption? ``` // a and b point to disjoint arrays void foo(size_t n, double * __restrict a, double * __restrict b) { size_t i; double x, y, z; double * c = b; // copy for(i=0; i<n; ++i) { x = *(a++); // not aliased y = *(b + i); // not aliased z = c[i]; // not aliased } } ``` Thank you.
Yes. Therestrictqualifier is part of the type of the pointer, and this type isn't changed when you increment, decrement, or assign it.
Hey, I'm having the toughest time figuring out how to display this result. Say for example I enter a number such as 59. Based off that number, I get a remaining result of 1 week(s) 2 Day(s) and 5 Hour(s). This is of course assuming one week has 40 hours and 1 day has 7 hours in order to get that output. Any help in the right direction would be helpful. So far I've set it up like so: ``` scanf("%d %d %d", &totalWeeksWorked, &totalDaysWorked, &totalHoursWorked); ```
This is not the fastest way, but is perhaps the most illustrative: ``` int numodweeks = input/(7*24); int numofdays =input/24; int numofhours = 24 - (input/24); ``` Using modulo: ``` int numofweeks = input/(7*24); int numofdays = (input%numofweeks)/7; int numofhours = (input%(numofdays*24)); ``` Then display them how you want.
I wrote a small Hello World app. ``` #include <stdio.h> int main(int argc, const char * argv[]) { printf("Hello World\n"); } ``` When I run ``` gcc fileName.c ``` nothing is returned to the terminal. Can someone tell me what I'm doing wrong?
gcc is the compiler. it outputs a file calleda.outunless specified otherwise using the-oflag, for examplegcc -o myprogram fileName.cwhich will create an executable called myprogram from the source myFile.c. To run your program write:./a.outin the terminal
The question is quite simple: How to read a .pgm image file into a 2D double array in C. I do not have a .pgm buffer in memory. I would like to read it from the disk into memory. Would really appreciate if I could get a code snippet. Thank You.
You probably won't get someone writing you all the code, but here are some useful links that might point you in the right direction: pgm.cpgm.hPGM Format Specificationhttp://www.cplusplus.com/forum/general/2393/
This question already has answers here:Closed12 years ago. Possible Duplicate:Does free(ptr) where ptr is NULL corrupt memory? I'm writing a C function that frees a pointer if it wasmalloc()ed. The pointer can either be NULL (in the case that an error occured and the code didn't get the chance to allocate anything) or allocated withmalloc(). Is it safe to usefree(ptr);instead ofif (ptr != NULL) free(ptr);? gccdoesn't complain at all, even with-Wall -Wextra -ansi -pedantic, but is it good practice?
Quoting the C standard, 7.20.3.2/2 fromISO-IEC 9899: ``` void free(void *ptr); ``` Ifptris a null pointer, no action occurs. Don't check forNULL, it only adds more dummy code to read and is thus a bad practice. However, you mustalwayscheck forNULLpointers when usingmalloc& co. In that caseNULLmean that something went wrong, most likely that no memory was available.
I am looking for a C / C++ or even C# code that will trim the first word of a each line in a text file e.g. file.txt ``` test C:\Windows\System32\cacl.exe download C:\Program Files\MS\ ``` So I will be left with: ``` C:\Windows\System32\cacl.exe C:\Program Files\MS\ ``` I have the current code, but it doesnt seem to work: ``` #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { char s[2048]; while (fgets(s, sizeof(s), stdin)) { char *pos = strpbrk(s, "|\r\n"); if (pos != 0) fputs(pos+1, stdout); } return 0; } ```
``` #include <iostream> using namespace std; int main() { string tmp; while ( !cin.eof() ) { cin >> tmp; getline(cin, tmp); cout << tmp << endl; } } ```
I have this code to draw an arrow: ``` const GLfloat vertices[] = { -0.25f, -0.25f, 0.0f, 0.0f, 0.25f, -0.25f, 0.0f, 0.5f, }; glVertexPointer(2, GL_FLOAT, 0, vertices); glEnableClientState(GL_VERTEX_ARRAY); glColor4f(0.0f, 0.5f, 0.0f, 1.0f); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); ``` Itshoulddraw similar to this: This is the actual result (which is undesired): I don't see what I have done wrong, the vertices seem correct to me, but it seems like OpenGL draws the polygon in a different order than I specified. Can anyone help me out? Thanks in advance. :)
Your triangle strip takes the lower three points first (i.e. the lower part of your green arrow) and then the right three points. Just change the order of points in your definition: ``` const GLfloat vertices[] = { -0.25f, -0.25f, 0.0f, 0.0f, 0.0f, 0.5f, 0.25f, -0.25f, }; ```
I am considering writing an nbody style simulation in c/c++ that needs to run on most personal computers. Essentially an O(n^2) particle simulator. Because this needs to be rather user friendly I was hoping to have 1 Windows exe file that wouldn't require the user to install anything. Is this possible with OpenCL? Does anybody know how to do this without writing two seperate codes?
The user would always need to have the latest version of the driver for their video card installed. AMD users would also need the AMD APP SDK. I guess you could make an installer that determines the users video card and downloads the correct drivers for them, but I don't think you can do this without any installing. That would require loading the drivers from your program. I'm not sure whether that is possible, and even if it's possible, you would essentially have to write your own driver, which is a lot of work. So in short, no.
Is there a tool around that will list all the global variables in a C program? More specifically, is there a simple commandline tool that will do this, i.e. not a heavyweight IDE, CASE, graphical toolkit system etc., but just something that can be run likefoo *.c?
``` ctags -R -x --sort=yes --c-kinds=v --file-scope=no file "c:\my sources" > c:\ctagop.txt ```
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.Closed2 years ago.Improve this question I want a image loader library to help me load images (bmp, jpg, gif, png, and other common format) in Ubuntu using C. I'm writing a opengl program and want to load image to textures. Is there any good choice?
How about OpenCV? This open source project already realise many algorithm and support C/C++ and python. My classmates have done Object recognition project with OpenCV. easy to use~
Does incrementing or decrementing a restrict qualified pointer preserve no aliasing assumption? ``` // a and b point to disjoint arrays void foo(size_t n, double * __restrict a, double * __restrict b) { size_t i; double x, y, z; double * c = b; // copy for(i=0; i<n; ++i) { x = *(a++); // not aliased y = *(b + i); // not aliased z = c[i]; // not aliased } } ``` Thank you.
Yes. Therestrictqualifier is part of the type of the pointer, and this type isn't changed when you increment, decrement, or assign it.
Hey, I'm having the toughest time figuring out how to display this result. Say for example I enter a number such as 59. Based off that number, I get a remaining result of 1 week(s) 2 Day(s) and 5 Hour(s). This is of course assuming one week has 40 hours and 1 day has 7 hours in order to get that output. Any help in the right direction would be helpful. So far I've set it up like so: ``` scanf("%d %d %d", &totalWeeksWorked, &totalDaysWorked, &totalHoursWorked); ```
This is not the fastest way, but is perhaps the most illustrative: ``` int numodweeks = input/(7*24); int numofdays =input/24; int numofhours = 24 - (input/24); ``` Using modulo: ``` int numofweeks = input/(7*24); int numofdays = (input%numofweeks)/7; int numofhours = (input%(numofdays*24)); ``` Then display them how you want.
I wrote a small Hello World app. ``` #include <stdio.h> int main(int argc, const char * argv[]) { printf("Hello World\n"); } ``` When I run ``` gcc fileName.c ``` nothing is returned to the terminal. Can someone tell me what I'm doing wrong?
gcc is the compiler. it outputs a file calleda.outunless specified otherwise using the-oflag, for examplegcc -o myprogram fileName.cwhich will create an executable called myprogram from the source myFile.c. To run your program write:./a.outin the terminal
The question is quite simple: How to read a .pgm image file into a 2D double array in C. I do not have a .pgm buffer in memory. I would like to read it from the disk into memory. Would really appreciate if I could get a code snippet. Thank You.
You probably won't get someone writing you all the code, but here are some useful links that might point you in the right direction: pgm.cpgm.hPGM Format Specificationhttp://www.cplusplus.com/forum/general/2393/
This question already has answers here:Closed12 years ago. Possible Duplicate:Does free(ptr) where ptr is NULL corrupt memory? I'm writing a C function that frees a pointer if it wasmalloc()ed. The pointer can either be NULL (in the case that an error occured and the code didn't get the chance to allocate anything) or allocated withmalloc(). Is it safe to usefree(ptr);instead ofif (ptr != NULL) free(ptr);? gccdoesn't complain at all, even with-Wall -Wextra -ansi -pedantic, but is it good practice?
Quoting the C standard, 7.20.3.2/2 fromISO-IEC 9899: ``` void free(void *ptr); ``` Ifptris a null pointer, no action occurs. Don't check forNULL, it only adds more dummy code to read and is thus a bad practice. However, you mustalwayscheck forNULLpointers when usingmalloc& co. In that caseNULLmean that something went wrong, most likely that no memory was available.
I am looking for a C / C++ or even C# code that will trim the first word of a each line in a text file e.g. file.txt ``` test C:\Windows\System32\cacl.exe download C:\Program Files\MS\ ``` So I will be left with: ``` C:\Windows\System32\cacl.exe C:\Program Files\MS\ ``` I have the current code, but it doesnt seem to work: ``` #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { char s[2048]; while (fgets(s, sizeof(s), stdin)) { char *pos = strpbrk(s, "|\r\n"); if (pos != 0) fputs(pos+1, stdout); } return 0; } ```
``` #include <iostream> using namespace std; int main() { string tmp; while ( !cin.eof() ) { cin >> tmp; getline(cin, tmp); cout << tmp << endl; } } ```
I have this code to draw an arrow: ``` const GLfloat vertices[] = { -0.25f, -0.25f, 0.0f, 0.0f, 0.25f, -0.25f, 0.0f, 0.5f, }; glVertexPointer(2, GL_FLOAT, 0, vertices); glEnableClientState(GL_VERTEX_ARRAY); glColor4f(0.0f, 0.5f, 0.0f, 1.0f); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); ``` Itshoulddraw similar to this: This is the actual result (which is undesired): I don't see what I have done wrong, the vertices seem correct to me, but it seems like OpenGL draws the polygon in a different order than I specified. Can anyone help me out? Thanks in advance. :)
Your triangle strip takes the lower three points first (i.e. the lower part of your green arrow) and then the right three points. Just change the order of points in your definition: ``` const GLfloat vertices[] = { -0.25f, -0.25f, 0.0f, 0.0f, 0.0f, 0.5f, 0.25f, -0.25f, }; ```
I am considering writing an nbody style simulation in c/c++ that needs to run on most personal computers. Essentially an O(n^2) particle simulator. Because this needs to be rather user friendly I was hoping to have 1 Windows exe file that wouldn't require the user to install anything. Is this possible with OpenCL? Does anybody know how to do this without writing two seperate codes?
The user would always need to have the latest version of the driver for their video card installed. AMD users would also need the AMD APP SDK. I guess you could make an installer that determines the users video card and downloads the correct drivers for them, but I don't think you can do this without any installing. That would require loading the drivers from your program. I'm not sure whether that is possible, and even if it's possible, you would essentially have to write your own driver, which is a lot of work. So in short, no.
Is there a tool around that will list all the global variables in a C program? More specifically, is there a simple commandline tool that will do this, i.e. not a heavyweight IDE, CASE, graphical toolkit system etc., but just something that can be run likefoo *.c?
``` ctags -R -x --sort=yes --c-kinds=v --file-scope=no file "c:\my sources" > c:\ctagop.txt ```
``` struct x_firm { char name[50]; double lPrice; char EIK[14]; int day; int month; int year; }; typedef struct x_firm Firm; ``` I have problem with filling struct data ``` printf("Enter firm name:"); scanf("%50s",&firm->name); printf("Enter firm EIK:"); scanf("%13s",&firm->EIK); printf("Enter firm last 5 years price:"); scanf("%f",&firm->lPrice); printf("%f\n",firm->lPrice); printf("Enter registration date[dd.mm.yyyy]:"); scanf("%2d.%2d.%4d", &firm->day, &firm->month, &firm->year); ``` The problem is that the lPrice variable isn't initialize and I don't know why! Please help!
lPriceis adouble, not afloat. Use the%lfformatter. ``` scanf("%lf",&firm->lPrice); ```
When I printf a char with %c format and the char is unprintable like '\0' then there is no column of printout. Same if I use %1c. Or %1.1c. Is there a way to force printf to output a column for '\0'? I'm doing some large printf's and I want columns to match up.
There is nothing you can do for printf. But you can useisprintto filter the arguments of printf ``` printf("%c", (isprint(c) ? c : ' ' )); ```
Suppose i create a thread that ,in some point, calls a function foo(). If i call pthread_exit() from within foo, will that have as a result termination of the thread that called foo? thanks, Nikos
Of course. Otherwise what's the point of pthread_exit in the first place.http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_exit.3.html"The pthread_exit() function shall terminate the calling thread"
In C, if my application ends unexpectedly can I call a function before that happens? I'm writing a flag into a database (processRunning = 1) that prevents other applications from starting a similar process. When the application ends it would not change that flag back.
look into theatexitAPI of the C standard library.
``` #if sizeof(int) != 4 /* do something */ ``` Using sizeof inside#ifdoesn't work while inside#defineit works, why? ``` #define size(x) sizeof(x)/sizeof(x[0]) /*works*/ ```
Nothing is evil - everything can be misused, or in your case misunderstood. Thesizeofoperator is a compiler feature, but compiler features are not available to the preprocessor (which runs before the compiler gets involved), and so cannot be used in#ifpreprocessor directives. However, when you say: ``` #define size(x) sizeof(x)/sizeof(x[0]) ``` and use it: ``` size(a) ``` the preprocessor performs a textual substitution that is handed to the compiler: ``` sizeof(a)/sizeof(a[0]) ```
I'm dealing with CvMat in opencv of type CV_8U. I'm basically adding arrays (and resultant addition is expected to be more than 255). It looks like the CvMat array doesn't store values more than 255 (values more than 10,000-20,000). I don't want an overflow to occur. Is there any way I can do that using a opencv data-structure?
CV_8U means each variable is between 0 and 255 (8bit unsigned integer). CV_16U will give you 0 to 65535 Is that all you were looking for?
``` #include<stdio.h> void f(int a) { printf("%d", a); } #define f(a) {} int main() { /* call f : function */ } ``` How to callf(the function)? Writingf(3)doesn't work because it is replaced by{}
Does(f)(3);work? The C preprocessor doesn't expand the macrofinside( ).
``` section .text global my_strlen my_strlen: xor rax, rax .LOOP: cmp BYTE[rdi+rax], 0 jne .LOOP inc rax ret ``` I execute it with: ``` #include <stddef.h> #include <stdio.h> extern size_t my_strlen(const char *str); int main(int argc, char *argv[]) { if(argc!=2) return 1; printf("%lu\n", (unsigned long)my_strlen(argv[1])); return 0; } ``` But when I execute the program, it does not output anything and it does not close.
You need to increment rax inside the loop.
I want to write data from a C program to a file, so that Excel can read the file to plot a graph of the data. But I'm not sure of the exact syntax to use for fprintf. I have stdlib.h declared in the very top of my program. I declared "File *fp;" in main but I'm getting that File and fp are undeclared. What could be the problem? **EDIT: My program compiles and runs but now my output file doesn't contain any data This is what I have at the end of a while loop that does some computations.. ``` fp = fopen( "out_file.txt", "w" ); // Open file for writing fprintf(fp, "x = %f, y = %f, vx = %f, vy = %f, time = %f, ", x,y,vx,vy,time); ```
Your logic should look something like this: ``` fp = fopen( "out_file.txt", "w" ); // Open file for writing while ( some condition ) { ... some calculations fprintf(fp, "x = %f, y = %f, vx = %f, vy = %f, time = %f, ", x,y,vx,vy,time); } fclose(fp); ```
I have managed to build a static C library on OSX usingmakeon the command line. I have tried to use the same Makefile (withARCHFLAGS=-arch armv6 -arch armv7) to build a static library for iOS, but it fails with: ``` gcc-4.2: error trying to exec '/usr/bin/arm-apple-darwin10-gcc-4.2.1': execvp: No such file or directory ``` I guess it is not working because I'm using the OSX SDK make instead of a some part of the iOS SDK. Any clues? N.B. For more details on the library in question (levmar) and for the Makefile, please refer tothis Stack Overflow answer.
You need to find: the location of the iOS compilerthe command line options that are used in the command line invocation The easiest way is to create a test iPhone/iPad app in XCode, build it, and then look at the build log to find how XCode invokes the compiler.
I'm learning OpenGL usingthis book. I'm trying to run the first example, which ishere. It compiles fine, but when I try to run it, I get an X11 BadAlloc error: ``` X Error of failed request: BadAlloc (insufficient resources for operation) Major opcode of failed request: 128 (GLX) Minor opcode of failed request: 34 () Serial number of failed request: 38 Current serial number in output stream: 39 ``` As far as I can tell, this error is caused when glutCreateWindow is called. I don't know if this is an issue with X itself or with my graphics card, which is a nVidia geForce 310.
Your graphics drivers don't support OpenGL version 4.0. ``` glutInitContextVersion(4, 0); ``` I changed it to 3.3: ``` glutInitContextVersion(3, 3); ``` and it works fine. You can get your OpenGL version fromglxinfo.
``` if ( sscanf( line, "%[^ ] %[^ ] %[^ ]", method, url, protocol ) != 3 )... ``` That format above is very strange,what's it doing?
That line is attempting to read 3 strings that do not contain a space separated by spaces into method, url, protocol and if it fails to read 3 it will then enter the if block.
``` if ( fgets( line, sizeof(line), stdin ) == (char*) 0 )... ``` I don't understand what this line does,anyone knows?
That's a rather odd way of writing a test for the return of a null pointer which indicates an error infgets(). I'd write it like this: ``` if (!fgets(line, sizeof(line), stdin)) ```
``` #include <stdio.h> int main() { long long x = 0x8ce4b16b; long long y = x<<4; printf("%lx, %lx, abc\n", x, y); return 0; } ``` I'm getting8ce4b16b, 0, abc... Is this okay? However if I changeprintflikeprintf("%lld, %lx, abc\n", x, y); The output becomes:2363797867, ce4b16b0, abc Why could have been this behaviour!! :(
Using incorrect format specifier in printf invokes Undefined Behaviour. The correct format specifier forlong longis%lld. Also make sure that you dont have signed integer overflow in your code because that's UB too.
I'm currently working on a code that uses SDL to display video and as i'm working through ssh, i'm looking for something like a text driver (just need to avoid seing the video because it's so slow). So what I need is a simple way to avoid screen init and all that stuff that keep my framerate below 15fps :) Does anyone know something that might help me?
I'm not sure if that's what you want. But try: ``` export SDL_VIDEODRIVER=dummy ```
I want to create a timer usingtimerfd_create, but i don't know how to check for the expiry. Can someone please help me with an easy example? I know how to create and populate using thesettimeas you can see from my earlier timer questions, but how to check the expiry oftimerfd_create? I know it notifies via file descriptor of it's expiry. But how to check it? Thanks in advance.
You can useselectorepollto monitor the file descriptor. Here's an example: ``` struct epoll_event event; efd = epoll_create(2); event.data.fd = timer_fd; event.events = EPOLLIN; epoll_ctl(efd, EPOLL_CTL_ADD, timer_fd, &event); while (1) { struct epoll_event revent; epoll_wait(efd, &revent, 1, -1); /* revent can now be used */ } ```
i am writing a C in Linux, forks a parent and N children. the Parent takes the sqrt(ArraySize) and the rest is divided equally upon the N children. how could i divide the rest of the array equally upon the N children?\ Thnx in advance :)
``` int arraySize = 100; // You would get a count from the array here int nChildren = 5; // This would be provided by you as a parameter to this function int parentSize = sqrt(arraySize); int remainder = arraySize - parentSize; int nChildSize = (remainder / nChildren) + 1 ```
I'm a ruby developer and its been long time since I've coded in C. I want to use a datatype in C which behaves like a symbol. Is this possible? Program asks user for nameUser replies - "foobar"Program declares an integer with the same name i.e.int foobar;
Unlike in interpreted languages, C does not have a dictionary of variable names at runtime. There exist no variable names at runtime at all. Hence unfortunately it is impossible to do what you want in C.
Is there any where to convert a openFILE*returned fromfopento aHANDLEthat is used in the Windows API functions? If so, how?
(HANDLE)_get_osfhandle(_fileno( file ) ) Good luck on 64-bit systems if you're using Visual C++ 2008 or earlier, though, because the return type islongon those. :(
I'm currently working on a code that uses SDL to display video and as i'm working through ssh, i'm looking for something like a text driver (just need to avoid seing the video because it's so slow). So what I need is a simple way to avoid screen init and all that stuff that keep my framerate below 15fps :) Does anyone know something that might help me?
I'm not sure if that's what you want. But try: ``` export SDL_VIDEODRIVER=dummy ```
I want to create a timer usingtimerfd_create, but i don't know how to check for the expiry. Can someone please help me with an easy example? I know how to create and populate using thesettimeas you can see from my earlier timer questions, but how to check the expiry oftimerfd_create? I know it notifies via file descriptor of it's expiry. But how to check it? Thanks in advance.
You can useselectorepollto monitor the file descriptor. Here's an example: ``` struct epoll_event event; efd = epoll_create(2); event.data.fd = timer_fd; event.events = EPOLLIN; epoll_ctl(efd, EPOLL_CTL_ADD, timer_fd, &event); while (1) { struct epoll_event revent; epoll_wait(efd, &revent, 1, -1); /* revent can now be used */ } ```
i am writing a C in Linux, forks a parent and N children. the Parent takes the sqrt(ArraySize) and the rest is divided equally upon the N children. how could i divide the rest of the array equally upon the N children?\ Thnx in advance :)
``` int arraySize = 100; // You would get a count from the array here int nChildren = 5; // This would be provided by you as a parameter to this function int parentSize = sqrt(arraySize); int remainder = arraySize - parentSize; int nChildSize = (remainder / nChildren) + 1 ```
I'm a ruby developer and its been long time since I've coded in C. I want to use a datatype in C which behaves like a symbol. Is this possible? Program asks user for nameUser replies - "foobar"Program declares an integer with the same name i.e.int foobar;
Unlike in interpreted languages, C does not have a dictionary of variable names at runtime. There exist no variable names at runtime at all. Hence unfortunately it is impossible to do what you want in C.
Is there any where to convert a openFILE*returned fromfopento aHANDLEthat is used in the Windows API functions? If so, how?
(HANDLE)_get_osfhandle(_fileno( file ) ) Good luck on 64-bit systems if you're using Visual C++ 2008 or earlier, though, because the return type islongon those. :(
I'm looking for a measure performance tool for C (I'm using MinGW windows toolchain) that gives me some results like: Occupied memory by a variable;Cycles to run the program/a function;Spent time on a function. Thanks
Google Perftools is multi-platform:http://code.google.com/p/google-perftools/ GCC has profiling as well:How to use profile guided optimizations in g++?
I'm writing a parser using flex. I'm using Mac OS X 10.6.7. I have already include header files like this: ``` #include "string.h" #include "stdlib.h" ``` but it says ``` Undefined symbols for architecture x86_64: "_strndup", referenced from: _yylex in ccl2332A.o ld: symbol(s) not found for architecture x86_64 ``` why?
AFAIK there is no method strndup in string.h or stdlib.h, try using strdup() which is probably what you want. If you really need to specifiy the length you want allocated you could do it using malloc and memcpy instead.
When I compile a C file, it says: ``` pcat.lex:12: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘hasTab’. ``` Here's the beginning of the file: ``` #include "ctype.h" #include "stdio.h" #include "stdlib.h" #include "pcat.tab.h" #define YY_USER_ACTION Do_Before_Each_Action(); #define STRING_MAX_LENGTH 255 #define IDENTIFIER_MAX_LENGTH 255 #define MAX_INT 2147483647 static int lineno = 1; static int colno = 1; static bool hasTab; void Do_Before_Each_Action(); ``` Does anybody know what happens?I'm using Mac OS X 10.6.7
boolis not a pre-C99 keyword. (In fact, it's still only a macro in C99.)
It's possible to create an in memory SQlite database: ``` rc = sqlite3_open(":memory:", &db); ``` but if I've understoodthe documentationcorrectly, this database is local to the app that created it. I have a requirement for an in memory SQLite database which can be accessed by several apps. Other than creating the database on a ramdisk, is there any way of doing this? This is for an embedded linux platform.
You can't share an in-memory database across processes – it'sreallynot designed to do that because it lacks the right sort of integrity promises (but which does mean it's faster) – so either put the database on more permanent storage (such as the ramdisk) or put the DB in a single process (the “database manager”) and use some form of local communication strategy (unix-domain sockets, named pipes, etc.) to allow the other processes to ask the database manager to do a query for them.
I am writing data to a file, however on sudden power offs I can see garbage data in the file sometimes. Sometimes the data is missing, sometimes it is editted and sometimes its a garbage data just before my first entry to the file on system reboot. Is there a way I can make sure fwrite is consistent? Just to add I am using "a" to append data to the file everytime. Further, the garbage values or indermined data which I am seeing in the file, is it really due to the fwrite() operation?
FAT32 is not ajournaling filesystem, so there is no way to guarantee consistent writes. Even if you flush the disk buffers after each write, the data could still be corrupted if there is a power loss just as the data is written to disk. To answer your other question, no, the garbage isn't caused byfwriteat all, it is because the filesystem has not completed the write operation in its entirety.
I would like to use the WINAPI RtlDecompressBuffer in User Mode to decompress a buffer previously compressed using RtlCompressBuffer. I have the code for compression but it seems that in order to decompress I need to know the size of the uncompressed data as the function needs it as a parameter. How can I do this without knowing the size of the uncompressed data? Perhaps I should use RtlDecompressFragment. A code sample would be great! Thanks in advance.
You don't need to know the size of the uncompressed data. All you have to do is reserve enough memory to hold all the uncompressed data and pass that to the API. If your buffer isn't big enough, the API will returnSTATUS_BAD_COMPRESSION_BUFFERand you then have to allocate a bigger buffer for the uncompressed data.
I wonder there are any tools or online tools which one can construct tree just giving datas. ex ; after giving datas, I want get a picture like ;google picture
Look intoGraphviz, and its descriptive languageDOT.
I have a C / C++ program which needs to read in a file that may or may not be gzip compressed. I know we can use gzread() from zlib to read in both compressed and uncompressed files - however, I want to use the zlib functions ONLY if the file is gzip compressed (for performance reasons). So is there any way to programatically detect or check if a certain file is gzipped from C / C++?
There is a magic number at the beginning of the file. Just read the first two bytes and check if they are equal to0x1f8b.
I thought it was retrieve at compile time from/proc/sys/net/core/somaxconn,but after I modified it to1024byecho 1024 > /proc/sys/net/core/somaxconn,theSOMAXCONNis still128in my programe. ``` printf("---------------set socket to listen,maxconn is %d--------------\r\n\r\n", SOMAXCONN); // set socket to listen if (listen(sock_listen, SOMAXCONN) != 0)... ``` I've checkedsys/socket.hbut it's not there... Where/how can I change its value?
On my system it's defined inbits/socket.h ``` /* Maximum queue length specifiable by listen. */ #define SOMAXCONN 128 ``` According tothis, you don't need to use SOMAXCONN. Just specify number you want and it will be limited to actual maximum.
I want to write a method which takes two pointers to ints and changes the values they point to. Something like: ``` int main() { int a = 3; int b = 1; change(&a, &b); return 0; } void change(int *a, int *b) { int t = a; *a = *b; *b = *t; } ``` I have a problem understanding how to save a copy ofaand point to it fromblater.
You do it like this: ``` int temp = *a; // remember actual value "a" points to *a = *b; // copy value "b" points to onto value "a" points to (will overwrite that value, but we have a copy in "temp") *b = temp; // now copy value "a" originally pointed to onto value "b" points to ```
I would like to massively useinlinein my project to speed up performance. As far as I know the compilermightapply inline or not; it is up to the compiler. It is not clear to me what I can do to make this possible, but before going that direction, do you know a way to check that inlinining really occurred or not in the output binary?
Usegcc -Winlineto get warnings when an inline function is not inlined. Use__attribute__ ((always_inline))to force functions to be inlined. Having said that, be warned that you can screw up performance, compile time and get huge code bloat if you use inlining injudiciously.
I want to make GUI for my application. It should work on multiple platforms. I want most of the code to be portable for all the OS (unix, windows, MAC). GTK and GLib looks as a good solution. I want to use native APIs too How to do this all??
Qtmay be good for that.
I packed my VC application in release mode and tested in a clean Windows XP/2003. Once I run the application, it could not load my dll and reports the system error code 14001, which is 'ERROR_SXS_CANT_GEN_ACTCTX'. The api which returns the error is LoadLibrary Can anybody help me out?
The problem was in side-by-side assemblies, clean Windows XP didn't have necessary assemblies, I think VC80.CRT or VC90.CRT (most probably). See about side-by side assemblieshere. You have 2 options to solve this issue: deploy assemblies with your application or build your application with static CRT libraries using /MT flag.
Is there a way to find out day of the week given date in just one line of C code? For example Given 19-05-2011(dd-mm-yyyy) gives me Thursday
As reported also byWikipedia, in 1990 Michael Keith and Tom Craver published an expression to minimise the number of keystrokes needed to enter a self-contained function for converting a Gregorian date into a numerical day of the week. The expression does preserve neitherynord, and returns a zero-based index representing the day, starting with Sunday, i.e. if the day is Monday the expression returns1. A code example which uses the expression follows: ``` int d = 15 ; //Day 1-31 int m = 5 ; //Month 1-12` int y = 2013 ; //Year 2013` int weekday = (d += m < 3 ? y-- : y - 2, 23*m/9 + d + 4 + y/4- y/100 + y/400)%7; ``` The expression uses thecomma operator, as discussed inthis answer. Enjoy! ;-)
I have a char array in the form ofmm/dd/yy(as the user was asked to enter a date). How do I split the array, and remove the/'s, and putmm,ddandyyinto 3 different integers?
I would use sscanf to parse the string: ``` int m, d, y; sscanf("05/18/11", "%02d/%02d/%02d", &m, &d, &y); ``` This will parse the date into the three integer values. In addition, to verify that the input data was formatted properly, you should also check that sscanf returned 3, indicating that all three values were properly parsed. See the followingworking example, which includes some basic error checking.
Does anyone know for a tool that allows a c executable to be run in the browser? I'm looking for a javascript, java, or flash solution because I don't have privileges to run c executables on the server. The executables are basic input and output programs.
Looking at your comments, I hear you mention students and running simple programs. As a suggestion, you might want to look intoCodePad. This will let you interpret simple C programs. Note that everything needs to be in one place, so you'll have to combine C and header files. Here is a sample: http://codepad.org/qQS31BwM EDIT Here's another one I found: http://ideone.com/ When you run the program, at the bottom there is a link for input. You can use it to run the program with given input as entered.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago. How I can convert milliseconds to minutes or hours, in Objective-C or C?
Just use simple division. Use floating point numbers so that you don't lose precision from rounding. ``` float milliseconds = 966000.0; float seconds = milliseconds / 1000.0; float minutes = seconds / 60.0; float hours = minutes / 60.0; ```
I want to set the MTU in or to get some device details, but I don't want to use system("ifconfig ..."). Is there any way to do it in C? Some like libifconfig.so? The source code of MTU can be foundhere. But I really don't too much time right now. How can I get the name of ALL the available interfaces (I have plenty in my system)
It can be done withioctl. Seenetdevice(7). I'm guessingSIOCGIFMTUandSIOCSIFMTUare what you're looking for. I don't know if it's standard, update your question if you need to support other Unixes. EDIT To get the interfaces on your machine (untested): ``` int sock; struct ifconf *conf; sock = socket(AF_INET, SOCK_STREAM, 0); ioctl(sock, SIOCGIFCONF , (char*) conf); ``` Don't be sloppy and don't forget to check the return values. I don't check them here because I don't care; you probably do.
This is the command I'm using: ``` rsync --partial --timeout=60 --rsh='/usr/bin/ssh -i /root/.ssh/id_rsa' /path/file user@host:/remote_path/ ``` This works when I run it on the command line, but does not work when I use system() in my C program. Correction: This call will not work after boot up, no matter how long the program runs. If the program is restarted it will work every time no matter how many times the program is run. ``` status = system("rsync --partial --timeout=60 --rsh='/usr/bin/ssh -i /root/.ssh/id_rsa' /path/file user@host:/remote_path/"); ``` The return value from rsync is 12: Error in rsync protocol data stream.
Turns out that the problem was the environment variables. HOME was set to '/' on start up instead of '/user'. ssh was unable to locate the known_hosts file and therefor the auto-login failed, causing rsync to fail.
I have a function in C that calls another software to execute and generate a file then its manipulates the data e.g. ``` void main() { function(); //manipulate data in output.txt } void execute() { system("./test input.txt output.txt"); } ``` for some reason the output.txt file is not being generated by full...how does the system call work? will execute return to main before system call ends? if yes how can I solve this? Im working on ubuntu using gcc
Check the result of system() ALWAYS. Ensure that it executed successfully(ie. returns 0 or whatever is a successful result for 'test')When system executes it runs through /bin/sh (on unix/linux anyway). However since you're specifying it with './test' make sure that you're operating in the working directory that you THINK you are. Complex systems(and poorly designed ones) change directories like underwear.
Quick question, hoping someone can verify. After a fork, if you callclose(2)in the parent, stderr in the child is unaffected. However, if you callclose(2)in the child, stderr in the parent is closed. Does that seem right? I tested this in FreeBSD and it seems to be the case, but I'm not sure why. I would expect that either they both don't affect each other or they do, but not this. Any insight?
After a fork, every open file descriptor in the parent gets dup'ed, so any closeafterthe fork won't affect either the parent or the child. Unless, you're doing it not properly (i.e. not checking the output of thefork()system call).
I am trying to complete a college assignment, and the marking criteria specifies 5% for memory management - specifically for having no memory leaks. As I understand it, memory leaks in simple C programs, are only caused by pointers which have become abandoned by the program - ie, malloc/calloc/etc calls which are never have a correspondingfree. My question is in 3 parts: Whats the simplest way on Solaris and OSX to 'prove' that you haven't leaked any memory?Does XCode have any tools to help determine memory leaks?Does the operating system release all previously allocated memory within a c program once the process ends?
Valgrindis your friend.
What does it mean to numerically sort alpha characters in opposite of lexicographic, like in K&R 5-14 with option-n
It means to treat a string as a single numeric value instead of as a series of characters that happen to be numeric. K&R shows you thenumcmpfunction to use just above exercise 5-14. It converts thechar*arguments todoubleand compares them numerically, instead of comparing the strings one character at a time. That way, the string103gets sortedafterthe string23because 103 is greater than 23. Comparing as strings,103would sortaheadof23because the character code for1is less than the character code for2.
I built a dynamic lib called InterfaceLayer.so. When I call: ``` > nm InterfaceLayer ``` As output, I get some symbols that look like: ``` 00000e28 T _Z5startv ``` while I was expecting it to be "start", just as the name of the function I defined in the code. Why does this happen?
That's because of C++ name mangling ``` nm -C ``` demangles them. To prevent name mangling, use a C compiler (gcc, not g++), name your source file .c (not .cpp)or declare extern "C": . my.h ``` extern "C" { void start(); void finish(); } ``` This will give them "C" linkage, meaning they can't be overloaded, cannot pass by reference, nothing c++ :)
If the user typetime_tis defined as__darwin_time_t, which itself is defined aslongin MacOS X, why does the following code outputs8 Time is (null)? Maybe it's something silly, but I can't really understand it. ``` #include <stdio.h> #include <time.h> int main(void) { time_t time = 0x7FFFFFFFFFFFFFFF; printf("%lu\n" "Time is %s\n", sizeof(time_t), ctime(&time)); return 0; } ```
Time 0x7FFFFFFFFFFFFFFF appears to be around the year 292,471,210,647 AD, which undoubtedly causesctimeto exceed the 26 characters it is guaranteed by C99, so it returns NULL rather than overflowing its buffer. In general, try to avoid any dates that occur after the Morlocks go to war with the Eloi.
Say a C program might trigger an exception of opcode0xCCHow can I catch it? I tried: ``` __try { ...some code } __except(GetExceptionCode()==EXCEPTION_EXECUTE_HANDLER) { _tprintf(_T("Error\n"),i); return 0; } ``` This is not working for me. What am I doing wrong? Thanks!
You're not checking for the right exception code. int 3throwsEXCEPTION_SINGLE_STEP. You handle it this way : ``` __try { // some code that might cause an int3 } __except(GetExceptionCode() == EXCEPTION_SINGLE_STEP ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { // error handling of int3 } ``` EDIT: Please note that a code running with a debugger attached willnotsee the exception, because the debugger handles it and clears it before passing the hand back to the code.
I am trying to do a simple post using libcURL. I noticed that if I define my data as char const data[] = "Some data"; It does not POST. If I use char const *data = "Some data"; It does POST. The main issue is [] vs *. Since an array is a pointer I don't understand why it won't post using the array style. Any help is greatly appreciated. Thanks, Greg
libcurl will POST the data you pass to it, with for example theCURLOPT_POSTFIELDSoption. It does not distinguish between a char array and a pointer to data as long as you make sure you pass it on correctly. A very simple post example can be found here:http://curl.haxx.se/libcurl/c/simplepost.html
Folks, I had another issue now regarding tolibmysqlclient-dev api Here the story: I created about 10 threads which will do SQL query in every 2 seconds, and loop, in math you could say 10 query in 2 secondsin the same time, and it ended itself with MySQL error messagelost connection during SQL query Questions: in these case, is my algorithm will always cause MySQL server lost connection ?if so, will these issue appear if I use another db (say Oracle, Postgre, etc), or result will same?
What are you doing in the thread that loses the connection, and what are the other threads doing at the same time?It depends. Consider your question the equivalent of "my car makes a funny noise when I drive down Street X. Should I get a new car?". If the noise is due to you falling into a pothole, changing cars won't make any difference.
Just for confirmation. When an audio player, created via OpenSL ES for Android, finishes playing a buffer, is that buffer automatically freed by the Garbage collector? Or do I need to free the buffer myself? If it is the latter, I could use some help. But as for now, I won't post any code until I get told that I need to do it myself...
The buffer queue doesn't actually allocate buffer memory itself (or need to free it), you pass in pointers to memory you have allocated via the 'enqueue' function. You will need to free the memory you allocated when you're finished playing buffers. As OpenSL ES is a native library in C++, it knows nothing of garbage collection, any memory you allocate for the API must be freed by you, and objects you create must have 'destroy' called on them to clean up internal memory.
Is it possible to create PHP extensions with Haskell? Usually PHP extensions are written using C. Is using Haskell FFI to provide functionality for a stub C extension possible (or even a good idea)? What are the caveats to such an approach? Does Zend perform some magic in the background that would disrupt such a scheme?
You can certainly do this, though I'm not sure anyone has tried. Haskell interoperates with C viaits FFI mechanism, and you can certainly: Call Haskell from C so if you can call C from PHP, and that C calls Haskell, you're in business. Why would you want to do this? Faster, safer, simple code for your core algorithms or safety-critical code, perhaps. Or to take advantage of say, a parallel or multicore server backend via Haskell.
Say I have the following code: ``` struct test* t1; t1 = get_t(1); ``` ... whereget_tis: ``` struct test* get_t(int); ``` How can I refactor the above code and put it in a function? Something like the following: ``` void r1(?* t, ?* (fn*)(int)) { t = fn(1); } /* ... */ struct test* t1; r1(t1, &get_t); ```
usevoid *param, a pointer to anything ... commonly used in glib asgpointer
I am new to gimp programming. I have installed the gimp and using it in Visual Studio 2010. The configuration is ok. I was trying to compile the code from here:http://git.gnome.org/browse/gimp/tree/plug-ins/common/blur.c The problem is that when includingconfig.h, I am getting this: fatal error C1189: #error : "config.h must be included prior to stdplugins-intl.h" where is thisconfig.hfile located? Also, I have problem with this code: GimpRunMode run_mode; run_mode = param[0].data.d_int32; it says a value of typegint32cannot be assigned to an entity of typeGimpRunMode.
config.h is generated when you run ./configure in the root of the gimp directory. If you have run configure it should have ended up in the root of the gimp directory. As to your other problem, try casting the value before assigning it: ``` GimpRunMode run_mode; run_mode = (GimpRunMode)param[0].data.d_int32; ```
Thisis a c program demonstrating some basic usage of the libxml2 library. Below is quoted from the main function: ``` LIBXML_TEST_VERSION example1Func(argv[1]); ``` What does this statement stand for? I can only tell that LIBXML_TEST_VERSION is obviously a constant, and after that is a function call, that function returns nothing (void). But I've no idea what it means the statement in whole.
LIBXML_TEST_VERSIONis not a constant - it's a macro - see the documentation here: ``` Macro: LIBXML_TEST_VERSION #define LIBXML_TEST_VERSION Macro to check that the libxml version in use is compatible with the version the software has been compiled against ``` It's also nothing to do with the call toexample1func()- the code should look like this (comments are mine): ``` LIBXML_TEST_VERSION // test libxml version example1func(); // call example1func ```
How can I know in a C program, on which physical processor and core my code is running? I'm using Linux and gcc 4.4.3.
sched_getcpu() call returns virtual CPU number. Mapping of virtual CPU to real CPU info is in /proc/cpuinfo. If your system supports VDSO, thensched_getcpu()is relatively fast. CPU number can be also obtained usingCPUIDinstruction, but it is slower thansched_getcpu().