question
stringlengths
25
894
answer
stringlengths
4
863
I have a very small program which converts a string to double. The problem is everytime it is printing 0.0000. Please help me. Thanks in advance. ``` enter code here $ export LT_LEAK_START=1.5 $ echo $LT_LEAK_START 1.5 #include <stdio.h> int main() { double d; d=strtod(getenv("LT_LEAK_START"), NULL); printf("d = %lf\n",d); } Output: d=0.0000000 ```
Try including ``` #include <stdlib.h> ```
When I run this piece of code: ``` void main(){ int a = 5; static int i = a+5; printf("%d", i); } ``` I get the error:initializer element is not constant What does this mean?
Static variables in function scope go in data segment. Data segment is initialized at compile time. That means the initial value has to be known at compile time. In your case, the initial value (value of a) comes from a variable on stack which is available only at runtime.
How do I remove a character from a string? If I have the string"abcdef"and I want to remove"b"how do I do that? Removing thefirstcharacter is easy with this code: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char word[] = "abcdef"; char word2[10]; strcpy(word2, &word[1]); printf("%s\n", word2); return 0; } ``` and ``` strncpy(word2, word, strlen(word) - 1); ``` will give me the string without thelastcharacter, but I still didn't figure out how to remove a char in themiddleof a string.
memmovecan handle overlapping areas, I would try something like that (not tested, maybe +-1 issue) ``` char word[] = "abcdef"; int idxToDel = 2; memmove(&word[idxToDel], &word[idxToDel + 1], strlen(word) - idxToDel); ``` Before:"abcdef" After:"abdef"
I am making a C program that, running with admin privileges, makes another .exe (also in C) to run at startup for one/all user(s), in the background. Other answers use .net, but how do I do it in C, developed in minGW? So C code which sets a program to run at startup for userthe installed program to run in the background (without opening a terminal) Yes, I feel it's sufficiently distinct enough to be asked on it's own :-)
You can have your program register itself in the windows registry to list of program run at startup.You need to link to the windows subsystem instead of the console subsystem. This can be done by passing the-Wl,-subsystem,windowstogccwhen linking your program.
This question already has answers here:Closed12 years ago. Possible Duplicate:How many 1s in an n-bit integer? Hello How to calculate how many ones in bits? ``` 1100110 -> 4 101 -> 2 ``` And second question: How to invert bits? ``` 1100110 -> 0011001 101 -> 010 ``` Thanks
If you can get your bits into astd::bitset, you can use theflipmethod to invert, and thecountmethod to count the bits.
Is there any way to make pointers read a file as a block of memory in C? Can access of a file can be faster...?
Treating a file as memory (and letting the OS do the file IO for you) is termed 'memory mapping'. On POSIX (e.g.Linux), themmap()function does this. OnWindows, theOpenFileMapping()function and friends do this. Microsoft have excellent description of how this works, why to use it, and particulars on their platformhere.
I would like to know if it is possible to create a .EXE from a .C file without using any compiler on Windows ?
You can cross-compile from another platform, e.g. usingMinGW on another OS such as Linux or Mac OS X, but ultimately you need a compilersomewhere. If you don't actually need a .EXEper se, but just want to compile and run some C code without having to install a compiler, e.g. for educational/experimental purposes, then there are very useful sites such ascodepad.organdideone.comwhich provide this capability for C and a number of other languages.
How can I assign "pwd" (or any other command in that case) result (present working dir) to a variable which is char*? command can be anything. Not bounded to just "pwd". Thanks.
Start withpopen. That will let you run a command with its standard output directed to aFILE *that your parent can read. From there it's just a matter of reading its output like you would any normal file (e.g., withfgets,getchar, etc.) Generally, however, you'd prefer to avoid running an external program for that -- you should havegetcwdavailable, which will give the same result much more directly.
I heard somewhere about 16 bit long char type on some of 64 bit systems. What is the size of char type on Intel 64 (EM64T) system?
There are two 64-bit ABIs in common use on EM64T / AMD64 systems: Thestandard ABI used by Linux(and, as far as I'm aware, other Unix variants), which definescharas 8 bits (see section 3.1.2).TheWindows x64 ABI, which also definescharas 8 bits (seeTypes and Storage -> Scalar Types). But theC standarddoesallow a "byte" to be larger than 8 bits, and acharis a "byte" (in terms of the C standard) by definition; and such platforms do exist,e.g. some DSPs.
``` int system(const char *) ``` How can I send output of this command (lets say the command is "pwd") to a char*? Its returning an int but I want the results of the command to be sent to a char*.
You can pipe the output of the command directly to a file by using "pwd > tempfile" as command.Another way is to usepopen ``` FILE *output = popen("pwd", "r"); ``` That will give you a file pointer where you can read the output from.
I am trying to retrieve POST data from html form using program written in C. At the moment I am using: ``` char *formdata = getenv("QUERY_STRING"); if(formdata == NULL) /* no data retrieved */ ``` This seems to be working fine with form "GET" method but not with "POST" method. How do I retrieve POST data?
POST data is appended to the request header, after a double newline. In a CGI-BIN environment, you read it from STDIN. Be warned that the serverIS NOT REQUIRED to send you an EOF character(or some termination indicator) at the end of the POST data. Never read more than CONTENT_LENGTH bytes.
1) What is the newest version of C language? 2) How is GCC complying to it? 3) For an old C programmer, what is the main differences of the new language? I'm asking this because I learned these days (a new feature) that we can actually attribute values to a struct like: ``` struct t { int i; char c; } s; s = (struct t){exponent, coefficient}; ``` So I'm wondering about other things I might be missing when programming... Thanks, Beco
The most recent version of C language seems to be C99. Among the numerous changes, the most important IMHO are: restrictpointersvariable length arraysbuilt-in complex numbersvariable declarations mixed with codeC++-style//comments Hereis a bigger list.
I was going through an open source codebase and I see the following:- ``` char *buf; char *line; #define BUFSIZE 5000 buf = malloc(BUFSIZE) line = buf; while(fgets(line, (unsigned)(buf + BUFSIZE -line), in) != NULL) { // do stuff // .... } ``` Why is the second argument to fgets given asbuf + BUFSIZE - line?
That gives the number of characters fromlineto end ofbuf. Your//do stufflikely incrementsline buf + BUFSIZEis achar *pointing to the first charafterthe memory allocated forbuf buf + BUFSIZE - lineis an integral, the number of chars fromlinetobuf + BUFSIZE- and therefore the number of characters you can safely write tolinewithout overflowingbuf
I have a c program that watches over a folder somewhere in your directory (location is given when program starts up). One of its tasks is to tell the user what contents are stored in that specified folder. I was thinking of piping the ls command but I'm unsure how to get contents of a folder in which you are not currently in. Help? Thanks!
Just use ls? ``` ls /path/to/directory ``` Alternatively, useopendir()andreaddir(), seeman 3 opendirandman 3 readdir
``` struct Dummy { int x; char y; }; int main() { struct Dummy dum; dum.x = 10; dum.y = 'a'; } ``` How would be the layout of the structure members on a little endian machine? Would it be something like this? ``` 0x1000 +0 +1 +2 +3 ___________________ x: | 10 | 0 | 0 | 0 | ------------------- y: | 'a'| 0 | 0 | 0 | ------------------- 0x1000 +4 +5 +6 +7 ```
I think you'll findthis questionuseful. The endianess is usually relevant for a word in the memory, not to the whole structure.
Anyone know what could be problem: ``` cvSmooth(origImage, grayImage1, CV_BLUR,3); ``` I received error: ``` error: cannot convert `cv::Mat' to `const CvArr*' for argument `1' to `void cvSmooth(const CvArr*, CvArr*, int, int, int, double, double)' ``` If I use: ``` cvtColor(origImage, grayImage, CV_BGR2GRAY); ``` All worked fine. capturing is from laptop camera(realtime).
cv::Matis a new structure from the C++ version of OpenCV.cvSmooth()is from the old C API. Do not mix the C interface with the C++! I'll suggest that you take a moment to read theintroduction. Also, if you checkopencv/modules/imgproc/src/smooth.cppyou'll see thatcv::boxFilter()is the equivalent forcvSmooth(CV_BLUR)on the new C++ interface.
``` int i; va_list objects_list; va_start(objects_list, objects); for (id o = objects, i = 0; o != nil; o = va_arg(objects_list, id), i++); objectsInArray = malloc(sizeof(id) * i); va_end(objects_list); // ... (malloc NULL checking is here, does not involve i) va_start(objects_list, objects); for (id o = objects, i = 0; o != nil; o = va_arg(objects_list, id), i++) { objectsInArray[i] = o; } va_end(objects_list); ``` I am getting anArray subscript is not an integererror on theobjectsInArray[i] = o;line.objectsInArrayis declared asid *objectsInArray. iis anint, so why am I getting this error and how can I fix this? Thanks in advance.
iis of typeidwithin the for loop. To resolve the ambiguous syntax, declareid ooutside of thefor(...)statement. In Xcode, under project settings, enable the warnings for "Hidden local variables", so the compiler will warn for such things. Otherwise, when usinggcc, use-Wshadow.
I need to process xml and xsd docs into a 'C' program I am writing on freebsd. Does anyone know if any libraries available (must be some like XML DOM) so that I do not need to read it like text and do all stupid things? For example: I want to do operations like, adding a particular node at a designated place in the xml node tree and all.
You probably should look atlibxml2. It has a DOM interface and most other things you might want to do at a node manipulation level. I'm not sure from your question if you need XSD validation or not. There is an incompletexsd validation pluginbut I've not used it so I can't comment further on that.
Why would sizeof in the following cases print different values: ``` printf("%d",sizeof("ab")); //print 3 char* t="ab"; printf("%d",sizeof(t)); //print 4 ``` In the first case I have 2 characters... Shouldn'tsizeofprint 2? Because they are 2 bytes?
Strings in C are null terminated. "ab" in memory looks like'a' 'b' '\0' Whiletis a pointer, so size is 4.
I can read values of elapsed seconds since some reference time which appears in the format1301330553(Decimal)/4D90BA79(hex). I would like to convert these seconds in somedate/timeformat inC. The elapsed seconds mentioned above are ofu32 data type.
there's a function called ctime which takes a unix long as a parameter that renders the time in ascii.
Can some one please tell me how to check if a unix process with a given process id is running inside a C program. I know I can call system() and use the ps command but I dont want to call the system().
Usingkill(2): ``` if (kill(pid, 0) == 0) { /* process is running or a zombie */ } else if (errno == ESRCH) { /* no such process with the given pid is running */ } else { /* some other error... use perror("...") or strerror(errno) to report */ } ```
I have a C function which accepts a character. I need to extract as well insert bits into that character. I am clear with the extraction part. Can anyone give me an idea of how to insert values to bits?
Pretty vague question, I would suggest you brush up on bitwise operators. This should point you in the right direction. http://www.cprogramming.com/tutorial/bitwise_operators.html
Considering the following scenario: fn(1) calls fn(2) , then fn(2) calls fn(3), and now fn(3) should pass the control to fn(1) instead of fn(2) and control must not come back again. Regarding this I have tried with goto, but goto does not work between functions, its only a local jump. I wanted to check if there is any other method I could use to send the control to another function NOTE: NO global variable, pointer to functions will work in this case, as per my exploration
Well, the typical way of doing this would be: ``` int fn3() { return 1; } void fn2() { if (fn3()) return; ... } ``` Not sure if you're looking for something more esoteric, such as setjmp/longjmp
For the following code snippet I get the output as1. I want to know how it came? ``` void main() { int x=10,y=20,z=5,i; i=x<y<z; printf("%d",i); } ```
i=x<y<z;, gets interpreted asi=(x<y)<z, which in turn gets interpreted asi=1<z, which evaluates to 1.
I have atest.cthat is using code from two libraries. One is statically linked (saylibstatic.a, the other - dynamically (e.g.libdynamic.so). I compiled my c file as follows: ``` gcc -I../inc -c test_subframeip_omap.c -o test_subframeip_omap.o ``` How do I link now the static and dynamic libraries in order to produce the final executable? Thanks!
You generally need something like: ``` gcc -I../inc -c test_subframeip_omap.c -o test_subframeip_omap.o gcc -L/path/to/libs -l static -ldynamic -o test_subframeip_omap test_subframeip_omap.o ``` The-Ladds directories to the library search path and-lspecifies a library to link with. It's also done as part of thelink,not thecompile.
I have a double which is not necessarily positive but usually. It can be 0.xxxx000 or X.xxxx00000 or XX.00000 or 0.xxx0xxx00000, where eventually there are all 0's to the right of the last number. I need to keep track of how many digits there are. I've been having trouble with this, any help? This is C.
A double has 52 mantissa bits plus an implicit "1" bit, so you should be able to type-pun a double pointer to a 64-bit integer (getting the raw bits into an integer), &= this with (1<<52)-1, and |= the result with (1<<52). The log10 of that would be the number of decimal digits. Though, I'm almost inclined to say "go with jonsca's solution" because it is so ingeniously simple (it deserves a +1 in any case for being KISS).
I define aNULL_PTRas0U Then call a function with thisNULL_PTRas argument. ``` read_some_data(2U, (uint8_t *const) NULL_PTR, (uint8_t *const) NULL_PTR); ``` Called function prototype: ``` int16_t read_some_data(const uint8_t id, uint8_t *const data_1, uint8_t *const data_2); ``` On compilation, Misra raised a rule 11.3 violation error.(A cast should not be performed between a pointer type and an integral type.) But if I just pass theNULL_PTRas follows, no violation. ``` read_some_data(2U, NULL_PTR, NULL_PTR); ``` Which is the better way to do? Suppress Misra 11.3 rule or just pass theNULL_PTRwithout casting?
What is wrong with the Standard 'NULL'?
I have a very small program which converts a string to double. The problem is everytime it is printing 0.0000. Please help me. Thanks in advance. ``` enter code here $ export LT_LEAK_START=1.5 $ echo $LT_LEAK_START 1.5 #include <stdio.h> int main() { double d; d=strtod(getenv("LT_LEAK_START"), NULL); printf("d = %lf\n",d); } Output: d=0.0000000 ```
Try including ``` #include <stdlib.h> ```
When I run this piece of code: ``` void main(){ int a = 5; static int i = a+5; printf("%d", i); } ``` I get the error:initializer element is not constant What does this mean?
Static variables in function scope go in data segment. Data segment is initialized at compile time. That means the initial value has to be known at compile time. In your case, the initial value (value of a) comes from a variable on stack which is available only at runtime.
How do I remove a character from a string? If I have the string"abcdef"and I want to remove"b"how do I do that? Removing thefirstcharacter is easy with this code: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char word[] = "abcdef"; char word2[10]; strcpy(word2, &word[1]); printf("%s\n", word2); return 0; } ``` and ``` strncpy(word2, word, strlen(word) - 1); ``` will give me the string without thelastcharacter, but I still didn't figure out how to remove a char in themiddleof a string.
memmovecan handle overlapping areas, I would try something like that (not tested, maybe +-1 issue) ``` char word[] = "abcdef"; int idxToDel = 2; memmove(&word[idxToDel], &word[idxToDel + 1], strlen(word) - idxToDel); ``` Before:"abcdef" After:"abdef"
I am making a C program that, running with admin privileges, makes another .exe (also in C) to run at startup for one/all user(s), in the background. Other answers use .net, but how do I do it in C, developed in minGW? So C code which sets a program to run at startup for userthe installed program to run in the background (without opening a terminal) Yes, I feel it's sufficiently distinct enough to be asked on it's own :-)
You can have your program register itself in the windows registry to list of program run at startup.You need to link to the windows subsystem instead of the console subsystem. This can be done by passing the-Wl,-subsystem,windowstogccwhen linking your program.
This question already has answers here:Closed12 years ago. Possible Duplicate:How many 1s in an n-bit integer? Hello How to calculate how many ones in bits? ``` 1100110 -> 4 101 -> 2 ``` And second question: How to invert bits? ``` 1100110 -> 0011001 101 -> 010 ``` Thanks
If you can get your bits into astd::bitset, you can use theflipmethod to invert, and thecountmethod to count the bits.
Is there any way to make pointers read a file as a block of memory in C? Can access of a file can be faster...?
Treating a file as memory (and letting the OS do the file IO for you) is termed 'memory mapping'. On POSIX (e.g.Linux), themmap()function does this. OnWindows, theOpenFileMapping()function and friends do this. Microsoft have excellent description of how this works, why to use it, and particulars on their platformhere.
I would like to know if it is possible to create a .EXE from a .C file without using any compiler on Windows ?
You can cross-compile from another platform, e.g. usingMinGW on another OS such as Linux or Mac OS X, but ultimately you need a compilersomewhere. If you don't actually need a .EXEper se, but just want to compile and run some C code without having to install a compiler, e.g. for educational/experimental purposes, then there are very useful sites such ascodepad.organdideone.comwhich provide this capability for C and a number of other languages.
How can I assign "pwd" (or any other command in that case) result (present working dir) to a variable which is char*? command can be anything. Not bounded to just "pwd". Thanks.
Start withpopen. That will let you run a command with its standard output directed to aFILE *that your parent can read. From there it's just a matter of reading its output like you would any normal file (e.g., withfgets,getchar, etc.) Generally, however, you'd prefer to avoid running an external program for that -- you should havegetcwdavailable, which will give the same result much more directly.
I heard somewhere about 16 bit long char type on some of 64 bit systems. What is the size of char type on Intel 64 (EM64T) system?
There are two 64-bit ABIs in common use on EM64T / AMD64 systems: Thestandard ABI used by Linux(and, as far as I'm aware, other Unix variants), which definescharas 8 bits (see section 3.1.2).TheWindows x64 ABI, which also definescharas 8 bits (seeTypes and Storage -> Scalar Types). But theC standarddoesallow a "byte" to be larger than 8 bits, and acharis a "byte" (in terms of the C standard) by definition; and such platforms do exist,e.g. some DSPs.
``` int system(const char *) ``` How can I send output of this command (lets say the command is "pwd") to a char*? Its returning an int but I want the results of the command to be sent to a char*.
You can pipe the output of the command directly to a file by using "pwd > tempfile" as command.Another way is to usepopen ``` FILE *output = popen("pwd", "r"); ``` That will give you a file pointer where you can read the output from.
I am trying to retrieve POST data from html form using program written in C. At the moment I am using: ``` char *formdata = getenv("QUERY_STRING"); if(formdata == NULL) /* no data retrieved */ ``` This seems to be working fine with form "GET" method but not with "POST" method. How do I retrieve POST data?
POST data is appended to the request header, after a double newline. In a CGI-BIN environment, you read it from STDIN. Be warned that the serverIS NOT REQUIRED to send you an EOF character(or some termination indicator) at the end of the POST data. Never read more than CONTENT_LENGTH bytes.
1) What is the newest version of C language? 2) How is GCC complying to it? 3) For an old C programmer, what is the main differences of the new language? I'm asking this because I learned these days (a new feature) that we can actually attribute values to a struct like: ``` struct t { int i; char c; } s; s = (struct t){exponent, coefficient}; ``` So I'm wondering about other things I might be missing when programming... Thanks, Beco
The most recent version of C language seems to be C99. Among the numerous changes, the most important IMHO are: restrictpointersvariable length arraysbuilt-in complex numbersvariable declarations mixed with codeC++-style//comments Hereis a bigger list.
I was going through an open source codebase and I see the following:- ``` char *buf; char *line; #define BUFSIZE 5000 buf = malloc(BUFSIZE) line = buf; while(fgets(line, (unsigned)(buf + BUFSIZE -line), in) != NULL) { // do stuff // .... } ``` Why is the second argument to fgets given asbuf + BUFSIZE - line?
That gives the number of characters fromlineto end ofbuf. Your//do stufflikely incrementsline buf + BUFSIZEis achar *pointing to the first charafterthe memory allocated forbuf buf + BUFSIZE - lineis an integral, the number of chars fromlinetobuf + BUFSIZE- and therefore the number of characters you can safely write tolinewithout overflowingbuf
I have a c program that watches over a folder somewhere in your directory (location is given when program starts up). One of its tasks is to tell the user what contents are stored in that specified folder. I was thinking of piping the ls command but I'm unsure how to get contents of a folder in which you are not currently in. Help? Thanks!
Just use ls? ``` ls /path/to/directory ``` Alternatively, useopendir()andreaddir(), seeman 3 opendirandman 3 readdir
``` struct Dummy { int x; char y; }; int main() { struct Dummy dum; dum.x = 10; dum.y = 'a'; } ``` How would be the layout of the structure members on a little endian machine? Would it be something like this? ``` 0x1000 +0 +1 +2 +3 ___________________ x: | 10 | 0 | 0 | 0 | ------------------- y: | 'a'| 0 | 0 | 0 | ------------------- 0x1000 +4 +5 +6 +7 ```
I think you'll findthis questionuseful. The endianess is usually relevant for a word in the memory, not to the whole structure.
Anyone know what could be problem: ``` cvSmooth(origImage, grayImage1, CV_BLUR,3); ``` I received error: ``` error: cannot convert `cv::Mat' to `const CvArr*' for argument `1' to `void cvSmooth(const CvArr*, CvArr*, int, int, int, double, double)' ``` If I use: ``` cvtColor(origImage, grayImage, CV_BGR2GRAY); ``` All worked fine. capturing is from laptop camera(realtime).
cv::Matis a new structure from the C++ version of OpenCV.cvSmooth()is from the old C API. Do not mix the C interface with the C++! I'll suggest that you take a moment to read theintroduction. Also, if you checkopencv/modules/imgproc/src/smooth.cppyou'll see thatcv::boxFilter()is the equivalent forcvSmooth(CV_BLUR)on the new C++ interface.
``` int i; va_list objects_list; va_start(objects_list, objects); for (id o = objects, i = 0; o != nil; o = va_arg(objects_list, id), i++); objectsInArray = malloc(sizeof(id) * i); va_end(objects_list); // ... (malloc NULL checking is here, does not involve i) va_start(objects_list, objects); for (id o = objects, i = 0; o != nil; o = va_arg(objects_list, id), i++) { objectsInArray[i] = o; } va_end(objects_list); ``` I am getting anArray subscript is not an integererror on theobjectsInArray[i] = o;line.objectsInArrayis declared asid *objectsInArray. iis anint, so why am I getting this error and how can I fix this? Thanks in advance.
iis of typeidwithin the for loop. To resolve the ambiguous syntax, declareid ooutside of thefor(...)statement. In Xcode, under project settings, enable the warnings for "Hidden local variables", so the compiler will warn for such things. Otherwise, when usinggcc, use-Wshadow.
Is there a native implementation of JSON in Windows that I can call from C? If not, what about .NET or C#? Or what if any library or implementation do people use when they wish to use JSON in a Windows app?
Yes, there is a built-in Windows JSON parser:http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx It can be called from a native language using the .NET interop facilities (COM Callable Wrapper), which may be more work for you than a truly native library, as first answer suggests.
I keep hearing "perimeter locking" along with other topics such as "race conditions, IPC .." - what does "perimeter locking" mean? any pointers or links will be helpful too. I see it being referred to under "Job Requirements" such as " understanding concepts of DMA engines, interrupts, timers, memory virtualization, race conditions, and perimeter locking..." I recognize others but not "perimeter locking".Thanks
Probably things like "do not leave a JTAG/ISP connector accessible". For a regular PC it would clearly also include the firewire port which can be (ab)used to do interesting things like accessing the PC's memory without running special software on it.
This is not specific to any programming language, the problem is "find the index of a specified value in an array of n numbers. Now my question is, in the code below can you declare an array how I have done it. ``` {int n; read(n); int array[n]; ``` ...... or is this allowed? ``` {int n; array[n]; read(n) ``` I'm thinking the first one is correct. Thanks in advance.
Converted from a comment as suggested byMerlyn Morgan-Graham The way an array is declared depends on what language you use. If you are writing pseudo-code you can decide it yourself as long as it communicates the intent and the desired result. The array can be declared asarray = [],int[] array = new int[],int array[],array = array(), ´array = {}` etc. In some languages you have to declare the size of the array beforehand and in some languages the arrays expand when needed
I have two string constantsconst char *like this: ``` const char * p1 = "abcd"; const char * p2 = "efgh"; ``` I want to convert these into a single string so that it becomes a file name: ``` const char * filename = "abcd_efgh.txt"; ``` I tried to concatenate thechar *but failed. Kindly guide me as to how to do this. Thanks
char*arepointers, i.e they hold the address of the memory segment where the data is stored. You need to allocate a new, large enough buffer and then use thestrcat()function to concatenate the strings. This is really the C way to do this, not the C++ way. In C++ you should use a string class, such asstd::stringwhich handles all the buffer allocation stuff for you.
For example: ``` struct myCar{ int price; int *uniqueID; }; ``` In C, an int has 4 bytes. I'm assuming a pointer also occupies 4 bytes as well? Therefore, 8 bytes total?
Find out: ``` printf("Size of my struct is: %zu\n", sizeof(struct myCar)); ``` The size of a pointer is platform dependent. For that matter, the size of anintis platform dependent. Could be 8 bytes for either if you're on a 64bit machine.
If I pass a lib name with-loption, then GCC will link to the best lib from /usr/lib. I think the dynamic version is chosen over the static version when both are present. But there are also debug versions of the same lib. Debug versions are supposed to be compiled with optimisations off and extra runtime checks on. I checked it with the package manager (Synaptic on Ubuntu) that dbg versions are indeed installed on my computer, but not entirely sure where are those libs and how to link to them. Any hints are greatly appreciated. Thanks.
If you are aware of the name of the debug library, you can directly use it in compilation instead of going with -l option. For example : ``` gcc -o <output_file> *.c <libdebug_file>.so ```
I have the following header file, but keep on getting: syntax error : missing ')' before '*' on the prototype declaration lines. what's the problem? ``` typedef struct queue{ int count; int first; int last; int *q; }; void init_queue(queue *q); void enqueue(queue *q, int x); int dequeue(queue *q); int empty(queue *q); ```
You never finished your typedef. You probably meant to do: ``` typedef struct queue{ int count; int first; int last; int *q; } queue; ``` You need to define an alias for your type at the end of the typedef. If you didn't have a typedef, you'd have to write your prototypes like so: ``` void init_queue(struct queue *q); // etc. ```
I have simple method for prinitng matrix. ``` void printMatrix(int matrix){ int i; for(i=0;i<sizeof matrix/sizeof matrix[0];i++){ for(j=0; j<sizeof matrix[0]/sizeof matrix[0][0];i++){ printf("%03d",matrix[i][j]); } printf("\n"); } printf("\n"); } ``` And in main I have call: ``` printMatrix(matrix); ``` and matrix is defined as: ``` int matrix[2][3] = {{1, 3, 4}, {2, 0, 1}}; ``` Problem is I am getting "Undefined reference to 'printMatrix'" Do you know where could be the problem? Does it require some special include? I don't thinks so, but I don't know, where is the fault.
Are you calling the function before it has been defined? If so, try putting the function definition before main.
I know it's related to the order in which shared objects are specified in the linker command line, i.e. if you do this: gcc -o main main.c -lA -lB The CTORs in libB will run before the ones in libA. Is this behavior standardized? Can I make use of it in a framework that is meant to be portable between hardware platforms? P.S. A CTOR is a function with the__attribute__((constructor))stuff.
An application that depends on this is extremely fragile... Also a number of people consideranyuse of global constructors, especially in C, a major offense and grounds for not using a library.pthread_onceprovides a much cleaner way to get the same safe initialization without programmers using your library having to worry that you may have messed up the program's initial state beforemainis entered.
How can one extract gzip data using C? Example code ``` <layer name="Background" width="50" height="50"> <data encoding="base64" compression="gzip"> H4sIAAAAAAAAA+3YIQ6AMAwF0AEKEATwSO5/RCoRmGHY2BMvaVLzRb/pkVI6gOZ0oQ9DAVlynbd5DFOYH3Y1WcMW9gKytGbJ8HXWFtXaaQAAAAAA/s8Pm1xuBvLpDW9ciGmfRhAnAAA= </data> </layer> ``` I need to extract that gzip data and continue parsing the xml (tmx) file.
You can use thezliblibrary that can decompress gzipped data. Before that, you'll have to decode thebase64encoding. You can uselibbase64for that.
What is stored in the data tag of of a tmx file such as the following ``` <data encoding="base64" compression="gzip"> H4sIAAAAAAAAA+3YIQ6AMAwF0AEKEATwSO5/RCoRmGHY2BMvaVLzRb/pkVI6gOZ0oQ9DAVlynbd5DFOYH3Y1WcMW9gKytGbJ8HXWFtXaaQAAAAAA/s8Pm1xuBvLpDW9ciGmfRhAnAAA= </data> ``` Also if this is key info, how is it read or extracted using c ?
This looks like binary octet data that has been compressed usinggzipand then encoded inBase64to make it XML-safe. Implementations for both should be easy to obtain, though I don't know enough C libraries to recommend one.
``` #include <stdio.h> #include <stdlib.h> int main(){ char *str="abcdce"; char c='c'; char *pfast=str,*pslow=str; while(*pfast!='\0'){ if(*pfast==c){ pfast++; *pslow=*pfast; //error here when pfast reaches the first 'c' } pfast++; pslow++; } *pslow='\0'; return 0; } ``` segment fault when it runs to the assignment statement of "*pslow=*pfast;"... Somebody tell me why, thanks in advance!
You are trying to change a string literal which leads to undefined behavior. Change ``` char *str="abcdce"; ``` to ``` char str[] ="abcdce"; ```
I'm afraid to admit, I haven't used C++ for a while now but i'm afraid I have to now, and I'm a bit rusty.I need to have a bitmap, and I do care about performance, my bitmap size will be no longer then 25 bits.I was thinking about using unsigned int, but I am afraid I do not remember how it is implemented in c/c++Is unsigned int implemented as a regular binary number?I am also open to any other suggestions for a bitmap.thanks in advance for the help!
Use anstd::bitset<25>from the header<bitset>.bitsetcan be indexed with[]and is a template, so it likely expands to just anunsigned int(or equivalent) with all operations inlined.
Can a single char be made read-only in C ? (I would like to make '\0' read-only to avoid buffer overflows.) ``` char var[5 + 1] = "Hello"; var[5] = '\0'; // specify this char as read-only ? ```
You can't make a mixedconst/non-constarray or string. The\0not being overwritten should be guaranteed by the invariants in your program.
I'm trying to find out the best way to generate the following bitmask : - For a given input n, the output would be a bitmask which has the first (n-1) bits set, and all other bits unset. Example: ``` if n = 1, output = 0x00000001 = 00000000000000000000000000000001 if n = 2, output = 0x00000003 = 00000000000000000000000000000011 if n = 3, output = 0x00000007 = 00000000000000000000000000000111 ``` I know of the obvious iterative way(setting the bits one at a time), that would take O(n) time....I'm just wondering if there's any "bit-magic" that can do this in constant time, or at least sub-linear time (without using LUT !!) Any takers ?
This should do it:(1 << n) - 1
How would I make a version of sleep in C spin so it uses cpu cycles?
I suppose something like (pseudocode) ``` while (time < endtime) ; ``` The implementation of "time < endtime" is OS-dependent, but you just want to compute the end time based on an argument before your loop starts, and then continuously fetch the system time and compare it to that end time.
I'm not sure whats wrong with this it says incompatible implicit built in func Well I did include string.h file but it still giving me a error ``` int name_read; int name_bytes = 100; char *name; printf("Please enter name:\n"); name = (char *)malloc(name_bytes + 1); name_read = getline(&name, &name_bytes, stdin); ```
You need to#include <stdlib.h>to get the correct declaration ofmalloc. Alsosizeof(name_bytes) + 1looks fishy; that will give you 5 bytes of memory, not 101 as you probably expected. Finally, there is no need to cast the return value ofmallocin C since it returns avoid*. ``` #include <stdlib.h> /* ... */ int name_bytes = 100; char* name = malloc(name_bytes + 1); ```
``` struct timeval start, end; . . . elapsedTime = (((end.tv_sec * 1000000) - (start.tv_sec * 1000000)) + (end.tv_usec - start.tv_usec)); ``` I just want to double check this returns time in micro sec..
The code is correct, but watch out for overflow. It's slightly safer to do ``` (end.tv_sec - start.tv_sec) * 1000000 ``` then add in theusecdifference.
I am trying to zero-out an entirecharpointer. If I perform the statement: memset(myCharPointer, 0, sizeof(myCharPointer)); it only zeros-out the first 4 bytes because that is the size of acharpointer on my system. So how can I ensure that the data is completely set to 0? Setting it toNULLdoes not wipe out the entirecharpointer.
sizeof(myCharPointer)is going to give you asizeof(char*), which is the size of apointer, which is usually four bytes. A sizeof(char) is going to give you 1 byte. To do the memset you need to know how long your data is. e.g., memset(myCharPointer, 0, myCharPointerLen);
Is there an option, part of read() that when calling read() on a file descriptor it only prints out the characters up to the null terminator?
Sorry, no, there isn't.read()doesn't look at the data at all; it just reads as many bytes as there are (but not more than your buffer size). I would do this with the higher-levelstdio.hfunctions, by callinggetc()(and writing to a buffer) until I saw a NUL byte, and thenungetc()on the NUL.
In my code I must choose one of this two expressions (where mask and i non constant integer numbers-1 < i < (sizeof(int) << 3) + 1). I don't think that this will make preformance of my programm better or worse, but it is very interesting for me. Do you know which is better and why?
First of all, whenever you find yourself asking "which is faster", your first reaction should be to profile, measure and find out for yourself. Second of all, this is such a tiny calculation, that it almost certainly has no bearing on the performance of your application. Third, the two are most likely identical in performance.
I'm running an Linux OS and trying to open file in C compiler like this : ``` file = fopen ("list.txt", "r"); ``` but the file is not opend! and when i put the full path like this : ``` file = fopen ("/home/rami/Desktop/netfilter/list.txt", "r"); ``` it is working! why the first example is not working? the list.txt is in the same directory of the c file thanks.
It's not the directory of theCfile that matters, it'syour current working directorythat does. Try ``` cd /home/rami/Desktop/netfilter ``` before running the executable.
We have postgres 8 installed on a linux box, and I'm copying over data and triggers from our windows version to this new one. However, plpgsql isn't installed by default, so copying my trigger source is failing. I only have C or Internal languages to choose from; barring asking the DBA to install plpgsql, can anyone help me convert this: ``` CREATE OR REPLACE FUNCTION "datestampTrigger"() RETURNS "trigger" AS 'BEGIN -- check for datecreated IF NEW.datecreated IS NULL THEN NEW.datecreated := ''now''; END IF; NEW.datelastmodified := ''now''; RETURN NEW; END;' LANGUAGE plpgsql VOLATILE; ```
On most linux systems I have encountered plpgsql is actually installed on the system but is not included in the database template. Executing the following "activates" plpgsql in your database. ``` CREATE LANGUAGE plpgsql; ```
I want to change the linux kernel code to filter some tcp packet and drop it. But I always keep receiving it again and again. Here is my code in /net/ipv4/tcp_ipv4.c ``` int tcp_v4_do_rcv(struct sock *sk, struct sk_buff *skb) { // my code start struct iphdr *iph; iph = skb->nh.iph; if(iph->ttl > 64) // I want to drop all tcp packet that meet this requirement { return 0; } // my code end // start normal linux code if(sk->sk_state == TCP_ESTABLISHED) { /* Fast path */ ... } ```
As @nos said, TCP is reliable, so the other end will retransmit the dropped packet. You would need to send a RST or an ICMP ERROR (probably host unreachable, administratively prohibited) to teardown the connection. Also, note that you've created a memory leak, you're responsible for freeing skb's when you discard them.
I'd like to know how many instructions are needed for a function call in a C program compiled with gcc for x86 platforms from start to finish.
Write some code.Compile it.Look at the disassembly.Count the instructions. The answer will vary as you vary the number and type of parameters, calling conventions etc.
What are the recommended XML parsers for parsing a TMX file(XML based tilemap) in C? What are the pros and cons of each, as I would like to have an efficient one because it will be running on an embedded system.
We used libxml on an embedded product a while back. It may be right for you.
I am trying to print a dynamic array, but I am having trouble with the bounds for the array. For a simple example, lets say I'm trying to loop through an array of ints. How can I get the size of the array? I was trying to divide the size of the array by the size of the type like thissizeof(list)/sizeof(int)but that was not working correctly. I understand that I was trying to divide the size of thepointerby the type. ``` int *list // Populate list int i; for(i = 0; i < ????; i++) printf("%d", list[i]); ```
With dynamic arrays you need to maintain a pointer to the beginning address of the array and a value that holds the number of elements in that array. There may be other ways, but this is the easiest way I can think of. sizeof(list) will also return 4 because the compiler is calculating the size of an integer pointer, not the size of your array, and this will always be four bytes (depending on your compiler).
I wondered if there are any simpler or more powerful syntax for C or C++. I have already come acrossSPECS. That is an alternative syntax for C++. But are there any others and what about C? It could also be a sort of code generator so that things like functors could be defined less verbosely. I imagine it could be made as a code generator that compiles to C or C++ code which is very similar to the code you wrote in the alternative syntax. Mirahis an example of doing this for Java. Ideally I would want to write C in Go like syntax. I like how they fixed switch-case, and in general made everything much less verbose.
``` #define BEGIN { #define END } ``` No!Just say NO!
Question: In C/C++, is there any system function that accepts Unicode ? See below for reason: ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { // http://stackoverflow.com/questions/3313332/bringing-another-apps-window-to-front-on-mac-in-c system("osascript -e \"tell application \\\"Address Book\\\" to activate\""); return EXIT_SUCCESS; } ```
Use_wsystem. _wsystemis a wide-character version ofsystem; the command argument to_wsystemis a wide-character string. These functions behave identically otherwise. http://msdn.microsoft.com/en-us/library/277bwbdz.aspx A special function namedmainis the starting point of execution for all C and C++ programs. If you are writing code that adheres to the Unicode programming model, you can usewmain, which is the wide-character version of main. http://msdn.microsoft.com/en-us/library/vstudio/6wd819wh.aspx
there has been many previous questions about redirecting stdout/stderr to a file. is there a way to redirect stdout/stderr to a string?
Yes, you can redirect it to anstd::stringstream: ``` std::stringstream buffer; std::streambuf * old = std::cout.rdbuf(buffer.rdbuf()); std::cout << "Bla" << std::endl; std::string text = buffer.str(); // text will now contain "Bla\n" ``` You can use a simple guard class to make sure the buffer is always reset: ``` struct cout_redirect { cout_redirect( std::streambuf * new_buffer ) : old( std::cout.rdbuf( new_buffer ) ) { } ~cout_redirect( ) { std::cout.rdbuf( old ); } private: std::streambuf * old; }; ```
I have a 15-digit floating-point number and I need to truncate the trailing zeros after the decimal point. Is there a format specifier for that?
%Lgis probably what you want: seehttp://developer.apple.com/library/ios/#DOCUMENTATION/System/Conceptual/ManPages_iPhoneOS/man3/printf.3.html.
Having an issue with printing a pointer out. Every time I try and compile the program below i get the following error: ``` pointers.c:11: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘int *’ ``` I'm obviously missing something simple here, but from other examles of similar code that I have seen, this should be working. Here's the code, any help would be great! ``` #include <stdio.h> int main(void) { int x = 99; int *pt1; pt1 = &x; printf("Value at p1: %d\n", *pt1); printf("Address of p1: %p\n", pt1); return 0; } ```
Simply cast your int pointer to a void one: ``` printf( "Address of p1: %p\n", ( void * )pt1 ); ``` Your code is safe, but you are compiling with the-Wformatwarning flag, that will type check the calls toprintf()andscanf().
When trying to compile my prgram with: ``` gcc -pedantic -Wall -ansi ``` I get the warning:warning: statement with no effect Referring to this line: ``` for(currentDirection; currentDirection <= endDirection; currentDirection++) ``` Can anyone help me with this?
currentDirection;does nothing. Replace your line with ``` for(; currentDirection <= endDirection; currentDirection++) ``` Or, in case you just forgot to initialize the variable: ``` for(currentDirection = 0; currentDirection <= endDirection; currentDirection++) ```
I was reading a book and came across a program to read entries from a/procfile. The program which they mentioned has following line ``` printf("%.*s", (int) n, line); ``` I am not clear with meaning of above line what type of print if above"%.*sused instead of%s The code can be readhere
Abstract fromhere: .* - The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted. So this prints up to n characters from line string.
Createprocess API has a option to create a process with CREATE_SUSPENDED flag. Similarly, is there any possiblity in ShellExecute APIs to create the process in suspended state.
No. ShellExecute doesn't have to imply a process is launched - it's used to perform "shell operations" such as "open" or "print", whichmaylead to a new process being created.
Part of the code is as follows but not work ``` printf("Enter a line of text (Enter to stop): "); fflush(stdin); fgets(input, 256, stdin); if (input == '\0') { exit(0); } ..... ..... ``` i want if the user only press enter, the program will be terminated. how to do it? thanks
Useif(*input == '\n')- iffgetsreads a newline, it's stored in the buffer.
I am using mysql cpp library . I checkout the recent copy from there bzr trunk and used cmake to generate library . First time I used release mode and second time I used debug mode to build. The both library have ``` a mysql_debug.cpp U mysql_debug ``` Is there a way to check in program (C or C++ code) or using nm that library is Release library or Debug library
I have seen false negatives with nm so I do not trust it. When I want to check to see if an object file has debug info I run objdump -x on the object file or library and look to see if there are headers that say dbg, stabs, or dwarf. This is not the most elegant solution by any means, but it has never been wrong and it is real easy to see the difference in when you have a debug and release build to compare.
is there any example of using work/pool (or. Producer/Consumer) scheme for MPI? As for everything I have done, I am getting just one going through application and my app is deadlocked then. Thanks
Just googling around for "MPI Master Worker" or "MPI Master Slave", I see a bunch of examples; one good one hosted at Argonne National Labs is: http://www.mcs.anl.gov/research/projects/mpi/tutorial/mpiexmpl/src2/io/C/main.html
Will thefree()routine work if I dynamically allocate an array and then pass, not the initial pointer, but a pointer to the middle of the array? Example: ``` int* array = malloc(10 * sizeof *array); if(array) { array += 5; // adjusting the indicies free(array); } ``` Or do I need to set the pointer back to the start of the array before callingfree()?
Absolutely not. The value passed tofree()must be exactly the same value returned bymalloc(). In fact, to ensure this is the case, I would recommend you use a copy of the pointer if you need a pointer you can increment or otherwise modify.
Suppose in a C program I have P threads running on a 32 bit machine, andint MAX--a shared 32-bit integer Each thread can read/write to MAX. Requirement:the value a thread read should not be corrupted, e.g first 16bit and last 16bit are out of sync Question:Do I need a lock to protect the read and write? or Can I safely ignore the lock, because LOAD/SAVE assembly instruction is guaranteed to happen atomically?
Reads and writes are atomic when the int is aligned properly. It cannot straddle the end of a cache line. A cache line is 64 bytes. Most any compiler ensures the alignment is taken care of but it can be overridden with, say, a structure packing pragma. Yes, you need a lock to protect the value when threads perform a read-modify-write operation. You can get a cheap one from InterlockedXxxx, perhaps.
Thanks! I just had to cast the right side of the assignment to Term. I have to make a dynamic array of polynomials that each have a dynamic array of terms. When giving the term a exponent and coefficient, I get an error "expected expression before '{' token". What am I doing incorrectly when assigning the values? Also, is there an easy way of keeping the dynamic array of terms ordered by their exponent? I was just planning on looping through, printing the max value but would prefer to store them in order. Thanks! ``` polynomialArray[index].polynomialTerm[0] = {exponent, coefficient}; // ISSUE HERE ``` change to ``` polynomialArray[index].polynomialTerm[0] = (Term){exponent, coefficient}; ```
``` polynomialArray[index].polynomialTerm[0]->exponent = exponent; polynomialArray[index].polynomialTerm[0]->coefficient = coefficient; ```
I'm wondering how gdb attaches a running program in linux(*nix)? I have windows "hook" programming experience. On windows, I can register a "Hook" to some events of a program(or any program), and when the event occurs(such as mouse click), OS injects my hook-dll into that program's process space and invokes my callback function. Then my program attaches a running program and gets access to the attached program's data and functions. How does linux do? Does it similar to Windows? Thank you, in advance!
Looks to be through theptrace() function. Although, I've never played around with it.
Would it be possible to take a users input as a variable to be used in an expresion? ``` scanf("%s", op); //User enters "==" or "!=" if(x op y) //Go. ```
No. The best you can do is something like: ``` scanf("%s", &op); if (strcmp(op, "==") == 0) { result = x == y; } else if (strcmp(op, "!=") == 0) { result = x != y; } // now use result ```
Ah, thanks! Makes sense. Just made command of size MAX_COMMAND_LENGTH + 1. I am trying to to use fscanf to read the same file 2 different times in a loop but I am getting a seg fault. The idea is that the file will be formatted so that it has a command at the beginning of each line, followed by arguments for the command. ``` char* command; //Changed to char command[MAX_COMMAND_LENGTH + 1] while(fscanf(file, "%s", command) == 1) { if (strcmp("CMD1", command) == 0) { int index, exp, coeff; fscanf(file, "%d %d %d", &index, &exp, &coeff); } else if (strcmp("CMD2", command) == 0) { int num; fscanf(file, "%d", &num); } } ```
You need to allocate memory forcommand. For example: ``` command = (char *)malloc(1024 * sizeof(char)); ``` will allocate enough memory for 1024 characters. Remember tofree(command)when you're finished with it.
I wrote a program to count blanks. I can compile it and run it, it's fine. But why it does not display the count? ``` #include<stdio.h> main() { int count=0; int c; while((c=getchar())!=EOF) { if(c == ' ') count++; } printf("%d\n",count); } ```
Your exact code (errors and all) works as you'd expect atideone. How do you terminate the input? To send an EOF signal to your program from the console type, at the beginning of a line,CtrlDin Linux orCtrlZin Windows. Also try to run with redirected input. Something like ``` yourprog < data.txt ``` or ``` echo one two three four | yourprog ```
When using realloc is the memory automatically freed? Or is it necessary to use free with realloc? Which of the following is correct? ``` //Situation A ptr1 = realloc(ptr1, 3 * sizeof(int)); //Situation B ptr1 = realloc(ptr2, 3 * sizeof(int)); free(ptr1); ptr1 = ptr2; ```
Neither is correct. realloc() can return a pointer to newly allocated memory or NULL on error. What you should do is check the return value: ``` ptr1 = realloc(ptr2, 3 * sizeof(int)); if (!ptr1) { /* Do something here to handle the failure */ /* ptr2 is still pointing to allocated memory, so you may need to free(ptr2) here */ } /* Success! ptr1 is now pointing to allocated memory and ptr2 was deallocated already */ free(ptr1); ```
I've been trying to open a new terminal window from my application and execute a command on this second window as specified by the user. I've built some debugging software and I would like to execute the user's program on a separate window so my debugging output doesn't get intermixed with the programs output. I am usingfork()andexec(). The command I am executing isgnome-terminal -e 'the program to be executed'. I have 2 questions: Callinggnome-terminalmeans the user has to be running a gnome graphical environment. Is there a more cross-platform command to use (I am only interested in Linux machines though)?After the command finishes executing the second terminal also finishes executing and closes. Is there any way to pause it, or just let it continue normal operation by waiting for input?
You probably want something likexterm -hold.
Lately I had a task that included printing base-4 representation of a number. Since I didn't find a function to do it for me, I implemented it (which is not so hard of course), but I wonder, is there a way to do it using format placeholders? I'm not asking how to implement such function, but if such function / format placeholder already exists?
There is no standard C or C++ function, but you may be able to useitoa
I'm just learning C typing and am wondering what's wrong with the following example. When I try to compile it I get the error: "format '%i' expects type int, but argument 2 has type 'int(*)(int, int)'. ``` #include <stdio.h> int difference (int x, int y); int sum(int x, int y); main(){ int differ = difference(10, 5); int thesum = sum(3, 4); printf("differnece: %i, sum: %i \n", differ, sum); } int sum(int x, int y){ return x + y; } int difference (int x, int y){ return x - y; } ```
You usedsum(a function) where you presumably intendedthesum(an(int)variable).
``` typedef struct _lnode{ struct _lnode *next; unsigned short row; unsigned short column; short data; }lnode; typedef struct _llist{ struct _lnode *header; unsigned int size; }llist; lnode* add(lnode *lnode, lnode *newNode); ``` I have this code in .h file and if I am trying to compile then it complains "expected declaration specifier" at the line where I declare "add" function. I recently changed IDE to Eclipse CDT and this code worked just fine on my Linux machine..
``` lnode* add(lnode *node, lnode *newNode); ``` don't name your variable like your typedef and in the prototype, you don't have to name them at all ``` lnode* add(lnode*, lnode *); ```
I've tried searching here and on google, i ended up with the "GetDlgItem" method, but it doesn't work. Here is my code: ``` HWND hwnd_Parent; HWND hwnd_Child; hwnd_Parent = FindWindow(NULL,"MyTitle"); hwnd_Child = GetDlgItem(hwnd, 0x00030756); ``` hwnd_Parent is ok (i even did some post message tests), but hwnd_Child is null. So, the hex number you see was found through WinSpy++. My system is Windows 7 64 bits, my IDE is Code Blocks. Thanks in advance.
You need to know the ID of the window to useGetDlgItem(). I suspect you are passing in an HWND that you got from Spy++. It looks like you are poking around in another app because if it was your own app then you wouldn't need to call FindWindow, and you'd know the control ID. Probably the easiest way to find this window, once you have got the top-level window from FindWindow, is to callEnumChildWindows().
I heard that C compiler with/without optimization option may generate different program(compiling the program with optimizations causes it to behave differently), but I never encountered such case. Anyone can give simple example to show this?
For gcc 4.4.4, this differs with-O0and-O2 ``` void foo(int i) { foo(i+1); } main() { foo(0); } ``` With optimizations this loops forever. Without optimizations, it crashes (stack overflow!) Other and more realistic variants would typically be dependent on timing, vulnerable to float exactness variations, or depending on undefined behavior (uninitialized variables, heap/stack layout)
I need to print an array of in order of largest to smallest. For simplicity, we'll say that it is an array of ints. The only way I can think to do it is loop through the array, find the largest element, print it and set a corresponding boolean flag so it doesn't get printed twice. Is there a better way to go about this? ``` int *array; // Fill array, malloc, all that good stuff int i, j, max = 0, max_index = 0; int isPrinted[ARRAY_SIZE] = {0}; for (i = 0; i < ARRAY_SIZE; i++) { for (j = 0; j < ARRAY_SIZE; j++) { if (isPrinted[j] == 0 && array[j] > max) { max = array[j]; max_index = j; } } isPrinted[max_index] = 1; printf("%d", max); max = 0; } ```
Yes..sort the array before printing and then print it. If you can't modify the original array, copy the elements to another inserting them in the correct order and print the second one.
I am trying to print a dynamic array, but I am having trouble with the bounds for the array. For a simple example, lets say I'm trying to loop through an array of ints. How can I get the size of the array? I was trying to divide the size of the array by the size of the type like thissizeof(list)/sizeof(int)but that was not working correctly. I understand that I was trying to divide the size of thepointerby the type. ``` int *list // Populate list int i; for(i = 0; i < ????; i++) printf("%d", list[i]); ```
With dynamic arrays you need to maintain a pointer to the beginning address of the array and a value that holds the number of elements in that array. There may be other ways, but this is the easiest way I can think of. sizeof(list) will also return 4 because the compiler is calculating the size of an integer pointer, not the size of your array, and this will always be four bytes (depending on your compiler).
I wondered if there are any simpler or more powerful syntax for C or C++. I have already come acrossSPECS. That is an alternative syntax for C++. But are there any others and what about C? It could also be a sort of code generator so that things like functors could be defined less verbosely. I imagine it could be made as a code generator that compiles to C or C++ code which is very similar to the code you wrote in the alternative syntax. Mirahis an example of doing this for Java. Ideally I would want to write C in Go like syntax. I like how they fixed switch-case, and in general made everything much less verbose.
``` #define BEGIN { #define END } ``` No!Just say NO!
Question: In C/C++, is there any system function that accepts Unicode ? See below for reason: ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { // http://stackoverflow.com/questions/3313332/bringing-another-apps-window-to-front-on-mac-in-c system("osascript -e \"tell application \\\"Address Book\\\" to activate\""); return EXIT_SUCCESS; } ```
Use_wsystem. _wsystemis a wide-character version ofsystem; the command argument to_wsystemis a wide-character string. These functions behave identically otherwise. http://msdn.microsoft.com/en-us/library/277bwbdz.aspx A special function namedmainis the starting point of execution for all C and C++ programs. If you are writing code that adheres to the Unicode programming model, you can usewmain, which is the wide-character version of main. http://msdn.microsoft.com/en-us/library/vstudio/6wd819wh.aspx