question
stringlengths
25
894
answer
stringlengths
4
863
I have below programme where memory is read-only, but I am still able to write to it. ``` main() { char *p="amit"; p[0]="s"; printf("%s",p); } ``` The output is "smit" Is it the expected output sinceppoints a location that is read-only? When I run this programme on GCC or on Visual C++, I get a segmentation fault, but on Turbo C++ I get "smit". Please confirm this behaviour...
Writing to a string literal gives undefined behavior, so the compiler is allowed to do anything it wants when you do that. The simple answer is that Turbo C++ compiles for real-mode, so none of the memory is protected. Neither the compiler nor the OS will stop you from writing anything anywhere.
What is the best practice for C what you put into a C header file? Is it useful to put all the includes used for a program across multiple source files in one header file? What about includes that are used in practically every file (i.e. stdio.h)?
No. It simply adds cruft and overhead. One of the biggest pains that you'll face as a maintainer is figuring out what headersdon'tneed to be included and get rid of them. Whe you get to a list of 20+ headers, you startcontemplating ugly thingslike brute forcing through it (removing one at a time and seeing if anything breaks). Be kind to people who have to maintain your stuff in the future. Use the headers you need per module, no more .. no less :)
With OpenGL, there's a lot of times where putting strides on the data is necessary for better efficiency. for example, the memory structure would be vertex-color-normal-vertex-color-normal.. etc. Is there any viable option for changing, say, only the color section of a memory with some kind of memset variant (that is, not using a loop). Also brings to question, is there such thing as a looping memset? For example, in an array of colors made of four floats each, set all of them to a particular color.
Just use a loop. There is nothing magical about memset, internally it is just using a loop, it may on same compilers be slightly optimized to clear 64bits at a time if used with 0, but it doesn't set a block of memory in a single instruction
I'm searching with brute force for a floating point number with certain properties (small roundoff error of sin(a)^2+cos(a)^2-1). I therefore want to loop over the neighborhood of a given floating point number by incrementing the significand. Is there a simple way to do that in C?
C99 has nextafter and nexttoward; they weren't present in C90.
Why does the following code output the same memory location everytime? ``` int x; for (x = 0; x < 10; x++) { int y = 10; printf("%p\n", &y); } ``` I thought that the memory location should change as each time the for-loop is run, the variable is new.
Yes, you are absolutely right that the memory locationcouldchange. But it doesn't have to :). In each iteration the old variable is "destroyed" and a new one is "created" at the same place. Although any decent compiler would optimize the unnecessary "actions" away
I want to build a library from multiple source files, like a1.cpp a2.cpp. I used the following command, 'g++ -o libcode -c a1.cpp a2.cpp'. However, error pop up "cannot specify -o with -c or -S with multiple files". In general, how should I build such lib from multiple sources? thanks...
You first compile your source files to objects files (*.o), and then invoke thearcommand to build the library. In your example: ``` g++ -c a1.cpp a2.cpp ar rcs libcode.a a1.o a2.o ``` This would build a static library, you can also create a dynamic one. http://www.network-theory.co.uk/docs/gccintro/gccintro_79.html http://tldp.org/HOWTO/Program-Library-HOWTO/static-libraries.html
``` unsigned short a; char temp[] = "70000"; a = atoi(temp); printf("a: %d\n", a); ``` Gives me the outputa: 4464when it should bea: 70000Is there a better way to convert from ASCII to a decimal? The range of a unsigned short is 0 - 65535
Asschnaader said, you may be running into an overflow problem. But answering yourprintfquestion about outputting unsigned values, you want theumodifier (for "unsigned"). In this case, as Jens points out below, you want%hu: ``` printf("a: %hu\n", a); ``` ...although just%u(unsigned int, rather thanunsigned short) would probably work as well, because theshortwill get promoted tointwhen it gets pushed on the stack forprintf. But again, that's only if the value 70000 will fit in anunsigned shorton your platform.
Between formal parameters in a function definition, like: ``` void change (int *s) { s[0] = 42; } ``` And another definition: ``` void change (int s[]) { s[0] = 42; } ``` They are the same I assume, as*(a+0)is the same asa[0]. Is there a reason to prefer one over the another? Please note, the preference pertains to coding style.
Yes, they are exactly the same. All function parameters declared as arrays are adjusted to the corresponding pointer type. Personally, I prefer the former which actually makes it look like a pointer declaration which is what it is in both cases.
I need a program that polls a site every second and responds if the site doesnt respond in 15 seconds. I made the following hack from an example program. On a dry run, it printed 7 times in 15 seconds. Cant I make curl_easy_perform wait for 15 seconds before responding? ``` int main(void) { CURL *curl; CURLcode res; char *postthis="moo mooo moo moo"; curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, "http://192.168.1.101"); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postthis); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(postthis)); curl_easy_setopt(curl, CURLOPT_TIMEOUT, 15); while(1) { Sleep(1000); res = curl_easy_perform(curl); if(res!= CURLE_OK) printf("nada \n"); } ```
``` Sleep(15000 - timeTakenForCurlInMs); ```
``` #!/usr/bin/env perl use warnings; use 5.012; use Inline 'C'; my $value = test(); say $value; __END__ __C__ void test() { int a = 4294967294; Inline_Stack_Vars; Inline_Stack_Reset; Inline_Stack_Push( sv_2mortal( newSViv( a ) ) ); Inline_Stack_Done; } ``` Output: ``` -2 ``` Why do I get here an output of "-2"?
int auses probably 32-bit representation. You should useunsigned intif you want to represent values above 4,294,967,296/2.
What is the best way to generate an HTTP session ID and avoid collisions as much as possible? How long should my session ID be?
Just use a Guid. This will very hard to get a duplicate one.
I am getting an error described in the title when I try to run my code with this line: ``` (int**)newPtr = *(list + index); ``` Does anyone know whats wrong? These are my declarations ``` int index; int* newPtr; static int* list; ```
There are a couple of errors in the code: newPtr is declared as a pointer-to-integer, but you are casting it to pointer-to-pointer-to-integer which is wrong.list+index is also a pointer-to-integer to *(list+index) is an integer pointed to by (list+index). But you are trying to assign that to newPtr (which is also casted to wrong type as above). Possibly you intended to do this: ``` newPtr = list+index; ``` and get a pointer-to-integer located at list + index-th location.
Consider a char array like this: ``` 43 234 32 32 ``` I want the last value that is32in integer form. The string size/length is not known. In the above example there are 4 numbers, but the size will vary. How can this be done?
i have copied these value from the file onto char array.now i want the last number in integer variable When you were copying,add a counter of # of characters copied. Then do this ``` int count = 0; char c; while(c = readCharFromFile()) { array[count++] = c; } int last = array[count - 1]; ```
Given a gray code for a number, find the binary code for the number. Gray code is a binary numeral system where two successive values differ in only one bit. For Example two bit gray code is: 0 - 00 1 - 01 2 - 11 3 - 10 Binary is: 0 - 00 1 - 01 2 - 10 3 - 11 Provide an algorithm to convert the gray code of the number to binary code. For example, input is 11. Expected output is 10.
Converting the Gray code to binary is: Retain the Most significant bit as it is and for the rest of the bits keep xoring the successive bits. ie Gn Gn-1 Gn-2 ........ G1 is the gray code and Bn Bn-1 .......B1 is the binary code. Bn= Gn and for all the other bits Bn-1 = Gn-1 XOR Gn
Can we predict how a C struct will be implemented by the compiler? If I write the (very badly aligned) struct: ``` struct { uint16_t a; uint32_t b; uint8_t c; } s; char *p = (char*)&s; ``` can I guarantee thatp[6]is the same ass.c? Are the struct fields allocated in this most obvious and canonical way, so we can predict where each field will be in memory? Edit: Willstruct __attribute__ ((__packed__)) {...} s;get me this behavior in GCC?
No you cannot. Don't do that. You are guaranteed only the order and the same compiler will always do the same layout. If you need such a thing consult your compiler's documentation for how to enable byte packing (always available) and pad yourself.
I am looking at making use of the Clang's AST for my C code and do some analysis over the AST. Some pointers on where to start, how to obtain the Clang's AST, tutorials or anything in this regard will be of great help!!! I have been trying to find some and I got thislinkwhich was created 2 years back. But for some reason, it is not working for me. The sample code, in the tutorial, gives me too many errors. So I am not sure, if I build the code properly or some thing is wrong with the tutorial. But I would be happy to start from some other page as well.
Start with the tutorial linked by sharth. Then go through Clang's Doxygen. Start withSemaConsumer. Read a lot of source code. Clang is a moving target. If you are writing tools based on clang, then you need to recognize that clang is adding and fixing features daily, so you should be prepared to read a lot of code!
I'm trying to use execlp(), but keep getting warnings that I'm not sure how to fix pathPiece is an array of paths to attempt to use in order to find the command.pathNum is the number of paths there are to try. ``` void execute(const char *argv, char *path, int argNum, const char **pathPiece, int pathNum){ int i, ret; for(i = 0; i < pathNum; i++) if(argNum == 0){ ret = execlp((const char *)&pathPiece[i], (const char *)argv[0], (const char*)NULL); if(ret == -1) continue; else{ break; } } } ``` warning: cast to pointer from integer of different size
pathPiece isconst char *pathPiece, so pathPiece[i] is a single char. From your description, it sounds like you want pathPiece to be aconst char **instead.
In windows, Java, etc, the scroll pane scrolls the widgets inside. What I'm wondering is, how exactly does it do its scrolling? Does it change the location of each nested widget, or does it have a content widget that it moves around? Or is it something else? Also, when both scrollbars are present, how does it mask that little square at the bottom right? That square is sometimes used to resize. Is it a separate nested widget? Thanks
I think it just changes the location of the widget, button, or thing-a-ma-bober. But my second guess would be it just draws the components "outside" of the scroll pane without being seen and when you scroll it just redraws dynamically.
Imagine the picture above represents a 6*6 array of ints where 0 is black. Is there a quick algorithm to split the non 0 cells into rectangles? Ideally the check would be contained within a for loop,without creating any other arrays. ``` for(x = 0; x < 6; x++) for(y = 0; y < 6; y++) if(cellIsBottomRightOfRect(x,y)) { left = getLeft(x,y); top = getTop(x,y); printf("Rect: %d,%d %d,%d \n", left, top, x, y); } ```
How about using a recursive method which calls itself everytime it encounters a color different than the one it is trying to group at the moment?
``` #include<stdio.h> #include<conio.h> #define PROD(x) (x*x) void main() { clrscr(); int p=3,k; k=PROD(p+1); //here i think value 3+1=4 would be passed to macro printf("\n%d",k); getch(); } ``` In my opinion, the output should be16, but I get7. Can anyone please tell me why?
Macros areexpanded, they don't have valuespassedto them. Have look what your macro expands to in the statement that assigns tok. ``` k=(p+1*p+1); ``` Prefer functions to macros, if you have to use a macro the minimum you should do is to fully parenthesise the parameters. Note that even this has potential surprises if users use it with expressions that have side effects. ``` #define PROD(x) ((x)*(x)) ```
Has a way to get the datatype in C? For example: ``` int foo; if (foo is int) { // do something } ``` or something like: ``` if (typeof(foo) == typeof(int)) { // do something } ``` Thanks in advance.
This is called type introspection or reflection and is not supported by the C language. You would probably have to write your own reflection library, and it would be a significant effort.
So I read that: char pattern[] = "ould"; is basically the easier way of writing: char pattern[] = { 'o', 'u', 'l', 'd', '\0' }; I understand that the null character\0marks the end of a string, but what if I write it like: char pattern[] = { 'o', 'u', 'l', 'd'};(without the \0) It still compiles. Where wouldpatternwithout the\0cause problems, because it seems to be compile without warnings (-Wall)
If you leave off the terminating zero, you no longer have a null terminated string, just an array ofchar, so passing it to any function that expects a string would be an error. E.g.strlen, as the source parameter tostrcpy, as a...parameter toprintfwith a%sformat specifier, etc.
What is the best way to integrate C with JAVA for Blackberry app? In core java, we can use JNI for integration. But in Blackberry app ? Thanks in advance.
You can't integrate C, as RIM does not expose any API for the platform. Since BlackBerry use a j2me-compliant JVM, JNI is not exposed. Prior answer is partially correct - you may write code that uses only the J2ME API, but you can also use RIM's own Java API for better/more advanced features and functionality.
code: ``` char *m[10]; char * s; int lcounter=0; int sd=0; char mem_buf [ 500 ]; while ( fgets ( mem_buf, sizeof mem_buf, infile ) != NULL ) { m[lcounter] =(char *) malloc(10*sizeof(char)); item = strtok(mem_buf,delims); m[lcounter]=item; printf("\n value inside==== :%s:",m[lcounter]); lcounter=lcounter+1; } for(i=0;i<lcounter;i++) { printf("\n value outside==== :%s:",m[sd]); sd++; } ``` input: ``` goo| bbb| ccc| ``` When I execute this am getting below output: ``` value inside==== : goo value inside==== : bbb value inside==== : ccc value outside====:ccc value outside====:ccc value outside====:ccc ``` But I need like: ``` value outside====:goo value outside====:bbb value outside====:ccc ```
Usestrcpyif you want it to last outside of the loop.strtokmay reuse the same pointer.
can someone explain to me the difference between Vector and Linked List ADT in a c programming language context. Thanks.
Well, in C, there are no "vector" and "list" data types available to you directly like in C++ std library. But in terms of "abstract data type", a vector is usually considered to represent contiguous storage, and a linked list is considered to be represented by individual cells linked together. Vectors provide fast constant time random-access read and write operations, but inserting and deleting vector elements take linear time. Lists have linear lookup performance to find an element to read and write, but given an element location, have constant time insertion and deletion. You can also add items to the start and to the end of a list in constant time (if the ADT implementation caches the location of the last element in the list).
Is there a standard library or commonly used library that can be used for calculating SHA-512 hashes on Linux? I'm looking for a C or C++ library.
Have you checkedOpenSSL. I myself have not used it but documentation says it supports it. Here is list offew more implementations. Example code ``` md = EVP_get_digestbyname("sha512"); EVP_MD_CTX_init(&mdctx); EVP_DigestInit_ex(&mdctx, md, NULL); EVP_DigestUpdate(&mdctx, mess1, strlen(mess1)); EVP_DigestUpdate(&mdctx, mess2, strlen(mess2)); EVP_DigestFinal_ex(&mdctx, md_value, &md_len); EVP_MD_CTX_cleanup(&mdctx); ```
I know that on your hard drive, if you delete a file, the data is not (instantly) gone. The data is still there until it is overwritten. I was wondering if a similar concept existed in memory. Say I allocate 256 bytes for a string, is that string still floating in memory somewhere after Ifree()it until it is overwritten?
Your analogy is correct. The data in memory doesn't disappear or anything like that; the values may indeed still be there after afree(), though attempting to read from freed memory is undefined behaviour.
These obnoxious warnings are on-by-default in current gcc, and I can't find which option is needed to disable them. They're generating warning-spam and preventing compiling with-Werrorin code where the behavior gcc warns about is intentional (and comes from general-purpose macros that could not easily avoid generating such constants).
After digging through the GCC source code, I found that the warnings you've described are part of the-Woverflowoption. So just turn off that warning. By the way, this comment is in the code for the warning: Both C and C++ require a diagnostic for a floating constant outside the range of representable values of its type... We also give a warning if the value underflows.
Hey, I am wondering how void pointers is applied in the real world in terms of making a software more secure, more flexible. For example, I know that void pointers, what pointer it will cast to is hidden to outside, which will make a software more secure. Are there other reasons why you would use void pointers?
Void pointers don't make the software any more secure. The reason to use void* in c is a form of polymorphism - if you don't know what type the data will be you can pass a void* In C++ there is less need to use void* and the language prevents some of the C uses
When I compile and run this code (it's part of a much larger program), Linux gets halfway through thewhileloop, then simply stops working. The code below printstime: 0and then hangs, doing nothing else until I suspend the process. Why on earth would it printtime: 0but not the following line of sanity check? ``` while (i < 5) { printf("time: %d\n",elapsedTime); printf("sanity check"); foo(); i++; } ```
Output usually is buffered and only written after a flush or newline. In ``` printf("sanity check"); ``` there is no newline, so if you run in an endless loop after this, you won't see it. Replace it with ``` printf("sanity check\n"); ``` or ``` printf("sanity check"); fflush(stdout); ``` and you'll see it.
In C, are the following equivalent: long int x = 3L;(notice theL) and long int x = 3 They seem to be the same. In case they are, which one should be used? Should theLbe specified explicitly? If they are different, what is the difference?
3.14Lis along doubleliteral, while3.14is adoubleliteral. It won't make much difference in this case, since both are being used to initialize a long int. The result will be 3. EDIT: Ok,3Lis alongliteral, while3is anintliteral. It still won't make much difference, since theintwill be "promoted" to a long. The result will be the same in both cases. EDIT 2: One place it might make a difference is something like this: ``` printf("%ld\n", 123); ``` This is undefined behavior, since the format string specifies alongand only anintis being passed. This would be correct: ``` printf("%ld\n", 123L); ```
``` char copy, array[20] printf("enter ..."): scanf("%s", array); if (strlen(array) > 20 ) { strcpy(copy, array....); ``` what would I need to do to make it only grab the first 20 character if the input is more then 20 character long
``` char array[20+1]; scanf("%20s", array); ``` Problem solved.
``` unsigned short a; char temp[] = "70000"; a = atoi(temp); printf("a: %d\n", a); ``` Gives me the outputa: 4464when it should bea: 70000Is there a better way to convert from ASCII to a decimal? The range of a unsigned short is 0 - 65535
Asschnaader said, you may be running into an overflow problem. But answering yourprintfquestion about outputting unsigned values, you want theumodifier (for "unsigned"). In this case, as Jens points out below, you want%hu: ``` printf("a: %hu\n", a); ``` ...although just%u(unsigned int, rather thanunsigned short) would probably work as well, because theshortwill get promoted tointwhen it gets pushed on the stack forprintf. But again, that's only if the value 70000 will fit in anunsigned shorton your platform.
Between formal parameters in a function definition, like: ``` void change (int *s) { s[0] = 42; } ``` And another definition: ``` void change (int s[]) { s[0] = 42; } ``` They are the same I assume, as*(a+0)is the same asa[0]. Is there a reason to prefer one over the another? Please note, the preference pertains to coding style.
Yes, they are exactly the same. All function parameters declared as arrays are adjusted to the corresponding pointer type. Personally, I prefer the former which actually makes it look like a pointer declaration which is what it is in both cases.
I need a program that polls a site every second and responds if the site doesnt respond in 15 seconds. I made the following hack from an example program. On a dry run, it printed 7 times in 15 seconds. Cant I make curl_easy_perform wait for 15 seconds before responding? ``` int main(void) { CURL *curl; CURLcode res; char *postthis="moo mooo moo moo"; curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, "http://192.168.1.101"); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postthis); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(postthis)); curl_easy_setopt(curl, CURLOPT_TIMEOUT, 15); while(1) { Sleep(1000); res = curl_easy_perform(curl); if(res!= CURLE_OK) printf("nada \n"); } ```
``` Sleep(15000 - timeTakenForCurlInMs); ```
``` #!/usr/bin/env perl use warnings; use 5.012; use Inline 'C'; my $value = test(); say $value; __END__ __C__ void test() { int a = 4294967294; Inline_Stack_Vars; Inline_Stack_Reset; Inline_Stack_Push( sv_2mortal( newSViv( a ) ) ); Inline_Stack_Done; } ``` Output: ``` -2 ``` Why do I get here an output of "-2"?
int auses probably 32-bit representation. You should useunsigned intif you want to represent values above 4,294,967,296/2.
What is the best way to generate an HTTP session ID and avoid collisions as much as possible? How long should my session ID be?
Just use a Guid. This will very hard to get a duplicate one.
I am getting an error described in the title when I try to run my code with this line: ``` (int**)newPtr = *(list + index); ``` Does anyone know whats wrong? These are my declarations ``` int index; int* newPtr; static int* list; ```
There are a couple of errors in the code: newPtr is declared as a pointer-to-integer, but you are casting it to pointer-to-pointer-to-integer which is wrong.list+index is also a pointer-to-integer to *(list+index) is an integer pointed to by (list+index). But you are trying to assign that to newPtr (which is also casted to wrong type as above). Possibly you intended to do this: ``` newPtr = list+index; ``` and get a pointer-to-integer located at list + index-th location.
Consider a char array like this: ``` 43 234 32 32 ``` I want the last value that is32in integer form. The string size/length is not known. In the above example there are 4 numbers, but the size will vary. How can this be done?
i have copied these value from the file onto char array.now i want the last number in integer variable When you were copying,add a counter of # of characters copied. Then do this ``` int count = 0; char c; while(c = readCharFromFile()) { array[count++] = c; } int last = array[count - 1]; ```
Given a gray code for a number, find the binary code for the number. Gray code is a binary numeral system where two successive values differ in only one bit. For Example two bit gray code is: 0 - 00 1 - 01 2 - 11 3 - 10 Binary is: 0 - 00 1 - 01 2 - 10 3 - 11 Provide an algorithm to convert the gray code of the number to binary code. For example, input is 11. Expected output is 10.
Converting the Gray code to binary is: Retain the Most significant bit as it is and for the rest of the bits keep xoring the successive bits. ie Gn Gn-1 Gn-2 ........ G1 is the gray code and Bn Bn-1 .......B1 is the binary code. Bn= Gn and for all the other bits Bn-1 = Gn-1 XOR Gn
Can we predict how a C struct will be implemented by the compiler? If I write the (very badly aligned) struct: ``` struct { uint16_t a; uint32_t b; uint8_t c; } s; char *p = (char*)&s; ``` can I guarantee thatp[6]is the same ass.c? Are the struct fields allocated in this most obvious and canonical way, so we can predict where each field will be in memory? Edit: Willstruct __attribute__ ((__packed__)) {...} s;get me this behavior in GCC?
No you cannot. Don't do that. You are guaranteed only the order and the same compiler will always do the same layout. If you need such a thing consult your compiler's documentation for how to enable byte packing (always available) and pad yourself.
I am looking at making use of the Clang's AST for my C code and do some analysis over the AST. Some pointers on where to start, how to obtain the Clang's AST, tutorials or anything in this regard will be of great help!!! I have been trying to find some and I got thislinkwhich was created 2 years back. But for some reason, it is not working for me. The sample code, in the tutorial, gives me too many errors. So I am not sure, if I build the code properly or some thing is wrong with the tutorial. But I would be happy to start from some other page as well.
Start with the tutorial linked by sharth. Then go through Clang's Doxygen. Start withSemaConsumer. Read a lot of source code. Clang is a moving target. If you are writing tools based on clang, then you need to recognize that clang is adding and fixing features daily, so you should be prepared to read a lot of code!
I'm trying to use execlp(), but keep getting warnings that I'm not sure how to fix pathPiece is an array of paths to attempt to use in order to find the command.pathNum is the number of paths there are to try. ``` void execute(const char *argv, char *path, int argNum, const char **pathPiece, int pathNum){ int i, ret; for(i = 0; i < pathNum; i++) if(argNum == 0){ ret = execlp((const char *)&pathPiece[i], (const char *)argv[0], (const char*)NULL); if(ret == -1) continue; else{ break; } } } ``` warning: cast to pointer from integer of different size
pathPiece isconst char *pathPiece, so pathPiece[i] is a single char. From your description, it sounds like you want pathPiece to be aconst char **instead.
In windows, Java, etc, the scroll pane scrolls the widgets inside. What I'm wondering is, how exactly does it do its scrolling? Does it change the location of each nested widget, or does it have a content widget that it moves around? Or is it something else? Also, when both scrollbars are present, how does it mask that little square at the bottom right? That square is sometimes used to resize. Is it a separate nested widget? Thanks
I think it just changes the location of the widget, button, or thing-a-ma-bober. But my second guess would be it just draws the components "outside" of the scroll pane without being seen and when you scroll it just redraws dynamically.
Imagine the picture above represents a 6*6 array of ints where 0 is black. Is there a quick algorithm to split the non 0 cells into rectangles? Ideally the check would be contained within a for loop,without creating any other arrays. ``` for(x = 0; x < 6; x++) for(y = 0; y < 6; y++) if(cellIsBottomRightOfRect(x,y)) { left = getLeft(x,y); top = getTop(x,y); printf("Rect: %d,%d %d,%d \n", left, top, x, y); } ```
How about using a recursive method which calls itself everytime it encounters a color different than the one it is trying to group at the moment?
``` #include<stdio.h> #include<conio.h> #define PROD(x) (x*x) void main() { clrscr(); int p=3,k; k=PROD(p+1); //here i think value 3+1=4 would be passed to macro printf("\n%d",k); getch(); } ``` In my opinion, the output should be16, but I get7. Can anyone please tell me why?
Macros areexpanded, they don't have valuespassedto them. Have look what your macro expands to in the statement that assigns tok. ``` k=(p+1*p+1); ``` Prefer functions to macros, if you have to use a macro the minimum you should do is to fully parenthesise the parameters. Note that even this has potential surprises if users use it with expressions that have side effects. ``` #define PROD(x) ((x)*(x)) ```
Has a way to get the datatype in C? For example: ``` int foo; if (foo is int) { // do something } ``` or something like: ``` if (typeof(foo) == typeof(int)) { // do something } ``` Thanks in advance.
This is called type introspection or reflection and is not supported by the C language. You would probably have to write your own reflection library, and it would be a significant effort.
So I read that: char pattern[] = "ould"; is basically the easier way of writing: char pattern[] = { 'o', 'u', 'l', 'd', '\0' }; I understand that the null character\0marks the end of a string, but what if I write it like: char pattern[] = { 'o', 'u', 'l', 'd'};(without the \0) It still compiles. Where wouldpatternwithout the\0cause problems, because it seems to be compile without warnings (-Wall)
If you leave off the terminating zero, you no longer have a null terminated string, just an array ofchar, so passing it to any function that expects a string would be an error. E.g.strlen, as the source parameter tostrcpy, as a...parameter toprintfwith a%sformat specifier, etc.
What is the best way to integrate C with JAVA for Blackberry app? In core java, we can use JNI for integration. But in Blackberry app ? Thanks in advance.
You can't integrate C, as RIM does not expose any API for the platform. Since BlackBerry use a j2me-compliant JVM, JNI is not exposed. Prior answer is partially correct - you may write code that uses only the J2ME API, but you can also use RIM's own Java API for better/more advanced features and functionality.
code: ``` char *m[10]; char * s; int lcounter=0; int sd=0; char mem_buf [ 500 ]; while ( fgets ( mem_buf, sizeof mem_buf, infile ) != NULL ) { m[lcounter] =(char *) malloc(10*sizeof(char)); item = strtok(mem_buf,delims); m[lcounter]=item; printf("\n value inside==== :%s:",m[lcounter]); lcounter=lcounter+1; } for(i=0;i<lcounter;i++) { printf("\n value outside==== :%s:",m[sd]); sd++; } ``` input: ``` goo| bbb| ccc| ``` When I execute this am getting below output: ``` value inside==== : goo value inside==== : bbb value inside==== : ccc value outside====:ccc value outside====:ccc value outside====:ccc ``` But I need like: ``` value outside====:goo value outside====:bbb value outside====:ccc ```
Usestrcpyif you want it to last outside of the loop.strtokmay reuse the same pointer.
can someone explain to me the difference between Vector and Linked List ADT in a c programming language context. Thanks.
Well, in C, there are no "vector" and "list" data types available to you directly like in C++ std library. But in terms of "abstract data type", a vector is usually considered to represent contiguous storage, and a linked list is considered to be represented by individual cells linked together. Vectors provide fast constant time random-access read and write operations, but inserting and deleting vector elements take linear time. Lists have linear lookup performance to find an element to read and write, but given an element location, have constant time insertion and deletion. You can also add items to the start and to the end of a list in constant time (if the ADT implementation caches the location of the last element in the list).
Is there a standard library or commonly used library that can be used for calculating SHA-512 hashes on Linux? I'm looking for a C or C++ library.
Have you checkedOpenSSL. I myself have not used it but documentation says it supports it. Here is list offew more implementations. Example code ``` md = EVP_get_digestbyname("sha512"); EVP_MD_CTX_init(&mdctx); EVP_DigestInit_ex(&mdctx, md, NULL); EVP_DigestUpdate(&mdctx, mess1, strlen(mess1)); EVP_DigestUpdate(&mdctx, mess2, strlen(mess2)); EVP_DigestFinal_ex(&mdctx, md_value, &md_len); EVP_MD_CTX_cleanup(&mdctx); ```
I know that on your hard drive, if you delete a file, the data is not (instantly) gone. The data is still there until it is overwritten. I was wondering if a similar concept existed in memory. Say I allocate 256 bytes for a string, is that string still floating in memory somewhere after Ifree()it until it is overwritten?
Your analogy is correct. The data in memory doesn't disappear or anything like that; the values may indeed still be there after afree(), though attempting to read from freed memory is undefined behaviour.
These obnoxious warnings are on-by-default in current gcc, and I can't find which option is needed to disable them. They're generating warning-spam and preventing compiling with-Werrorin code where the behavior gcc warns about is intentional (and comes from general-purpose macros that could not easily avoid generating such constants).
After digging through the GCC source code, I found that the warnings you've described are part of the-Woverflowoption. So just turn off that warning. By the way, this comment is in the code for the warning: Both C and C++ require a diagnostic for a floating constant outside the range of representable values of its type... We also give a warning if the value underflows.
Hey, I am wondering how void pointers is applied in the real world in terms of making a software more secure, more flexible. For example, I know that void pointers, what pointer it will cast to is hidden to outside, which will make a software more secure. Are there other reasons why you would use void pointers?
Void pointers don't make the software any more secure. The reason to use void* in c is a form of polymorphism - if you don't know what type the data will be you can pass a void* In C++ there is less need to use void* and the language prevents some of the C uses
When I compile and run this code (it's part of a much larger program), Linux gets halfway through thewhileloop, then simply stops working. The code below printstime: 0and then hangs, doing nothing else until I suspend the process. Why on earth would it printtime: 0but not the following line of sanity check? ``` while (i < 5) { printf("time: %d\n",elapsedTime); printf("sanity check"); foo(); i++; } ```
Output usually is buffered and only written after a flush or newline. In ``` printf("sanity check"); ``` there is no newline, so if you run in an endless loop after this, you won't see it. Replace it with ``` printf("sanity check\n"); ``` or ``` printf("sanity check"); fflush(stdout); ``` and you'll see it.
In C, are the following equivalent: long int x = 3L;(notice theL) and long int x = 3 They seem to be the same. In case they are, which one should be used? Should theLbe specified explicitly? If they are different, what is the difference?
3.14Lis along doubleliteral, while3.14is adoubleliteral. It won't make much difference in this case, since both are being used to initialize a long int. The result will be 3. EDIT: Ok,3Lis alongliteral, while3is anintliteral. It still won't make much difference, since theintwill be "promoted" to a long. The result will be the same in both cases. EDIT 2: One place it might make a difference is something like this: ``` printf("%ld\n", 123); ``` This is undefined behavior, since the format string specifies alongand only anintis being passed. This would be correct: ``` printf("%ld\n", 123L); ```
``` char copy, array[20] printf("enter ..."): scanf("%s", array); if (strlen(array) > 20 ) { strcpy(copy, array....); ``` what would I need to do to make it only grab the first 20 character if the input is more then 20 character long
``` char array[20+1]; scanf("%20s", array); ``` Problem solved.
I'm trying to find the find the relative merits of 2 small functions in C. One that adds by loop, one that adds by explicit variables. The functions are irrelevant themselves, but I'd like someone to teach me how to count cycles so as to compare the algorithms. So f1 will take 10 cycles, while f2 will take 8. That's the kind of reasoning I would like to do. No performance measurements (e.g.gprofexperiments) at this point, just good old instruction counting. Is there a good way to do this? Are there tools? Documentation? I'm writing C, compiling withgccon an x86 architecture.
http://icl.cs.utk.edu/papi/ PAPI_get_real_cyc(3) - return the total number of cycles since some arbitrary starting point
This question already has answers here:Closed12 years ago. Possible Duplicate:How do free and malloc work in C? How does free know how many bytes of memory to be free'd when called in a program?
This is implementation specific, but whenmallocis called, the size of the allocated memory is kept somewhere (usually offset from the pointer itself). Whenfreeis called, it will use that stored size. This is exactly why you should only ever callfreeon a pointer that was returned bymalloc.
I'm wondering if there would be any merit in trying to code astrlenfunction to find the\0sequence in parallel. If so, what should such a function take into account? Thanks.
strlen()is sequential by spirit - one step beyond the null-terminator is undefined behavior and the null-terminator can be anywhere - the first character or the one millionth character, so you have to scan sequentially.
hi every one i want to ask that i want to compare two time values in c how can i do it time is in form ``` Sat Feb 19 12:53:39 2011 ``` thanks
You need to parse the human readable form viastrptime()and convert to atime_t-- which is (unsigned) integer seconds since the epoch of Jan 1, 1970. As that is a number, usual comparison operators apply.
How to implement Server Name Indication(SNI) on OpenSSL in C or C++? Are there any real world examples available?
On the client side, you useSSL_set_tlsext_host_name(ssl, servername)before initiating the SSL connection. On the server side, it's a little more complicated: Set up an additionalSSL_CTX()for each different certificate;Add a servername callback to eachSSL_CTX()usingSSL_CTX_set_tlsext_servername_callback();In the callback, retrieve the client-supplied servername withSSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name). Figure out the rightSSL_CTXto go with that host name, then switch theSSLobject to thatSSL_CTXwithSSL_set_SSL_CTX(). Thes_client.cands_server.cfiles in theapps/directory of the OpenSSL source distribution implement this functionality, so they're a good resource to see how it should be done.
I came across this question: "Given an integer, write a program that converts the given number to a number (in base 10). The given number could be in any base, but the base is unknown." Provide an algorithm Thanks in advance.
Usestrtolto convert from whatever base to your computer's native integer format. Then useitoato convert to a base 10 representation.
I am learning C language and I have some question as follows (sorry if these are silly ones) I am using Dev-C++ 4.9.9.2 to run some examples: ``` int m=3, n=4, k = 2; (1) printf("%d", k<m<n); => this one prints 1 (2) printf("%d", k>m>n); => this one prints 0 (3) printf("%d", m<n>k); => this one prints 0 ``` As the book says "A zero value stands for false and any other value stands for true." So, why the statement (3) prints 0 (false). I thought it should be 1, or what am i missing here? Can anyone give me a clear explanation, please? Thanks a lot.
According to C's precedence rules,m<n>kgets interpreted as(m<n)>k(your other examples follow the same form).m<nis true, so that evaluates to 1. Then the statement is actually1>kwhich is false, thus 0.
I am reading a C book. In the Arithmetic Expression section, they say: "Division typically uses more resources.  To avoid division, we multiply rather than divide. For example, we multiply by 0.5 rather than divide by 2.0." Why Division typically uses more resources?. Can anyone give me a detail explanation, please? Thanks a lot.
Binary Multiplication is simple using the peasant algorithm - you basically shift, then sum:http://en.wikipedia.org/wiki/Multiplication_algorithm#Peasant_or_binary_multiplication Binary Division is much harder, as it's a sequence of subtractions (like long division you may have done in school). The main algorithm class is called 'radix', which you can see an example of here:http://www.bearcave.com/software/divide.htm Remember though - measure first, then optimise. It's much easier to maintain code that matches the problem domain than code that is already optimised.
``` if ( (code == S || M || L || N || P || K ||R || C || U || W || O) ) { return T; } ``` Am I using the or operator correctly? I was intending for to be either one of those Character but I'm not sure if I am correctly using the operator
You would need to write: ``` code == 'S' || code == 'M' || code == 'L', etc. ``` But you could also do: ``` if(strchr("SMLNPKJRCUWO", code) != NULL) (or != 0, if you don't have NULL defined) {} ``` strchrsays "Is a char in a string? If so, give me a pointer to where it is. If not, then return NULL" (which is just a fancy way of saying zero). To use strchr, you will probably need to have#include <string.h>at the top of your source file.
I have a file that has float numbers separated by spaces and I want to open the file and use the numbers inside this file for mathematical operations (e.g. average), how would I do this using only the following: fopen, fscanf, fclose, printf/scanf, pointers, if/else/switch/loops? (No arrays). The number of values in the space delimited file can be any amount.
Without any knowledge of quantity, you will have to read numbers until you encounterend of file, e.g. use awhileconstruct. Keep a running count of the numbers read. Remember: Check the return value fromfscanf, which tells how many values read.Read one number per loop to get things working.Test forEOFafter reading from the file, as reading may trigger an EOF.Also check for other possible file errors.
What is more effective? Declaring array e.g. char buffer[4096] before loop and in each iteration clear its content by strlcpy or declare array inside the loop with initial "" value? ``` char buffer[4096] = ""; while(sth) { strlcpy(buffer,"",sizeof(buffer)); //some action; } ``` vs ``` while(sth) { char buffer[4096] = ""; //some action; } ```
There's probably no significant difference between the two. The only way to be sure would be to benchmark or look at the assembly generated by the compiler. The second example is clearer and would be preferred.
This pageprovides lots of libraries to handle item resizing and re-adjustment, but they're all for C++. Is there anything I can use for plain C?
You can call MoveWindow() do not only move but also resize Windows and Dialogs: http://msdn.microsoft.com/en-us/library/ms633534%28VS.85%29.aspx
is it possible to concatenate strings during preprocessing? I found this example ``` #define H "Hello " #define W "World!" #define HW H W printf(HW); // Prints "Hello World!" ``` However it does not work for me - prints out "Hello" when I usegcc -std=c99 UPDThis example looks like working now. However, is it a normal feature of c preprocessor?
Concatenation of adjacent string litterals isn't a feature of the preprocessor, it is a feature of the core languages (both C and C++). You could write: ``` printf("Hello " " world\n"); ```
Specifically, can it point to int/float etc.? What about objects like NSString and the like? Any examples will be greatly appreciated.
void*is such a pointer, that any pointer can be implicitly converted tovoid*. For example; ``` int* p = new int; void* pv = p; //OK; p = pv; //Error, the opposite conversion must be explicit in C++ (in C this is OK too) ``` Also note that pointers to const cannot be converted tovoid*without aconst_cast E.g. ``` const int * pc = new const int(4); void * pv = pc; //Error const void* pcv = pc; //OK ``` Hth.
I'm looking towards writing some applications with C and CGI, and now that I've implemented basic functions like URI encode/decode, HTML entities encode/decode, query/cookie parser, etc. I need to manage sessions. How should I do this? For example, how does PHP manage sessions?
Store the UserID and SessionID in a cookie, then store all other data on the server in a database. Do not encode user and session in the url as this leads to session-hijacking even if the user only wants to show some friend a link.
I am reading some text at this url: https://cs.senecac.on.ca/~btp100/pages/content/varia_p.html In the section 'Qualifiers', they say: "We can qualify the int type to be sure that it contains a minimum number of bits" .... A short contains at least 16 bits: .... I don't understand this, what does "qualify the int type" mean and why "A short contains at least 16 bits". Can anybody elaborate on this please? Thanks all.
Qualifier is an extra name given to either variables or functions , showing an extra quality or extra meaning for that variable or function. like Dr in Dr Arun Kumar Qualifiers for variables are (TYPE qualifiers):signed,unsigned,long,short,long long,const,volatile,static,auto,extern,register Qualifiers for functions are:static,extern,inline
In the code below, I have saved the values 1 - 9 in an Excel file and I want to insert an "a" between "4" and "5". I have set the pointer to position 7 but it is still inserting it at the end. Please help me understand this. ``` FILE *ExcelFile = fopen("testdata.csv","a"); if (ExcelFile == NULL) return -1; fprintf(ExcelFile,"1 2 3 4 5 6 7 8 9"); fseek (ExcelFile, 7, SEEK_SET ); //printf("pos is %ld bytes\n", pos); fprintf(ExcelFile,"a"); fclose(ExcelFile); ```
The reason this does not work is because you are opening the file for appending (the "a" flag in the fopen call). Whenever you write to the file the data you write will always be appended. If your file does not exists before opening, usefopen("testdata.csv","w")instead.
Is it possible to replace BuildAll of Eclipse CDT by a Makefile? I mean I have a Makefile in C and I would buildall from this file. I build a Target in Eclipse to compile but I would use the Ctrl+B to buildall. My environment is Eclipse-Cdt.
There is no problem in creating a makefile that would invoke other make files. But achieving interaction between Eclipse and the makefile would be extremely hard.
Is there a way to check which libraries is a running process using? To be more specific, if a program loads some shared libraries usingdlopen, then readelf or ldd is not going to show it. Is it possible at all to get that information from a running process? If yes, how?
Other people are on the right track. Here are a couple ways. ``` cat /proc/NNNN/maps | awk '{print $6}' | grep '\.so' | sort | uniq ``` Or, with strace: ``` strace CMD.... 2>&1 | grep -E '^open(at)?\(.*\.so' ``` Both of these assume that shared libraries have ".so" somewhere in their paths, but you can modify that. The first one gives fairly pretty output as just a list of libraries, one per line. The second one will keep on listing libraries as they are opened, so that's nice. And of courselsof... ``` lsof -p NNNN | awk '{print $9}' | grep '\.so' ```
hi every kindly tell me how to display pointer position for eg fpos_t pos; (fgetpos(fp, &pos) how to disply pos value thanks
To do this portably you're not supposed to try and display that pos value. Try using ftell() instead. ``` long pos; pos = ftell(fp); printf("pos is %ld bytes\n", pos); ```
I useopendir()andreaddir()to display the file names in a directory. But they are disordered. How can I sort them? The language is C.
Maybe you could use scandir() instead of opendir and readdir? ``` #include <stdio.h> #include <stdlib.h> #include <dirent.h> int main(void) { struct dirent **namelist; int n; n = scandir(".", &namelist, 0, alphasort); if (n < 0) perror("scandir"); else { while (n--) { printf("%s\n", namelist[n]->d_name); free(namelist[n]); } free(namelist); } } ```
my team and I are working in a project based on the drone Parrot API. We are trying to find an api to write a small program which can scan the wireless network and selects the drone ESSID. Our main language is C but Java is also appreciated. I tried to look if exist any API for the iwlist/iwconfig command but i did not find anything. Can someone help me plz? Any example (code sample) will also be appreciated. Gracias
With newer kernels the framework for managing wireless cards is callednl80211. It's netlink based, so you can uselibnlto issue commands and parse answers. More information: https://wireless.wiki.kernel.org/en/developers/documentation/nl80211 Currentlyiwis the command line utility that utilizes nl80211, so you can list available hardware, scan, etc: https://wireless.wiki.kernel.org/en/users/documentation/iw Its source code is easy to study and reuse in your own project, just check out their git repo.
I am using a custom user space environment that has barely no OS support: only one char device, mass storage interface and a single network socket. To provide C programming to this platform, I need a libc. Is there any libc project that is configurable enough so that I can map low-level IO to the small API I have access to ? AFAIK glibc and uclibc are expecting linux syscalls, so I can't use them (without trying to emulate linux syscalls, which is something I prefer to avoid).
There are several different libc's to choose from, but all will need some work to integrate into your system. uClibc has alistof other C libraries. The most interesting ones on that list are probablydietlibcnewlibFreeDOShas aLIBCEGLIBCmight be simpler to port than the "standard" glibc.
Are socketsprogramming language independent? Can I keep the server written in Java and client written in C?
Absolutely. Otherwise it would be pretty hard to write a web browser and a web server, just as an example... Of course, the data youcommunicateover the socket may be easier to read with one language than another - for example if you use Java'sDataOutputStream, that's going to be easier to manage with Java at the other end to read the data. But you stillcouldread that data, as the format is well documented. If you put absolutely platform-specific data across the network though, that makes things harder - it would be tricky to use an object serialized with Java'sObjectOutputStreamfrom a non-Java platform, for example. But at the raw sockets level, there's no concept of which programming language the source happened to be written in.
I am making a program in c that can produce another c code. How to, using the first program, compile and run the second program immediately after the second program has been produced?
One way is to usedsystem()call ... ``` system("cl generated_file.c -o gen_exe") ; system("./gen.exe"); ``` or ``` system("gcc generated_file.c -o gen.exe"); system("./gen.exe"); ``` Or you use a simle batch or script or makefile to do this
What conditions are necessary for open() to fail, with UDP sockets, on Windows? Thanks.
The only time I've seen that happen is when I didn't initialize WinSock with WSAStartup().
Does C (or any other low-level language, for that matter) even have source, or is the compiler the part that "does all the work", including parsing? If so, couldn't different compilers have different C dialects? Where does the stdlib factor into this? I would really like to know how this works.
The C language is not a piece of software but adefined standard, so one wouldn't say that it's open-source, but rather that it's an open standard. There are a gazillion different compilers for C however, and many of those are indeed open-source. The most notable example isGCC's C compiler, which is all under theGNU General Public License (GPL), an open-source license. There are more options.Watcomis open-source, for instance. There is no shortage of open-source C compilers, but without a doubt the most widespread one, at least in the non-Windows world, is GCC. For Windows, your best bet is probably Watcom or GCC by usingCygwinorMinGW.
The official documentation here only lists the minimum required version for a very small number of attributes: http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html Is there a complete list of which version each attribute was added in? Even better would be a list that also shows which ones are compatible with pcc and tcc.
For gcc versions: http://www.ohse.de/uwe/articles/gcc-attributes.html For pcc: http://pcc.ludd.ltu.se/fisheye/browse/~raw,r=HEAD/pcc/pcc/cc/ccom/gcc_compat.c For tcc: ??
I'm using a resource editor to design my UI (resedit), however I cant find an option to tell it to keep the width of a control (listview) the same as its parent control (dialog) - so that when I resize the dialog also the listview resizes. Can I do this through the resource file or do I need to call some C/C++ function?
This is not automatic, you need to write some code to do it. Respond to the WM_SIZE message for the parent, determine how much the size changed, and resize the child by the same amount. Functions that can resize a window are MoveWindow, SetWindowPos, and DeferWindowPos. DeferWindowPos is a lot more complicated but will result in a nicer update if there are many windows moving or changing size at the same time.
I am referring to this answerHow to enable visual styles without a manifest Doing what that answers says creates a.manifestand visual styles are enabled. However I don't want the manifest to be bounded with my .exe - I am delivering only my executable and would like everything bundled in there. Is there a way to enable visual styles without manifest or maybe through embedding the manifest inside the executable itself?
Use mt.exe to embed the manifest into the executable as a resource. This is a standard part of the build since VS2005, use a project template if you have trouble setting it up properly.
I wonder if this would be a bad idea to makes such defines in C: ``` #define and && #define or || #define not ! ```
It would definitely be a bad idea to do this yourself. If you really want names likeandinstead of symbols like&&, you can include the<iso646.h>C Standard Library header, which defines several named operators, including the three you mention. In C++, the alternative representations (likeandandor) are operators built into the language, so you don't need to include any header to use them, and it isn't possible to define them as macros (a macro name must be an identifier, and the alternative representations are operators, not identifiers, even during preprocessing).
Efficient and O(n) code for this in c?? I know that solution of O(n*n) ``` stringCompare(str1, str2){ int freq1[100] = {0}, i; int freq2[100] = {0}; for(i=0; i<=strlen(str1); i++){ freq1[str1[i]]+ = 1; } for(i=0; i<=strlen(str2); i++) { freq2[str2[i]]+ = 1; } for(i=0;i<26;i++){ if(freq1[i]!=freq2[i]) return 0; return 1; ``` } ``` } ```
I modifiedMAK's pseudocode slightly so it only uses one frequency count array. A positive value in the final freq array means a char ins1is not ins2. A negative value signals extra chars ins2. ``` function same(s1,s2): freq=array of zeros for i=0 to length of s1: freq[s1[i]]+=1 for i=0 to length of s2: freq[s2[i]]-=1 for i=0 to alphabet_size: if not freq[i]=0 return "no" return "yes" ```
Suppose you have a function: ``` void fun(int *a, int *b); ``` Which way you would prefer to send the arguments? (1.) ``` int x, y; fun(&x, &y); ``` (2.) ``` int *x, *y; fun(x, y); ``` What are the problems with other way or both are same and their behavior will also be the same?
Usually you use the former if you want the variables on the stack, and the latter if you allocate memory for them on the heap. The stack is typically faster, whereas the heap is typically bigger. So in general, you use the first pattern quite often, and only use the latter when dealing with giant arrays or very large objects.
``` *(*(p+a)+b) ``` If a*size is added to an address (p), then why is b*size added to *(p+a)? *(p+a) appears to be the value at that location and adding b*size to it would change its value, not the address. However, based on what I read this is meant to be added to an address.
Given your expression, and assuming you're talking about C, p must be a pointer to a pointer. What happens is: ``` char ** p; int a = 2; int b = 4; (p+a) // adds 2 * sizeof(char *) *(p+a) // evaluates to a char * char * c = *(p+a) (c+b) // adds 4 * sizeof(char) *(c+b) // evaluates to a char ```
I was unsure whether to ask here or in superuser, but this site seemed more appropriate I'm looking for documentation/analysis on Clang specifically for these two areas: comparison of warnings provided by Clang vs. GCCI'm specifically looking for the amount of checking that Clang is doing in comparison to GCChttp://gcc.gnu.org/onlinedocs/gcc/Warning-Options.htmldescription of the--analyzeflag, what exactly does it check?
I did ask on the Clang mailing list and the documentation is non-existent at this point. You can follow this thread for more information:http://lists.cs.uiuc.edu/pipermail/cfe-dev/2011-March/013655.html
When creating aGtkNotebookin Glade, I get 3 tabs by default. How can I add another tab?
Right-click on one of the tabs, and click "Insert page before" or "Insert page after".
I'm looking for a good open source C/C++ regular expression library that has full Unicode support. I'm using this in an environment where the library might get ASCII, UTF-8, or UTF-16. If it gets UTF-16 it might or might not have the necessary quoting characters (FF FE) or (FE FF). I've looked around and there don't seem to be any options other than PCRE. My second problem is that I'm currently using flex to build some HUGE regular expressions. Ideally I would have a flex-like lexical expression generator that also handles Unicode. Any suggestions?
Have you consideredICU? It has matureregular expression support.
So I am pondering this question (this is a homework/exam review problem): Write down an equivalent expression fora[j++] = ++i;without using pre/post increment operators. If no such expression can be provided explain why. I was able to come up with the following: a[j] = i+=1;j+=1; I can't think of a way to increment j within a[] as a post increment other than usingj+=1;afterwards which I believe would lead to the answer of no such expression can be provided (because its two lines of code instead of one) and just explain that you can't post increment without the post increment operator. Am I missing anything or am I correct? I just wanted to double check. Thanks in advance. EDIT: Thanks to @James McNellis he provided a way usinga[(j+=1)-1] = (i+=1);
This is horrible and ugly, but here it is anyway: ``` a[(j += 1) - 1] = (i += 1); ```
I want to write a C program to display the file last modification time in microsecond or millisecond. How could I do? Could you give me a help? Thanks very much.
Thestat()function is used. In sufficiently recent versions of glibc,st_mtim(note: no trailinge) is a field of typestruct timespecthat holds the file modification time: ``` struct stat st; if (stat(filename, &st)) { perror(filename); } else { printf("%s: mtime = %lld.%.9ld\n", filename, (long long)st.st_mtim.tv_sec, st.st_mtim.tv_nsec); } ``` You should check for the presence ofst_mtiminstruct statin your build system, and be ready to fall back tost_mtime(which has typetime_t, and only 1 second resolution) if it is not present.
I'm new in C/C++ and I need to retrieve images from a shared folder place in another computer for processing. How can I do that? Can someone please provide me some guidance or sample codes on how to do it? Besides, can I also get the list of files in a folder in the shared folder?
Open a file for reading: ``` char* filename = "//machine/shared/image.jpg"; FILE* f = fopen(filename, "r"); ``` Read a directory: ``` struct dirent* ent; char* path = "//machine/shared"; DIR* d = opendir(path); while((ent = readdir(d)) != NULL) { printf("%s\n", ent->d_name); } ```
How to catch click on balloon tray icon? What message it sends to window? Scenario: The application shows balloon and user clicks on some point in the balloon space or to close button on balloon form.
The message you get sent is always the one you passed to Shell_NotifyIcon. The lParam of the message will be NIN_BALLOONUSERCLICK. You don't get to find out whether the user clicks the close button or not.
I am trying to find a good way to handle multicast group members.Keep track when someone joins/leaves the group. Language is C.
Unless you are implementing an IP multicast router you should add a subscription management protocol above multicast in the application layer.