question
stringlengths
25
894
answer
stringlengths
4
863
I'm experimenting with pthread library and I've got the following piece of code: ``` for (int j = 0; j < NUM_THREADS; j++) { int *threadNum = malloc(sizeof(int)); *threadNum = j; pthread_create(..., (void *)threadNum); } ``` Since there is no free, this code has a memory leak. Where should I place free to avoid memory leaks? If I simply write something like: ``` int *threadNum = 0; *threadNum = j; ``` This leads to a segfault. And I can't place free inside the scope, because I'm using pthread_join in the next few lines.
The thread which uses it (since it is passed as the parameter) should free it when it is done with it.
I am trying to write something like this: ``` #define COV_ON(x) \ #ifdef COVERAGE_TOOL \ _Pragma (COVERAGE #x) #endif ``` Is there any way to defineCOV_ONlike this? I know what I have done above is wrong as I can't have#ifdefinside #define. (#is not an allowed character in#define). So is there any solution?
Not possible. Do it the other way around: ``` #ifdef COVERAGE_TOOL #define COV_ON(x) _Pragma (COVERAGE #x) #else #define COV_ON(x) #endif ```
Gstreamer on IPhone, Android, Blackberry, Nokia. How can we make it using C or D or Vala languages? Or should we just use Java or Lua? 1) Glib porting to IPhone, Android, Blackberry, Nokia is available? For Android, there is a tipshttp://gstreamer.freedesktop.org/wiki/GstreamerAndroid_InstallInstructionsFor IPhone, no ideaFor Nokia, no ideaFor Blackberry, no idea Wish someone put some answers and feedback on this topic.
I don't know much about mobile development, but your best bet would be to look intoGtkD. This project provides bindings to GTK and GObject. AFAIK no D bindings to GStreamer exist yet, butcalling C code from D isn't difficult. Furthermore, to compile for ARM architectures, you'll probably want to look atGDCsince the reference DMD implementation only targets x86/x64.
How would one create a make file for running e.g. xml parser with the following command line command ``` gcc source.c -I/usr/include/libxml2 -lxml2 -o output ``` I use this to include libxml when compiling using the command line. How would this be made using a make file instead of the command line usage?
``` SOURCES:=source.c OBJECTS:=$(SOURCES:%.c=%.o) CC=gcc CFLAGS=-g -Wall -I/usr/include/libxml2 LD=gcc LDFLAGS= LIBS=-lxml2 TARGET:=output all: $(TARGET) $(TARGET): $(OBJECTS) $(LD) -o $@ $(OBJECTS) $(LDFLAGS) $(LIBS) .c.o: $(CC) $(CFLAGS) -c $< -o $@ depend: $(CC) $(CFLAGS) -MM $(SOURCES) > .depend clean: rm -f $(OBJECTS) $(TARGET) .depend: depend include .depend ``` You can use this as a template, then add to/modify SOURCES, TARGET, CFLAGS, LDFLAGS and LIBS. Makefiles require TABs for indentation - so you'll need to fix the spaces if you copy-paste this.
How do I write a function for this in C language? y = 20 ln (x + 3) ? How do I write the ln function?
``` #include <math.h> double fun(double x) { return 20 * log( x + 3 ); //base-e logarithm! } //usage double y = fun(30); ``` For base-10 logarithm, uselog10().
what is gendep? it builds dependencies, how? any good book to read about this entire gnu make gamut?
Not an expert by any means, but it appears to look at the system calls to open() that a particular binary makes and looks to see if the opened file matches a particular regular expression. If it finds a match, it records this match in a file GNU make can parse. http://www.hep.phy.cam.ac.uk/~lester/gendep/index.html As far as GNU make, I know there's an O'Reilly book out there on the subject but this free tutorial does a good job going over the basics:http://www.gnu.org/software/make/manual/make.html
As all we know: the sequence of evalutation is determined by the priority and associativity. For this example,the associativity determined that a+b,then the result plus c. This is what ANSI C compliant compiler do(leave out the optimization).But will it be evaluated like foregoing manner in the title? In what compiler? In K&R C?
Let me throw this at you: Operator Precedence vs Order of Evaluation
Greetings Overflowers, I know in C we can define a struct inline with the variable declaration so that the struct type is specific to this variable. This is instead of defining the type alone then declaring the variable to be of that struct type. Is this possible in C#? Thank !
This is not possible in C#, however you can define an instance of an anonymous type like this: ``` var x = new { SomeField = 1, SomeOtherField = "Two" }; ``` This would effectively be the same, giving you an instance of a type that is specific to that variable and cannot used outside the variable's scope.
Until now I used Netbeans and want to try eclipse now. I went to the eclipse site and wanted to download it. I am totally confused with the package. There are different packages for C, Java, PHP ... development. Well I want to develop in all these languages and in addition in PERL and Python. When I download one of these packages, do I have to add plugins for all the other languages, or is there a general package, which is packed with many plugins?
As far as I know there is not a ready-made package that contains support for everything. You can download one of the packages and add support for other languages, frameworks etc. later by installing more plug-ins (select Help / Install New Software... in Eclipse's menu).
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 does OS know to differentiate between ``` int x = 0; //variable ``` and ``` int 0x80; //interrupt, call system_call() ```
By co-incidence, the first 3 letters of 'integer' are the same as the first 3 letters of 'interrupt'. Two different languages have used these 3 letters, and they mean different things. Similarly, 'chat' is a word in both French and English, but in French it means 'cat' and in English it means 'talk'.
this question bothers me this few days. I want to read a string for example, input = (-0.001999,-0.919191,-0.777777,999999.999999) using sscanf. And my code is ``` char x[10], y[10], z[10], angle[10]; sscanf( input+1, "%[^,],%[^,],%[^,],%[^)]", &x, %y, &z, &angle); printf("%s %s %s %s\n", x, y, z, angle); ``` the expected result is x=-0.001999 y=-0.919191 z=-0.777777 a=999999.999999 but my printf shows : x=-0.001999 y=-0.919191 z=999 a=999999.999999 can somebody help me figure out where the problem is ?? thx!
angle is not big enough to hold the input data and thus z is getting overwritten. Try this: ``` char x[80], y[80], z[80], angle[80]; ```
I have wrote a sharedlibA.so. My programPwill dynamic loadlibA.so(uses dlopen, dlsym...). Here's my problem: InlibA.so, I have to use functions (such asfun1()) in a staticlibB.a, butlibB.ais not compiled with-fPIC, and I can't recompilelibB.a, so I can't linklibB.aintolibA.so. I have tried linklibB.aintoP(with -Wl,--whole-archive), in order to let dynamic loader linkfun1()intolibA.sowhen it is loaded. However, that doesn't work. And I'm pretty sure thatfun1()is inP(I checked it with:nm P | grep "fun1"). How can I do? Thanks in advance!
If you want to linklibB.aintoP, so that the functions are available tolibA.sowhen it is loaded byP, you need to compilePwith the-rdynamicoption.
Perhaps not a really important question, but just starting out in c. Why will this not compile correctly? ``` #include <stdio.h> #include <stdlib.h> void main() { int i = 15; char word[100]; itoa (i,word,10); printf("After conversion, int i = %d, char word = %s", i, word); } ``` I keep getting the error message ``` Undefined symbols: "_itoa", referenced from: _main in ccubsVbJ.o ld: symbol(s) not found collect2: ld returned 1 exit status ```
Use sprintf instead, itoa is not part of the C standard and it's probably not included in your stdlib implementation. ``` sprintf(word,"%d",i); ``` UPDATE: As noted in the comments snprintf is safer to use to avoid buffer overflows. In this case it's not necessary because your buffer is longer than the largest integer that can be stored in a 32-bit (or 64-bit integer). But it's good to keep buffer overflows in mind.
The following C statement is invalid in C++. ``` int *a = malloc(sizeof(*a)); ``` Why? How do you fix it? The answer is : C performs an implicit conversion for void *, while C++ does not. Use an explicit cast to work around this. My question is: explicit cast to whom and where? thanks.
In C++ you have to say ``` int *a = (int*)malloc(sizeof(*a)); ``` because casting avoid*into anint*isn't implicitly done by the compiler. Better yet, just usenewanddelete: ``` int *a = new int(); ```
1)(pointer) What is %p used for? To show the address or something else? (can you give example too?) 2) As using graph.h library and creating graphs, ellipse() function has 6 parameters. What are them? I could't find full list of them. Thank you editsorry. it should be<graphics.h>library. and yes, it is an external library that wanted us to use. ps: not homework.
%pis used to print out a pointer's value (the address) usingprintf:printf("%p", &printf); //Prints out the address of the 'printf' functionI have no idea whatgraph.hyou're referring to, and I doubt many others do either; could you post more information on what that library is for?
``` int (*rdPtrList[4])(unsigned int addr, unsigned int data); ``` The above declares an array of size 4 of pointers for functions that returns an int and takes two unsigned int. I would like to make a pointer to this array. Is this possible in C?
Leaving out the parameters to keep the following easier to read: ``` p -- p *p -- is a pointer (*p)[4] -- to a 4-element array *(*p)[4] -- of pointers (*(*p)[4])() -- to functions int (*(*p)[4])(); -- returning int. ```
I would like to use a variable in the ldap command ldap_search_s in C. I used strcat to create the string i needed. The error is "bad search filter". I'm pretty sure it has something to do with the string i have created. Here is my code: ``` char *numero = randomID1() ; char *var1="\"(studentID="; char *var2= numero; char *var3= ")\" "; char var4[80]; strcpy (var4,var1); strcat (var4, var2); strcat (var4,var3); char *attr[] = { "cn","sn","studentID", NULL }; ldap_search_s( ld, "dc=******,dc=fr", LDAP_SCOPE_SUBTREE, var4, attr , 0 , &res ) ```
I haven't tried it, but after looking at the documentation, I would suspect you should not include the double quotes in the filter: ``` char *var1="(studentID="; char *var2= numero; char *var3= ")"; ```
If make fails with: "bmake: don't know how to make blah", what/where is the best place to start looking for problems? why did it fail? What does it mean by "don't know"?
See theGNU Make Debugger
When i execute this code ``` #include<stdio.h> int main() { int (*x)[5]; printf("\nx = %u\nx+1 = %u\n&x = %u\n&x + 1 = %u",x,x+1,&x,&x+1); } ``` This is the output in C or C++: ``` x = 134513520 x+1 = 134513540 &x = 3221191940 &x + 1 = 3221191944 ``` Please explain. Also what is the difference between: int x[5]andint (*x)[5]?
int x[5]is an array of 5 integersint (*x)[5]is apointer toan array of 5 integers When you increment a pointer, you increment by the size of the pointed to type.x+1is therefore5*sizeof(int)bytes larger than justx- giving the8048370and8048384hex values with a difference of 0x14, or 20. &xis a pointer to a pointer - so when you increment it you addsizeof(a pointer)bytes - this gives thebf9b08b4andbf9b08b8hex values, with a difference of 4.
I have some code that moves bytes in a buffer usingmemmove(). The buffer is accessed by multiple threads. I get a very weird behavior; sometimes the buffer it's not what it should be and I was thinking ifmemmove()or/andmalloc()are thread safe. I'm working on iOS (in case this is platform dependent).
In an implementation that provides threads,mallocwill normally be thread safe (i.e., it will take steps to assure the heap doesn't get corrupted, even ifmallocgets called from multiple threads). The exact way it will do that varies: some use a single heap, and internal synchronization to ensure against corruption. Others will use multiple heaps, so different threads can allocate memory simultaneously without collisions. memmovewill normally be just like if you did assignments in your own code -- if you're sharing a buffer across threads, it's your responsibility to synchronize access to that data.
How to get the "inside" of a tab control, i.e. the area in which you can place controls? ``` // doesn't work: WINDOWINFO tabsInfo; GetWindowInfo(GetDlgItem(hwndDialog, IDC_TABS), &tabsInfo); MoveWindow(someHwnd, tabsInfo.rcClient.left, tabsInfo.rcClient.top, ... ``` tabsInfo.rcClient gives the entire region used by the tab control, including its own controls
You can useTabCtrl_AdjustRect-- pass in the bounding rectangle of the tab control and on output, the rectangle will be adjusted to the content area. Also, if you only need the client rectangle of the window, it's simpler to useGetClientRectinstead ofGetWindowInfo.
Let say i have a listListand i havepthread_t t1that polls from the list and i have many other pthreads that insert elements to the list. The list is locked with a locklistLock. whent1has the lock - if the list is empty he goes to sleep withpthread_cond_wait(..)and when a thread inserts to the list he signals him. my question is: ift1is in wait state and there are many threads that are stuck inpthread_mutex_lock(&listLock), when the lock will be unlocked, willt1have a priority to get the lock or will he "fight" the other threads to get the lock? thank you
It will fight, however it's a fair fight. All callers are put into a queue based on the order that they called the wait. It's completely deterministic. However given the way that you're using things, you may possibly want to think about using a read/write lock. It allowsNsimultaneous readers, but anytime something tries to do awriteit will lock everyone down until it's done.
In my c++ application I want to change working directory to specified one. But when I specifying"~/dev/"as working directorychdir()fails and returns -1. Instead it works when I'm specifying"/home/myusername/dev". Why this happens? How can I solve this problem (except of checking if string first charachter is~and replacing it with/home/myusername)?
The expansion of tilde (~) to HOME environment variable is done by bash. That expansion is done before that is passed to chdir command. The bottom line is ~ is handled by bash, not by chdir command. So you can not use it in chdir() function call. In order to find other kind of expansions (and the details of ~ expansion) done by bash, checkthis link.
Greetings, I had been studying C++ for a while now. I'm getting in to pointers now. But I'm creating a program on C++ that will ask for a string("%s") input. And I want to display its character on a different line. But when I run the program I get the wrong letters. Here's my code; ``` #include<stdio.h> #include<stdlib.h> main() { char* name; name = (char *)malloc(sizeof(char)); printf("Enter string: "); scanf("%s", name); while(*name != '\0') { printf("%c", name); *name++ } } ``` Your reply is highly appreciated.
malloc(sizeof(char))allocates space for a single character. This is probably not what you want. As the comments below point out, the dereferencing in*name++is pointless. It does no harm, but perhaps indicates that you're thinking incorrectly about something.name++has the same effect.
I am currently reading Cormen's "Introduction to Algorithms" and I found something called a sentinel. It's used in the mergesort algorithm as a tool to decide when one of the two merging lists is exhausted. Cormen uses the infinity symbol for the sentinels in his pseudocode and I would like to know how such an infinite value can be implemented in C.
A sentinel is just a dummy value. For strings, you might use a NULL pointer since that's not a sensible thing to have in a list. For integers, you might use a value unlikely to occur in your data set e.g. if you are dealing with a list ages, then you can use the age -1 to denote the list.
Is there any way how tomalloc()a 2D matrix in C? I have successfully triedmalloc()ing a 1D field, but in matrix I am getting errors.
float *mat2d = malloc( rows * cols * sizeof( float )); to access a value from the matrix use this adressing scheme: float val = mat2d[ x + y * cols ];
this question bothers me this few days. I want to read a string for example, input = (-0.001999,-0.919191,-0.777777,999999.999999) using sscanf. And my code is ``` char x[10], y[10], z[10], angle[10]; sscanf( input+1, "%[^,],%[^,],%[^,],%[^)]", &x, %y, &z, &angle); printf("%s %s %s %s\n", x, y, z, angle); ``` the expected result is x=-0.001999 y=-0.919191 z=-0.777777 a=999999.999999 but my printf shows : x=-0.001999 y=-0.919191 z=999 a=999999.999999 can somebody help me figure out where the problem is ?? thx!
angle is not big enough to hold the input data and thus z is getting overwritten. Try this: ``` char x[80], y[80], z[80], angle[80]; ```
I have wrote a sharedlibA.so. My programPwill dynamic loadlibA.so(uses dlopen, dlsym...). Here's my problem: InlibA.so, I have to use functions (such asfun1()) in a staticlibB.a, butlibB.ais not compiled with-fPIC, and I can't recompilelibB.a, so I can't linklibB.aintolibA.so. I have tried linklibB.aintoP(with -Wl,--whole-archive), in order to let dynamic loader linkfun1()intolibA.sowhen it is loaded. However, that doesn't work. And I'm pretty sure thatfun1()is inP(I checked it with:nm P | grep "fun1"). How can I do? Thanks in advance!
If you want to linklibB.aintoP, so that the functions are available tolibA.sowhen it is loaded byP, you need to compilePwith the-rdynamicoption.
Perhaps not a really important question, but just starting out in c. Why will this not compile correctly? ``` #include <stdio.h> #include <stdlib.h> void main() { int i = 15; char word[100]; itoa (i,word,10); printf("After conversion, int i = %d, char word = %s", i, word); } ``` I keep getting the error message ``` Undefined symbols: "_itoa", referenced from: _main in ccubsVbJ.o ld: symbol(s) not found collect2: ld returned 1 exit status ```
Use sprintf instead, itoa is not part of the C standard and it's probably not included in your stdlib implementation. ``` sprintf(word,"%d",i); ``` UPDATE: As noted in the comments snprintf is safer to use to avoid buffer overflows. In this case it's not necessary because your buffer is longer than the largest integer that can be stored in a 32-bit (or 64-bit integer). But it's good to keep buffer overflows in mind.
The following C statement is invalid in C++. ``` int *a = malloc(sizeof(*a)); ``` Why? How do you fix it? The answer is : C performs an implicit conversion for void *, while C++ does not. Use an explicit cast to work around this. My question is: explicit cast to whom and where? thanks.
In C++ you have to say ``` int *a = (int*)malloc(sizeof(*a)); ``` because casting avoid*into anint*isn't implicitly done by the compiler. Better yet, just usenewanddelete: ``` int *a = new int(); ```
1)(pointer) What is %p used for? To show the address or something else? (can you give example too?) 2) As using graph.h library and creating graphs, ellipse() function has 6 parameters. What are them? I could't find full list of them. Thank you editsorry. it should be<graphics.h>library. and yes, it is an external library that wanted us to use. ps: not homework.
%pis used to print out a pointer's value (the address) usingprintf:printf("%p", &printf); //Prints out the address of the 'printf' functionI have no idea whatgraph.hyou're referring to, and I doubt many others do either; could you post more information on what that library is for?
``` int (*rdPtrList[4])(unsigned int addr, unsigned int data); ``` The above declares an array of size 4 of pointers for functions that returns an int and takes two unsigned int. I would like to make a pointer to this array. Is this possible in C?
Leaving out the parameters to keep the following easier to read: ``` p -- p *p -- is a pointer (*p)[4] -- to a 4-element array *(*p)[4] -- of pointers (*(*p)[4])() -- to functions int (*(*p)[4])(); -- returning int. ```
I would like to use a variable in the ldap command ldap_search_s in C. I used strcat to create the string i needed. The error is "bad search filter". I'm pretty sure it has something to do with the string i have created. Here is my code: ``` char *numero = randomID1() ; char *var1="\"(studentID="; char *var2= numero; char *var3= ")\" "; char var4[80]; strcpy (var4,var1); strcat (var4, var2); strcat (var4,var3); char *attr[] = { "cn","sn","studentID", NULL }; ldap_search_s( ld, "dc=******,dc=fr", LDAP_SCOPE_SUBTREE, var4, attr , 0 , &res ) ```
I haven't tried it, but after looking at the documentation, I would suspect you should not include the double quotes in the filter: ``` char *var1="(studentID="; char *var2= numero; char *var3= ")"; ```
If make fails with: "bmake: don't know how to make blah", what/where is the best place to start looking for problems? why did it fail? What does it mean by "don't know"?
See theGNU Make Debugger
When i execute this code ``` #include<stdio.h> int main() { int (*x)[5]; printf("\nx = %u\nx+1 = %u\n&x = %u\n&x + 1 = %u",x,x+1,&x,&x+1); } ``` This is the output in C or C++: ``` x = 134513520 x+1 = 134513540 &x = 3221191940 &x + 1 = 3221191944 ``` Please explain. Also what is the difference between: int x[5]andint (*x)[5]?
int x[5]is an array of 5 integersint (*x)[5]is apointer toan array of 5 integers When you increment a pointer, you increment by the size of the pointed to type.x+1is therefore5*sizeof(int)bytes larger than justx- giving the8048370and8048384hex values with a difference of 0x14, or 20. &xis a pointer to a pointer - so when you increment it you addsizeof(a pointer)bytes - this gives thebf9b08b4andbf9b08b8hex values, with a difference of 4.
I have some code that moves bytes in a buffer usingmemmove(). The buffer is accessed by multiple threads. I get a very weird behavior; sometimes the buffer it's not what it should be and I was thinking ifmemmove()or/andmalloc()are thread safe. I'm working on iOS (in case this is platform dependent).
In an implementation that provides threads,mallocwill normally be thread safe (i.e., it will take steps to assure the heap doesn't get corrupted, even ifmallocgets called from multiple threads). The exact way it will do that varies: some use a single heap, and internal synchronization to ensure against corruption. Others will use multiple heaps, so different threads can allocate memory simultaneously without collisions. memmovewill normally be just like if you did assignments in your own code -- if you're sharing a buffer across threads, it's your responsibility to synchronize access to that data.
How to get the "inside" of a tab control, i.e. the area in which you can place controls? ``` // doesn't work: WINDOWINFO tabsInfo; GetWindowInfo(GetDlgItem(hwndDialog, IDC_TABS), &tabsInfo); MoveWindow(someHwnd, tabsInfo.rcClient.left, tabsInfo.rcClient.top, ... ``` tabsInfo.rcClient gives the entire region used by the tab control, including its own controls
You can useTabCtrl_AdjustRect-- pass in the bounding rectangle of the tab control and on output, the rectangle will be adjusted to the content area. Also, if you only need the client rectangle of the window, it's simpler to useGetClientRectinstead ofGetWindowInfo.
Let say i have a listListand i havepthread_t t1that polls from the list and i have many other pthreads that insert elements to the list. The list is locked with a locklistLock. whent1has the lock - if the list is empty he goes to sleep withpthread_cond_wait(..)and when a thread inserts to the list he signals him. my question is: ift1is in wait state and there are many threads that are stuck inpthread_mutex_lock(&listLock), when the lock will be unlocked, willt1have a priority to get the lock or will he "fight" the other threads to get the lock? thank you
It will fight, however it's a fair fight. All callers are put into a queue based on the order that they called the wait. It's completely deterministic. However given the way that you're using things, you may possibly want to think about using a read/write lock. It allowsNsimultaneous readers, but anytime something tries to do awriteit will lock everyone down until it's done.
In my c++ application I want to change working directory to specified one. But when I specifying"~/dev/"as working directorychdir()fails and returns -1. Instead it works when I'm specifying"/home/myusername/dev". Why this happens? How can I solve this problem (except of checking if string first charachter is~and replacing it with/home/myusername)?
The expansion of tilde (~) to HOME environment variable is done by bash. That expansion is done before that is passed to chdir command. The bottom line is ~ is handled by bash, not by chdir command. So you can not use it in chdir() function call. In order to find other kind of expansions (and the details of ~ expansion) done by bash, checkthis link.
Greetings, I had been studying C++ for a while now. I'm getting in to pointers now. But I'm creating a program on C++ that will ask for a string("%s") input. And I want to display its character on a different line. But when I run the program I get the wrong letters. Here's my code; ``` #include<stdio.h> #include<stdlib.h> main() { char* name; name = (char *)malloc(sizeof(char)); printf("Enter string: "); scanf("%s", name); while(*name != '\0') { printf("%c", name); *name++ } } ``` Your reply is highly appreciated.
malloc(sizeof(char))allocates space for a single character. This is probably not what you want. As the comments below point out, the dereferencing in*name++is pointless. It does no harm, but perhaps indicates that you're thinking incorrectly about something.name++has the same effect.
I am currently reading Cormen's "Introduction to Algorithms" and I found something called a sentinel. It's used in the mergesort algorithm as a tool to decide when one of the two merging lists is exhausted. Cormen uses the infinity symbol for the sentinels in his pseudocode and I would like to know how such an infinite value can be implemented in C.
A sentinel is just a dummy value. For strings, you might use a NULL pointer since that's not a sensible thing to have in a list. For integers, you might use a value unlikely to occur in your data set e.g. if you are dealing with a list ages, then you can use the age -1 to denote the list.
Is there any way how tomalloc()a 2D matrix in C? I have successfully triedmalloc()ing a 1D field, but in matrix I am getting errors.
float *mat2d = malloc( rows * cols * sizeof( float )); to access a value from the matrix use this adressing scheme: float val = mat2d[ x + y * cols ];
Consider the following program: ``` #define _POSIX_C_SOURCE 200809L #include <time.h> #include <pthread.h> #include <signal.h> void timerfunc(union sigval val) { } int main() { struct sigevent sev = { .sigev_notify = SIGEV_THREAD, .sigev_notify_function = timerfunc }; timer_t t; timer_create(CLOCK_REALTIME, &sev, &t); timer_delete(t); pthread_exit(0); } ``` Linked with glibc, it not only fails to terminate, but it is unkillable except bykill -9/SIGKILL. Is this behavior permitted by the standard? Are there good workarounds aside from either always explicitly exiting the process (as opposed to just exiting all threads)?
Well,POSIX specifically saysit is ...impossible to determine the lifetime of the created thread... which implies that any lifetime is allowed. SIGEV_THREADis simply bad mojo, and should be avoided.
Does C have an equivalent to the Obj c #pragma mark?
Objective-C is a superset of C.#pragmadirectives are part of the C standard, so they also exist in Objective-C also. There are only a handful of#pragmadirectives that are actually standardised, but, any conforming compiler is supposed to ignore#pragmadirectives that it doesn't understand. The problem though, is that “legally” the same#pragmadirective can cause two conforming implementations to behave differently. In any case, if you are writing C code using Xcode, then you can use#pragma markfor organisation; just keep in mind that it may decrease portability.
I just found out that thegetline()function which is originally a GNU extension is now part of the POSIX 2008 standard. Is there some overview of how broadly is this version of POSIX supported?
I would just go ahead and use it. It's possible to implementgetline(but not the more powerfulgetdelim) as a very fast/efficient wrapper aroundfgets, so if you're willing to do that as a fallback, usinggetlinedoesn't really make your program any less portable. (Versus something like using__fpending, which cannot be implemented portably and requires an implementation-specific hack to emulate.) Also, of course, bothgetlineandgetdelimcan simply be implemented on top offlockfile/funlockfileandfgetc. It's not very efficient, but it will work anywhere.
I need to generate a simple "Hello World" ELF32 executable using gcc. I don't seem to have the gcc-elf command though. Is it possible to create ELF binaries instead of a.out without building gcc again? (I'm assuming it should be possible with some options, but am unsure how to proceed)
Check the file a.out$ file a.outa.out:ELF32-bit LSB executable, Intel 80386, version 1 (SYSV), for GNU/Linux 2.6.9, dynamically linked (uses shared libs), for GNU/Linux 2.6.9, not stripped I believe the default name is retained as a.out but the format is ELF.
I seem to be able to compile code that callswsprintfwith theMinGWgccif I have these includes (in this order): ``` #include <stdarg.h> #include <wingdi.h> #include <winuser.h> ``` But I feel like there might be some "cleaner" way to do this. Perhaps with only a single header inclusion. I arrived at this list by searching header files for missing symbols and then including headers one-by-one.
Include<Windows.h>
I have a C source code for as application that I want to use in my iPhone App. I thought the best way of doing it was to call the main method of that C Application in anNSOperationsubclass. This works fine, except for cases where something in the C application goes wrong and anexit()/abort()is called, which takes my whole iPHone App down with it. The C code is very lengthy and I dont want to go through it or disturb it in any way. I would like to know if I can bypass thoseexit()/abort()calls in theNSOperationso that it just quits the thread and not the whole application.
How about to compile with -Dexit=my_exit -Dabort=my_abort options and implement my_exit and my_abort as the following? ``` void my_exit(int status) { if (!/* check thread ID or so forth, and check during calling the NSOperation */) { exit(status); } } ```
I am trying to read user input with multiple fields. But the number of fields is not specified. I want to read all the words till the carriage return. i tried this code but it isnt working: ``` char str[256]; while(1) { scanf("%s", str); if(str[strlen(str)] == '\n') break; else printf("Got %s\n", str); } ``` Examples of user input:1. store file1I need to parse store and file1 and break out of the loop.2. store file1 file2I need to parse store, file1 and file2 and break out of the loop. Wondering how to break out of the loop at the carriage return. thanks.
Use ``` char str[256] scanf("%255[^\n]", str); /*edit*/ ``` which will read to a newline or (Edit:) 255 characters, whichever comes first.
``` enum protocol { ascii_prot = 3, /* arbitrary value. */ binary_prot, negotiating_prot = 4 /* Discovering the protocol */ }; ``` Bothbinary_protandnegotiating_protequals to4?
Yes.
Does %*d mean one or more integer? in sprintf function
It is used to manipulate the minimum width of the numerical value printed, and it specifically means that the width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted. In other words, if you wanted to use a width that was stored in a variable, you could do this: ``` int width = /* something */; printf("%*d", width, value); ``` EDIT: Oops! Correct syntax for sprintf is: ``` sprintf(buffer, "%*d", width, value); ```
I am using arc4random to generate a random number. I would like to generate a number between 1-9. How can I exclude 0? ``` int r = arc4random() % (9); NSLog(@"Random Number: %d",r); ```
int r = (arc4random() % 8) + 1
hello everyone I found this function in Kernel of the Linux: ``` inline task_t *context_switch(task_t *prev, task_t *next) { ... switch_to(prev, next, prev); return prev; } ``` this function is making context switch, my question is why this function should be inline and not macro for example, thanks in advance...
It may not be a macro because a macro to do this would evaluate prev and next twice each, when they may be expressions with side effects. Also, after some searching I found that switch_to is (on some platforms) a macro that is a statement in braces, and therefore cannot return a value to be used in an expression. I found some of this info here:https://docs.blackfin.uclinux.org/doku.php?id=linux-kernel:task_switching
I am creating window inside my program, then sending HWND of this window to another application. Will drawing on window's HDC be valid for another process?
Windows are owned by other windows, not by processes. You can draw to any HWND on your desktop (at least if the window has the same integrity -- I'm not sure what happens if they don't). Web browsers that host plug-ins or tabs in a separate process generally make use of this functionality.
I have a C source code for as application that I want to use in my iPhone App. I thought the best way of doing it was to call the main method of that C Application in anNSOperationsubclass. This works fine, except for cases where something in the C application goes wrong and anexit()/abort()is called, which takes my whole iPHone App down with it. The C code is very lengthy and I dont want to go through it or disturb it in any way. I would like to know if I can bypass thoseexit()/abort()calls in theNSOperationso that it just quits the thread and not the whole application.
How about to compile with -Dexit=my_exit -Dabort=my_abort options and implement my_exit and my_abort as the following? ``` void my_exit(int status) { if (!/* check thread ID or so forth, and check during calling the NSOperation */) { exit(status); } } ```
I am trying to read user input with multiple fields. But the number of fields is not specified. I want to read all the words till the carriage return. i tried this code but it isnt working: ``` char str[256]; while(1) { scanf("%s", str); if(str[strlen(str)] == '\n') break; else printf("Got %s\n", str); } ``` Examples of user input:1. store file1I need to parse store and file1 and break out of the loop.2. store file1 file2I need to parse store, file1 and file2 and break out of the loop. Wondering how to break out of the loop at the carriage return. thanks.
Use ``` char str[256] scanf("%255[^\n]", str); /*edit*/ ``` which will read to a newline or (Edit:) 255 characters, whichever comes first.
``` enum protocol { ascii_prot = 3, /* arbitrary value. */ binary_prot, negotiating_prot = 4 /* Discovering the protocol */ }; ``` Bothbinary_protandnegotiating_protequals to4?
Yes.
Does %*d mean one or more integer? in sprintf function
It is used to manipulate the minimum width of the numerical value printed, and it specifically means that the width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted. In other words, if you wanted to use a width that was stored in a variable, you could do this: ``` int width = /* something */; printf("%*d", width, value); ``` EDIT: Oops! Correct syntax for sprintf is: ``` sprintf(buffer, "%*d", width, value); ```
I am using arc4random to generate a random number. I would like to generate a number between 1-9. How can I exclude 0? ``` int r = arc4random() % (9); NSLog(@"Random Number: %d",r); ```
int r = (arc4random() % 8) + 1
hello everyone I found this function in Kernel of the Linux: ``` inline task_t *context_switch(task_t *prev, task_t *next) { ... switch_to(prev, next, prev); return prev; } ``` this function is making context switch, my question is why this function should be inline and not macro for example, thanks in advance...
It may not be a macro because a macro to do this would evaluate prev and next twice each, when they may be expressions with side effects. Also, after some searching I found that switch_to is (on some platforms) a macro that is a statement in braces, and therefore cannot return a value to be used in an expression. I found some of this info here:https://docs.blackfin.uclinux.org/doku.php?id=linux-kernel:task_switching
I am creating window inside my program, then sending HWND of this window to another application. Will drawing on window's HDC be valid for another process?
Windows are owned by other windows, not by processes. You can draw to any HWND on your desktop (at least if the window has the same integrity -- I'm not sure what happens if they don't). Web browsers that host plug-ins or tabs in a separate process generally make use of this functionality.
If I have some lua code like this: ``` doSomething(function() print("Hello!") end) ``` How can I make it that, using the C API, I create C Lua function for doSomething that can then save the function passed to it to be executed a later date?
It's just a normal entry on the stack. Check it withlua_isfunction()then useluaL_ref()to generate a reference (so that the garbage collector doesn't steal it), and then maybelua_topointer()to store a pointer to this object, depends what you want to do with it. When you're finished it's just aluaL_unref().
is safe if I use this macro in my code? ``` #define my_calloc(x, n) ((x) = (__typeof__ (x))calloc((n), sizeof(__typeof__ (&(x))))) ``` I'm usign gcc as compiler... In my programm there is a lot of memory allocation point, so I use this. I tried it 5 minutes ago and I get some weird sigabort and sigsev, now I'm going home... after I'll try again if I can find something. Some idea/tip? EDIT ADDED: Generally I use the macro as follows: ``` double *x; my_calloc(x, 10); int **y; my_calloc(y, 30); ```
I think it should probably be: ``` #define my_calloc(x, n) do { (x) = calloc((n), sizeof *(x)); } while (0) ``` unnecessary/dangerous cast has been removedredundant parentheses removeddo/while added for correct behaviour betweenif (...)andelsefixed size of typeremove redundant and non-portable__typeof__
lets say I am doing mk "target" to build something. Is it possible to pass an argument to it? i.e. mk "target" "x" and it will do things accordingly? I know that I will be providing mk "target" an argument and I know its semantics, just dont know the name well in advance. Possible?
You might want to make use ofGNU Make's "Variables": ``` $ cat Makefile ifndef LOLCAKES LOLCAKES=1 endif all: @echo $(LOLCAKES) $ make all LOLCAKES=42 ``` You didn't explain what you're trying to accomplish, so it's hard to know what kind of "argument" you're after.
As we know java is a platform independent language due to JVM it's program can run at any OS. What about C/C++? could C/C++ exe run at any OS ? Could we have done something about this(Like write once run anywhere)? please clear my doubt about this. Thanks
No - an executable is built for a specific operating system and hardware (CPU) architecture. If you are carefull not to use any OS specific functions, or any assumptions about word size etc, then c++ source can be recompiled to run anywhere.
I'm learning C and hope someone can explain what's the logic of using#ifndef? I also find many C programs I looked, people seems following a convention using the filename following the#ifndef,#defineand#endif. Is there any rule or tip on how to choose this name? ``` #ifndef BITSTREAM_H #define BITSTREAM_H #include <stdio.h> #include <stdint.h> /*Some functions*/ #endif ```
Header files will often use logic like this to avoid being included more than once. The first time a source file includes them, the name isn't defined, so it gets defined and other things are done. Subsequent times, the name is defined, so all that is skipped.
I have made some c code for a program, which does some psycho-acoustics on sound data. There is a piece of code which runs very slowly. I think it would be best to use a look up table. How would one go about implementing it? Any pointers or help would be appreciated! :)
Your values are not equidistant so it is not that easy. But its still possible: take your greatest common divisor of all your condition-values (thats here 50) and then make your table byteout = lut[difference/50 + 12]; And in the lookup table you can just use your values in the posted order, where you duplicate the entries in case your stepping is 100. Btw it just see, there is a mistake, all your negative cases are catched by your first<=0(my example assumes that you want to omit the first case).
I have to to game for my school project. I have a little problem with selecting part of game screen where there is no enemy. Please see this screens, where i tried to explain a little bit.First screen, Second screen. Ok, so I have player and i can move him around a play ground - from one border to second one. And there is also an "enemy". The thing is, that I have to select area (divided by player line) where there is no enemy. Does anyone know kow can i do that, with some reasonable speed and memory ( i don't have to declare char array[width_screen][height_screen]; ) Thanks
Useflood fillalgorithm.
Is there an alternative way of rewriting this same script in C++ w/o using thescanforprintffunctions? Thanks! ``` #include <stdlib.h> #include <stdio.h> int main( int argc, char * argv[], char* env[]) { char quer[222]; printf("Content-type: text/plain\n\n"); scanf("%s",quer); printf("%s\n",quer); return 0; } ```
``` #include <iostream> #include <string> int main() { std::cout << "Content-type: text/plain\n\n"; std::string quer; std::getline(std::cin, quer); std::cout << quer << '\n'; } ```
I'm a newbie in UNIX programming. Normally, when we use local socket to communicate, the domain is always AF_UNIX or AF_LOCAL. So in this case, struct sockaddr_un serves always for the local communication. Why there is still "short sun_family"? For a historical reason? ``` struct sockaddr_un{ short sun_family; /*AF_UNIX*/ char sun_PATH[108]; /*path name */ }; ```
You pass asockaddr *to several socket functions (e.g.connect,bind,sendto) - these will look at the family variable before casting to e.g.sockaddr_un *orsockaddr_in *
How does one create a timer in C? I want a piece of code to continuously fetch data from a gps parsers output. Are there good libraries for this or should it be self written?
Simplest method available: ``` #include <pthread.h> void *do_smth_periodically(void *data) { int interval = *(int *)data; for (;;) { do_smth(); usleep(interval); } } int main() { pthread_t thread; int interval = 5000; pthread_create(&thread, NULL, do_smth_periodically, &interval) ... } ```
I have a C source code spread over many source files (*.c). For porting reasons say I need to comment out below statements from all source files ``` fprintf(stderr,"......",....); ``` The problem is these fprintfs could be multiline statements, meaning broken into two/or more lines spread over two lines in source files with a newline character(carriage returned entered at end of one line). How can I find such fprintfs scattered across all source files, replace them with a multiline C comment as: ``` /* */ ``` Since they are multiline, the find and replace command of source editors did not help. I am trying to read the source file using a PERL script but, parse them to do this but could not. Any pointers would be useful. thank you. -AD.
What you are looking for is named "coccinelle", it's semantic patch tool for C, via this you can easily do this. viz.http://coccinelle.lip6.fr/
Is there any simple way to create a GUI using OpenCV library or linking some other library with OpenCV. Just Like the trackbar in OpenCV, is there any way to create push buttons also?
OpenCV is a computer vision framework, not a GUI framework (even though OpenCV contains some very basic GUI functions). For a real GUI, better use something like GTK or Qt.
When I givesizeof(a), wherea=13.33, a float variable, the size is 4 bytes. But if i givesizeof(13.33)directly, the size is 8 bytes. I do not understand what is happening. Can someone help?
Those are the rules of the language. 13.33 is a numeric literal. It is treated as a double because it is a double. If you want 13.33 to be treated as a float literal, then you state 13.33f. 13.33 is a double literal. If sizeof(float) == 4, sizeof(13.33f) == 4 should also hold because 13.33f is a float literal.
suppose I have a macro, like ``` #define max(a,b) (((a) > (b)) ? (a) : (b)) ``` then I use it in the "normal code" ``` int foo() { ... c = max(a,b); ... } ``` Is there a way to see the code after precompiling? Does exist a way to see the effect of macro substituion (maybe done by compiler, I use gcc)? I'd like to get something like this: ``` int foo() { ... c = ((a>b) ? a : b); ... } ``` Is there something like this?
You want to see the preprocessed source code. Usually your C compiler has a switch to output the preprocessed output. For gcc, it'sgcc -E [C-filename]. For msvc, it'scl /EPorcl /P. SeeMSVC /P (Preprocess to a File)
I have already GtkTreeView. And I want hide some cells. There is method ``` gtk_cell_renderer_set_visible (GtkCellRenderer *cell, gboolean visible); ``` But How I can apply this method for some cells? Use iterator?
The only way is to 'mask' your model using aGtkTreeModelFilter. With this, you can supply an extra 'visible' column that tells whether the row should be visible or not; or you can use a function to decide which rows should be visible.
Besides not closing a comment/*..., what constitutes a lexical error in C?
Here are some: ``` "abc<EOF> ``` where EOF is the end of the file. In fact, EOF in the middle of many lexemes should produce errors: ``` 0x<EOF> ``` I assume that using bad escapes in strings is illegal: ``` "ab\qcd" ``` Probably trouble with floating point exponents ``` 1e+% ``` Arguably, you shouldn't have stuff at the end of a preprocessor directive: ``` #if x % ```
For example,printfis dynamically linked. But how does the compiler(gcc) know that?
gcc doesn't know that. It knows there is a functionprintfand it knows how to call it, but the object file it generates contains a call to an unresolved symbol. The symbol is then resolved by the linker, which is given all your object files and libraries. The linker finds the symbolprintfin a library, and after its combined all the relevant modules, it updates the unresolved calls.
I created a very small code to add two integers and save the result in another variables, both in assembly language and c language. code in assembly cost me 617 bytes but code in C took 25k bytes!! why there is a huge difference? Also how can I view the assembly symbolic instructions for C code I wrote?
High level languages have a certain amount of overhead. While in assembly all you have is exactly what you say. The overhead you are seeing in this case is likely the static binding of standard components, such asprintf. Likely an include statement added these. If you want to see what your output is like you will need a dissembler.Hereis the documentation for theNASMdissembler if you wanted to take a look at one. You can avoid some of this overhead by not including anything and instead implement the functionality in a fashion similar to how you did in assembly.
I need to create a read-only lock on a certain file in Windows, in C. The lockf function is completely useless, as it creates an exclusive lock. I need to protect the file from writes, but multiple processes should be able to read it at the same time. I cannot use CygWin or MINGW libraries, I am limited to the Microsoft APIs, which don't seem to have a decent fcntl. Or am I missing something?
if you mean for a termporary period, then use CreateFile() with dwShareMode=FILE_SHARE_READ, else use SetFileAttributes()
I have seen people use addition where a bitwise OR would be more conceptually appropriate, because they believe it is faster. Is this true? If yes, do all modern compilers know this trick?
Both addition and logical OR are probably performed in a similar part of the ALU of the CPU. There is unlikely to be any measurable performance difference, but this would have be measured in your situation to be certain. Compilers won't need to bother with this because usually the only way the compiler can know that addition and ORing will give the same result is if the operands areconstants, and in that case the compiler can simply do the arithmetic at compile time and not even have to generate code for it.
If I create pipe in windows this way: ``` CreatePipe(hRead, hWrite, &sec_atr, NULL) ``` Then makeFILE *fromhReadthis way: ``` int fd = _open_osfhandle((intptr_t)hRead, _O_RDONLY|_O_TEXT); FILE *pipe_read = _fdopen(fd, "rt"); ``` Then how should I close this file (pipe_read)? fclose(pipe_read)_pclose(pipe_read)CloseHandle((HANDLE)_get_osfhandle(fileno(pipe_read)))
From the examplehere, usefclose. The documentation forfclosefurther clarifies with: When these functions are used to close a stream, the underlying file descriptor and OS file handle (or socket) are closed, as well as the stream. Thus, if the file was originally opened as a file handle or file descriptor and is closed with fclose, do not also call _close to close the file descriptor; do not call the Win32 function CloseHandle to close the file handle; and do not call closesocket to also close the socket.
``` void (*a)(char*, char*); ``` is this a function called a. returns void pointer? in c?
This is a functionpointernameda. The function signature ofais a function that returns void and takes twochar *arguments. SeeFunction Pointer Tutorialsfor more information on function pointers.
Does it make sense in terms of better performance to build a LRU type cache in C/C++ and get java to access it via JNI ?
Doubtful JVMs do quite a decent job these days, especially considering that any applications that need a cache would probably stay up long enough for the JVM to optimise it quite a bit. Whatever your cache code would gain in speed by avoiding the JVM, you would probably lose pushing objects back and forth through JNI. Not to mention the inherent development, maintenance and deployment difficulties of C++ code when compared with Java. Or the dangers of reinventing the wheel by rolling out your own cache - there has to be something out there that you could use instead of rolling out your own.
I have a function that returns a const char * to a fixed value and when i am using this function i do a "==" operator to find eguality between the value returned and the one i expect. Is this a good practice? Should it be an anti-pattern? Ex: ``` const char * LOL = "LOL"; const char * getI() { return LOL; } main { if (getI() == LOL) something(); } ```
Is this a good practice? Well, that depends. It's the right thing to do if and only if you want to test whether the pointer returned bygetl()points to the same string literal as the globalLOLpointer. If that's not what you want to do, then, no, it's not good practice.
I define several functions in a file (the main function is defined by someone else). I can use gprof to analyze how many times my functions have been called, but is there a way of getting a list with the functions by the order they are called in the main program? of course I could write a message in the beginning of each function but there are quite a few of them. I would also be happy if it could be done by gdb by specifying something like "break in the first function that is called in this file". Again they are too many to list explicitly. Thanks.
And you don't want to use trace or truss or similar?
Is this even possible? Would be extra cool if somehow I manage to have a function called every time a buffer has been processed. Any other ideas besides polling the source it's welcomed :D
You know how many samples are in each buffer and you know the sample rate that the source is playing at. That should give you a pretty good idea of when the source will finish processing a buffer. If you're feeling very intrepid, you could hack this into the OpenAL-soft source. By the looks of the code, you would put the change intomixer.cat the very end of the file, somewhere near the end of theMixSource()function. Remembering, of course, that OpenAL-soft is lGPL; so you'd need to release/make available any changes that you made to the library itself. If you're stuck using pre-included libraries, then you don't have many options. OpenAL rejects the idea of callback functions.
I have a source file that I can run via the terminal using ``` gcc source.c -I/usr/include/libxml2 -lxml2 -o output ``` but when I#includethe source file which includes the libxml source files, the compiler complains that thelibxml/xmlmemory.h:,libxml/parser.h:,libxml/xpath.hcannot be found : no such file or directory.
You need always to keep the-I/usr/include/libxml2in your gcc statement, so that it can find the header files.
I have made some c code for a program, which does some psycho-acoustics on sound data. There is a piece of code which runs very slowly. I think it would be best to use a look up table. How would one go about implementing it? Any pointers or help would be appreciated! :)
Your values are not equidistant so it is not that easy. But its still possible: take your greatest common divisor of all your condition-values (thats here 50) and then make your table byteout = lut[difference/50 + 12]; And in the lookup table you can just use your values in the posted order, where you duplicate the entries in case your stepping is 100. Btw it just see, there is a mistake, all your negative cases are catched by your first<=0(my example assumes that you want to omit the first case).
I have to to game for my school project. I have a little problem with selecting part of game screen where there is no enemy. Please see this screens, where i tried to explain a little bit.First screen, Second screen. Ok, so I have player and i can move him around a play ground - from one border to second one. And there is also an "enemy". The thing is, that I have to select area (divided by player line) where there is no enemy. Does anyone know kow can i do that, with some reasonable speed and memory ( i don't have to declare char array[width_screen][height_screen]; ) Thanks
Useflood fillalgorithm.
Is there an alternative way of rewriting this same script in C++ w/o using thescanforprintffunctions? Thanks! ``` #include <stdlib.h> #include <stdio.h> int main( int argc, char * argv[], char* env[]) { char quer[222]; printf("Content-type: text/plain\n\n"); scanf("%s",quer); printf("%s\n",quer); return 0; } ```
``` #include <iostream> #include <string> int main() { std::cout << "Content-type: text/plain\n\n"; std::string quer; std::getline(std::cin, quer); std::cout << quer << '\n'; } ```
I'm a newbie in UNIX programming. Normally, when we use local socket to communicate, the domain is always AF_UNIX or AF_LOCAL. So in this case, struct sockaddr_un serves always for the local communication. Why there is still "short sun_family"? For a historical reason? ``` struct sockaddr_un{ short sun_family; /*AF_UNIX*/ char sun_PATH[108]; /*path name */ }; ```
You pass asockaddr *to several socket functions (e.g.connect,bind,sendto) - these will look at the family variable before casting to e.g.sockaddr_un *orsockaddr_in *
How does one create a timer in C? I want a piece of code to continuously fetch data from a gps parsers output. Are there good libraries for this or should it be self written?
Simplest method available: ``` #include <pthread.h> void *do_smth_periodically(void *data) { int interval = *(int *)data; for (;;) { do_smth(); usleep(interval); } } int main() { pthread_t thread; int interval = 5000; pthread_create(&thread, NULL, do_smth_periodically, &interval) ... } ```
I have a C source code spread over many source files (*.c). For porting reasons say I need to comment out below statements from all source files ``` fprintf(stderr,"......",....); ``` The problem is these fprintfs could be multiline statements, meaning broken into two/or more lines spread over two lines in source files with a newline character(carriage returned entered at end of one line). How can I find such fprintfs scattered across all source files, replace them with a multiline C comment as: ``` /* */ ``` Since they are multiline, the find and replace command of source editors did not help. I am trying to read the source file using a PERL script but, parse them to do this but could not. Any pointers would be useful. thank you. -AD.
What you are looking for is named "coccinelle", it's semantic patch tool for C, via this you can easily do this. viz.http://coccinelle.lip6.fr/
Is it possible to print (tostdout, or a file) an number (int,float,double,long, etc.) without actually using any of the*printffunctions (printf,fprintf,sprintf,snprintf,vsprintf, …)?
If your libc contains anitoa()function, you can use it to convert an integer to a string.Otherwise you'll have to write the code to convert a number to a string yourself. itoa()implementation fromC Programming Language, 2nd Edition - Kernighan and Ritchiepage 64: ``` /* itoa: convert n to characters in s */ void itoa(int n, char s[]) { int i, sign; if ((sign = n) < 0) /* record sign */ n = -n; /* make n positive */ i = 0; do { /* generate digits in reverse order */ s[i++] = n % 10 + '0'; /* get next digit */ } while ((n /= 10) > 0); /* delete it */ if (sign < 0) s[i++] = '-'; s[i] = '\0'; reverse(s); } ```
This question already has answers here:Closed12 years ago. Possible Duplicate:What should main() return in C/C++? Example1 ``` #include <stdio.h> int main(void) { printf ("Hello World!\n"); getch(); } ``` Example2 ``` #include <stdio.h> void main() { printf ("Hello World!\n"); getch(); } ``` Both output: ``` Hello World ```
The first example is recommended but also you need to put this line as the last one in the main() ``` return 0; ``` which returns zero to the system indicating that everything went alright.
Does anyone know why the following code ``` void foo(const int X) { #pragma omp parallel for private(X) for (int i = 0; i < 100; i++) { } } ``` gives this error error: 'X' is predetermined 'shared' for 'private' and how I can really makeXprivate to each thread?
You are getting an error becauseXis constant. Just removeconstand everything should work.
I'm looking for a very portable, minimalistic/small XML/configuration language library in ANSI C with no external dependencies (or very few), compiling down to less than 100K. I need it for a moderately complex configuration file, and it must support Unicode. Some more requirements: OK to use/embed/staticallylink into proprietary code. Credit will always will be given where credit is due.Not necessarily XML.Really,clean code/no weird or inconsistent string handling.UTF-8. Thank you fellas.
This is somehow similar to this question:Is there a good tiny XML parser for an embedded C project? I was able to tweak the compilation flags of the following XML parser libraries for C, and cut down more than 50% of their size on my Ubuntu machine. Mini-XML is the only one close to what you requested: Mini-XML(36K)Expat(124K)RXP(184K)
I'm trying to call the Vista functionSHGetKnownFolderPath()from C using Visual Studio 2008. The code works fine as C++ but refuses to compile as C code with this output: xyz\indexwiki.cpp(316) : error C2440: 'function' : cannot convert from 'const GUID' to 'const KNOWNFOLDERID *const ' xyz\indexwiki.cpp(316) : warning C4024: 'SHGetKnownFolderPath' : different types for formal and actual parameter 1 The code is pretty much: ``` PWSTR path; HRESULT hr = SHGetKnownFolderPath( FOLDERID_Profile, 0, NULL, &path ); ``` I'd prefer to keep it as C and keep the project as a single source file if I can. Is this a known problem with newer Windows APIs? I couldn't find much via Google. Am I missing something? Or is there perhaps a simple workaround involving casting or preprocessor defines?
How about the following? HRESULT hr = SHGetKnownFolderPath(&FOLDERID_Profile, 0, NULL, &path);
When I have to open a folder inWindows Explorer(for exampled:\myfolder\test), I use::GetForegroundWindow()to get itsWindow Handle, and use::GetWindowTextto get the Title Text. But in the default windows the full path of the current window is not displayed (of course you can throughtools-folder option-view-display full pathin title bar to set the title bar to display full path), and the::GetWindowTextonly getstest. If I want to get the full pathd:\myfolder\testhow can I get this by the windows handle got by::GetForegroundWindow()? Any suggestions. Thanks.
By using theShellWindowsCOM object. Seethis exampleon how the get the folder that an Explorer window is viewing.