question
stringlengths
25
894
answer
stringlengths
4
863
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he...
Here is a compilation: C TerminologyC ReferenceBasic CcdeclcprogrammingCLC-wiki<---got fromanon ymousto addA to Z(C++ but there are helpful common terms)A to Z(C/C++/C#)wiki-bookBig tutorialTips and Tricks
the code snippet below takes an an integer (i.e. number) from the user and prints the count of all the digits in that number, however, if I enter a number contains 0 somewhere, it gets out of the while loop immediately (because of the while loop condition). I tried fixing this bug but I could not. Could you please hel...
Perhaps it should be: ``` while (number != 0) ``` You don't seem to need the other stuff (remet al) unless you plan on doing more than just counting digits. And at any rate, you probably wantrem = number % 10;before the division.
I have ``` MessageBoxW(hwnd, L"Καλημέρα", L"Τέστ", MB_OK|MB_APPLMODAL); ``` That works, but now how can I pass a value that's in my variable "message" and "caption"? I cannot use L anymore because it is a variable, ``` MessageBoxW(hwnd, Lmessage, Lcaption, MB_OK|MB_APPLMODAL); //doesn't work ``` Is there a L(messa...
If your variables are of typeWCHAR*, they are naturally in the long string format. You may pass them toMessageBoxWas they are. ``` MessageBoxW(hwnd, message, caption, MB_OK|MB_APPLMODAL); ```
The problem is - I'm trying to sort several lines using qsort, everything works in the outfile. Unfortunatelyvalgrindgives me errors about not freeing some memory blocks. At first I thought - I need tofree(lines)but it is already there. What am I missing? ``` qsort(lines, linenumber, sizeof(char*), compare_string); ...
How did you assign memory to lines? If it is a two-dimensional array then you have to malloc each line separately in a for loop. Do something like this- ``` for(counter=Max_lines;counter>0;counter--){ free(lines[counter]); } ```
``` unsigned long long i = 1000; ``` Shouldn't now0.1*ibe automatically converted into a double? Why then isn't the compiler warning me when I pass0.1*iinto a function parameter that expects anunsigned long long? I thought the compiler was supposed to warn of such potential loss of precision. I have my compiler, Cla...
Yes, operation on an integer and a floating-point number results in a floating-point number. But when you pass that result (which is a double) to a function expecting an unsigned long long, then there'll be an implicit cast taking place automatically and the result will be truncated to unsigned long long. Why didn't ...
I use to define multi-line stuff, something like a help message, like this: ``` #define HELP_MSG "blabla\r\n" \ "Some other line" ``` Is there a way that I can avoid putting "\r\n" here, since I already have it defined in multiple line.
No,\is merely used as a linecontinuationmarker. If you need a line break, you need to include it explicitly in the string, as you're doing.
I have the following code. Why its undefined to derefrence union pointers in the following way ? ``` extern union MyUn *P1; extern union MyUn *P2; extern void myfunc(void) { *P1 = *P2; } ```
If you haven't also defined the union in this source file, the compiler doesn't know how much to copy. What is the size of the union?
Why if I callRSA_size()on an RSA object do I obtain a value less than the return value ofi2d_RSAPublicKey(the size of the public key) called on the same RSA object?
Becausei2d_RSAPublicKeygives you a PKCS#1 encoded version of the key, including public exponent and DER elements. RSA_size()gives you just the size in bytes of the pure modulus (which is also the size of any unencoded signature or ciphertext for that key).
What does the C standard (preferably C89,90) say about: ``` int a,b; a = 4; b = (a += 1); ``` ? I have tested it and the result isb=5, which is what I expect. I just want to be reassured by the Standard. The same applies to analogous operators like*=,/=,&=, etc. I know that=is sure to return the value of the left h...
Assignment operators do not "return" a value: they yield one, or as the standard puts it, have one. The value is of the left operand, although it won't be an lvalue. Here's the excerpt: (3.3.16) An assignment expression has the value of the left operand after the assignment, but is not an lvalue. All of= *= /= %...
I found this function definition ``` void *func(void *param) { } ``` Actually, I have a certain confusion regarding this function definition. What does void * mean in the return type of the function as well as the argument. I am a beginner in C. So please don't mind. Thank you ``` void *func(void *param) { int s...
void *means it's a pointer of no specific type, think of it as a generic pointer, unlike sayint *an int pointer. You can cast it into a different type if need be (for instance if you are going to do pointer arithmetic with the pointer). You might find this SO question of use:Concept of void pointer in C programming
Does ~0 mean its flipping 000000000 to 1111111111? ``` printf("Check: %i", ~0); ``` The printf results to -1, which is why I am confused.Does -1 essentially mean the same thing as 11111111111111111 bits?
Does ~0 mean its flipping 000000000 to 1111111111? Yes, it does. Does -1 essentially mean the same thing as 11111111111111111 bits? In2s complementrepresentation, it does.
Why do I get such a big int? ``` int ans = 1 << 45; printf("Check: %d", ans); return 0; ``` Check: 1858443624
This is undefined behavior in C. Anything can happen, including stuff like processor exceptions, or unpredictable changes in other parts of the program (which can happen as a side effect of aggressive compiler optimizations). 6.5.7/3 [...] If the value of the right operand is negative or is greater than or equal to t...
Consider: ``` void foo1(char **p) { *p++; } void foo2(char **p) { *p += 1; } ``` and ``` char *s = "abcd"; char *a = s; foo1(&a); printf("%s", a); //abcd ``` but if I usefoo2()instead of: ``` char *a = s; foo2(&a); printf("%s", a); //bcd ``` Can someone explain it?
The key is the precedence of the+=and the++operator. The++has a higher precedence than the+=(in fact, assignment operators have the second lowest precedence in C), so the operation ``` *p++ ``` means dereference the pointer, then increment the pointeritselfby 1 (as usually, according to the rules of pointer arithmet...
Is it possible to declare a variable in C, the name of which is given by the user at runtime? If yes, then how?
No, this is not possible: variable names do not survive the compilation step, becoming addresses and offsets "baked into" the compiled binary code. It is, however, possible to declare a variable the name of which is given by the developer at compile-time by using a-Dor a comparable option of your C compiler.
I need to sort a point array (a point is a struct with twofloattypes - one forxand one fory) in a special fashion. The points have to be sorted so when they are traversed, they form a zig-zag pattern starting at thetop leftmost point, moving to thetop rightmost point, then down to thesecond leftmost point, to theseco...
I'd use qsort() with a custom compare() function that as @stefan noted, sorts descending by y then alternates (max/min) for x.
the code snippet below takes an an integer (i.e. number) from the user and prints the count of all the digits in that number, however, if I enter a number contains 0 somewhere, it gets out of the while loop immediately (because of the while loop condition). I tried fixing this bug but I could not. Could you please hel...
Perhaps it should be: ``` while (number != 0) ``` You don't seem to need the other stuff (remet al) unless you plan on doing more than just counting digits. And at any rate, you probably wantrem = number % 10;before the division.
I have ``` MessageBoxW(hwnd, L"Καλημέρα", L"Τέστ", MB_OK|MB_APPLMODAL); ``` That works, but now how can I pass a value that's in my variable "message" and "caption"? I cannot use L anymore because it is a variable, ``` MessageBoxW(hwnd, Lmessage, Lcaption, MB_OK|MB_APPLMODAL); //doesn't work ``` Is there a L(messa...
If your variables are of typeWCHAR*, they are naturally in the long string format. You may pass them toMessageBoxWas they are. ``` MessageBoxW(hwnd, message, caption, MB_OK|MB_APPLMODAL); ```
The problem is - I'm trying to sort several lines using qsort, everything works in the outfile. Unfortunatelyvalgrindgives me errors about not freeing some memory blocks. At first I thought - I need tofree(lines)but it is already there. What am I missing? ``` qsort(lines, linenumber, sizeof(char*), compare_string); ...
How did you assign memory to lines? If it is a two-dimensional array then you have to malloc each line separately in a for loop. Do something like this- ``` for(counter=Max_lines;counter>0;counter--){ free(lines[counter]); } ```
``` unsigned long long i = 1000; ``` Shouldn't now0.1*ibe automatically converted into a double? Why then isn't the compiler warning me when I pass0.1*iinto a function parameter that expects anunsigned long long? I thought the compiler was supposed to warn of such potential loss of precision. I have my compiler, Cla...
Yes, operation on an integer and a floating-point number results in a floating-point number. But when you pass that result (which is a double) to a function expecting an unsigned long long, then there'll be an implicit cast taking place automatically and the result will be truncated to unsigned long long. Why didn't ...
I use to define multi-line stuff, something like a help message, like this: ``` #define HELP_MSG "blabla\r\n" \ "Some other line" ``` Is there a way that I can avoid putting "\r\n" here, since I already have it defined in multiple line.
No,\is merely used as a linecontinuationmarker. If you need a line break, you need to include it explicitly in the string, as you're doing.
I have the following code. Why its undefined to derefrence union pointers in the following way ? ``` extern union MyUn *P1; extern union MyUn *P2; extern void myfunc(void) { *P1 = *P2; } ```
If you haven't also defined the union in this source file, the compiler doesn't know how much to copy. What is the size of the union?
Why if I callRSA_size()on an RSA object do I obtain a value less than the return value ofi2d_RSAPublicKey(the size of the public key) called on the same RSA object?
Becausei2d_RSAPublicKeygives you a PKCS#1 encoded version of the key, including public exponent and DER elements. RSA_size()gives you just the size in bytes of the pure modulus (which is also the size of any unencoded signature or ciphertext for that key).
What does the C standard (preferably C89,90) say about: ``` int a,b; a = 4; b = (a += 1); ``` ? I have tested it and the result isb=5, which is what I expect. I just want to be reassured by the Standard. The same applies to analogous operators like*=,/=,&=, etc. I know that=is sure to return the value of the left h...
Assignment operators do not "return" a value: they yield one, or as the standard puts it, have one. The value is of the left operand, although it won't be an lvalue. Here's the excerpt: (3.3.16) An assignment expression has the value of the left operand after the assignment, but is not an lvalue. All of= *= /= %...
I found this function definition ``` void *func(void *param) { } ``` Actually, I have a certain confusion regarding this function definition. What does void * mean in the return type of the function as well as the argument. I am a beginner in C. So please don't mind. Thank you ``` void *func(void *param) { int s...
void *means it's a pointer of no specific type, think of it as a generic pointer, unlike sayint *an int pointer. You can cast it into a different type if need be (for instance if you are going to do pointer arithmetic with the pointer). You might find this SO question of use:Concept of void pointer in C programming
Does ~0 mean its flipping 000000000 to 1111111111? ``` printf("Check: %i", ~0); ``` The printf results to -1, which is why I am confused.Does -1 essentially mean the same thing as 11111111111111111 bits?
Does ~0 mean its flipping 000000000 to 1111111111? Yes, it does. Does -1 essentially mean the same thing as 11111111111111111 bits? In2s complementrepresentation, it does.
Why do I get such a big int? ``` int ans = 1 << 45; printf("Check: %d", ans); return 0; ``` Check: 1858443624
This is undefined behavior in C. Anything can happen, including stuff like processor exceptions, or unpredictable changes in other parts of the program (which can happen as a side effect of aggressive compiler optimizations). 6.5.7/3 [...] If the value of the right operand is negative or is greater than or equal to t...
Consider: ``` void foo1(char **p) { *p++; } void foo2(char **p) { *p += 1; } ``` and ``` char *s = "abcd"; char *a = s; foo1(&a); printf("%s", a); //abcd ``` but if I usefoo2()instead of: ``` char *a = s; foo2(&a); printf("%s", a); //bcd ``` Can someone explain it?
The key is the precedence of the+=and the++operator. The++has a higher precedence than the+=(in fact, assignment operators have the second lowest precedence in C), so the operation ``` *p++ ``` means dereference the pointer, then increment the pointeritselfby 1 (as usually, according to the rules of pointer arithmet...
Is it possible to declare a variable in C, the name of which is given by the user at runtime? If yes, then how?
No, this is not possible: variable names do not survive the compilation step, becoming addresses and offsets "baked into" the compiled binary code. It is, however, possible to declare a variable the name of which is given by the developer at compile-time by using a-Dor a comparable option of your C compiler.
I need to sort a point array (a point is a struct with twofloattypes - one forxand one fory) in a special fashion. The points have to be sorted so when they are traversed, they form a zig-zag pattern starting at thetop leftmost point, moving to thetop rightmost point, then down to thesecond leftmost point, to theseco...
I'd use qsort() with a custom compare() function that as @stefan noted, sorts descending by y then alternates (max/min) for x.
What does the C standard (preferably C89,90) say about: ``` int a,b; a = 4; b = (a += 1); ``` ? I have tested it and the result isb=5, which is what I expect. I just want to be reassured by the Standard. The same applies to analogous operators like*=,/=,&=, etc. I know that=is sure to return the value of the left h...
Assignment operators do not "return" a value: they yield one, or as the standard puts it, have one. The value is of the left operand, although it won't be an lvalue. Here's the excerpt: (3.3.16) An assignment expression has the value of the left operand after the assignment, but is not an lvalue. All of= *= /= %...
I found this function definition ``` void *func(void *param) { } ``` Actually, I have a certain confusion regarding this function definition. What does void * mean in the return type of the function as well as the argument. I am a beginner in C. So please don't mind. Thank you ``` void *func(void *param) { int s...
void *means it's a pointer of no specific type, think of it as a generic pointer, unlike sayint *an int pointer. You can cast it into a different type if need be (for instance if you are going to do pointer arithmetic with the pointer). You might find this SO question of use:Concept of void pointer in C programming
Does ~0 mean its flipping 000000000 to 1111111111? ``` printf("Check: %i", ~0); ``` The printf results to -1, which is why I am confused.Does -1 essentially mean the same thing as 11111111111111111 bits?
Does ~0 mean its flipping 000000000 to 1111111111? Yes, it does. Does -1 essentially mean the same thing as 11111111111111111 bits? In2s complementrepresentation, it does.
Why do I get such a big int? ``` int ans = 1 << 45; printf("Check: %d", ans); return 0; ``` Check: 1858443624
This is undefined behavior in C. Anything can happen, including stuff like processor exceptions, or unpredictable changes in other parts of the program (which can happen as a side effect of aggressive compiler optimizations). 6.5.7/3 [...] If the value of the right operand is negative or is greater than or equal to t...
Consider: ``` void foo1(char **p) { *p++; } void foo2(char **p) { *p += 1; } ``` and ``` char *s = "abcd"; char *a = s; foo1(&a); printf("%s", a); //abcd ``` but if I usefoo2()instead of: ``` char *a = s; foo2(&a); printf("%s", a); //bcd ``` Can someone explain it?
The key is the precedence of the+=and the++operator. The++has a higher precedence than the+=(in fact, assignment operators have the second lowest precedence in C), so the operation ``` *p++ ``` means dereference the pointer, then increment the pointeritselfby 1 (as usually, according to the rules of pointer arithmet...
Is it possible to declare a variable in C, the name of which is given by the user at runtime? If yes, then how?
No, this is not possible: variable names do not survive the compilation step, becoming addresses and offsets "baked into" the compiled binary code. It is, however, possible to declare a variable the name of which is given by the developer at compile-time by using a-Dor a comparable option of your C compiler.
I need to sort a point array (a point is a struct with twofloattypes - one forxand one fory) in a special fashion. The points have to be sorted so when they are traversed, they form a zig-zag pattern starting at thetop leftmost point, moving to thetop rightmost point, then down to thesecond leftmost point, to theseco...
I'd use qsort() with a custom compare() function that as @stefan noted, sorts descending by y then alternates (max/min) for x.
What happens when breaking in nested loops? suppose the following code: ``` for(int x = 0; x < 10; x++) { do { if(x == 4) break; x++; } while(x != 1); } ``` Which loop will exit on encountering the break statement, the for loop or the do while loop ?
Thebreakalways breaks the innermost loop. 6.8.6.3A break statement terminates execution of the smallest enclosing switch oriterationstatement. If you want to break out of both loops, use a label after theforand jump withgoto.
So, I have four integers and I need to find out the lowest two out of those four. What would be the most efficient way of doing so in C (or any other language)? Edit:I need a fixed implementation, for the sake of efficiency as this is a very critical operation that is going to be performed thousands of times.
Here's an efficient implementation usingsorting networks: ``` inline void Sort2(int *p0, int *p1) { if (*p0 > *p1) { const int temp = *p0; *p0 = *p1; *p1 = temp; } } inline void Sort4(int *p0, int *p1, int *p2, int *p3) { Sort2(p0, p1); Sort2(p2, p3); Sort2(p0, p2); ...
I am implemented some thing in C function and i want to call the another c method using NSTimer method but the selector not worked and also self method not called. How can do that? ``` [NSTimer scheduledTimerWithTimeInterval:900 target:self selector:@selector(prepareToUploadLog()) userInfo:nil repeats:YES]; ``` void...
According to the documentation ofscheduledTimerWithTimeInterval: aSelector:The message to send to target when the timer fires. The selectormust correspond to a methodthat returns void and takes a single argument. The timer passes itself as the argument to this method. So you can't use a C function and have to add an...
Whenever I read about program execution in C, it speaks very less about the function execution. I am still trying to find out what happens to a function when the program starts executing it from the time it is been called from another function to the time it returns? How do the function arguments get stored in memory?...
That's unspecified; it's up to the implementation. As pointed out by Keith Thompson, it doesn't even have to tell you how it works. :) Some implementations will put all the arguments on the stack, some will use registers, and many use a mix (the firstnarguments passed in registers, any more and they go on the stack)....
I'm having trouble with the algorithm: what I need to do is multiply the elements of the array via recursion. Here's what I've got so far: ``` #include <stdio.h> void vector(int vec[],int tam) { // gets a simple array int i; for (i=0; i<tam; i++) { printf("Ingrese un numero: "); ...
base case isif (pos == tam) return 1; You also have to make sure array is not empty
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen...
While @SamGrondahl is on the right track, unfortunately, if you enter a negative number it gives unexpected results. This should work properly with negative numbers: ``` int sumdigits(int number) { int sign = number < 0 ? -1 : 1; number = sign * number; // abs the number if (number < 10) return ...
I'm learning about the C language. I have this code, more can be provided if needed: ``` int result = 0; int mask1 = 0x0000ffff; mask1 = mask1 >> 28; ``` This when I use gdb and print/x mask1, I get0x0, which is correct. Then why does: ``` int result = 0; int mask1 = 0xffffffff; mask1 = mask1 >> 28; print 0xffffff...
The behaviour of right shifts on negative integers is implementation defined. One common behaviour is arithmetic shifting, which does sign-extension. The advantage of that is that right shifting is then also division by a power of two (rounded to negative infinity), like it is for positive numbers.
Does anyone know what this means param[in] timer /*The zero-based index of the timer. *param[in] delay_us /*The time to delay for, in microseconds. */void Timer_Wait(const uint8_t timer, const uint32_t delay_us); and this is the address mapping Timer 0 0x80000000 Timer 1 0x80000100 I would just li...
Zero based means if you have three timers, they are numbered 0,1,2 as opposed to 1,2,3.
Like this: ``` input: 10010011 (10->01->00->11) output: 11000110 (11->00->01->10) input: 11010001 (11->01->00->01) output: 01000111 (01->00->01->11) ``` Anyone has any ideas about that?
Fewer operations thanlserni'salgorithm: ``` uint32_t reverseByTwo(uint32_t value) { value = ((value & 0x03030303) << 2) | ((value >> 2) & 0x03030303); // swap adjacent pairs value = ((value & 0x0F0F0F0F) << 4) | ((value >> 4) & 0x0F0F0F0F); // swap nibbles value = ((value & 0x00FF00FF) << 8) | ((value >> ...
Here is my code , I want to print 15 and 12 but due to instance member hiding the local value of a is getting printed twice. ``` #include <stdio.h> int a = 12; int main() { int a = 15; printf("Inside a's main local a = : %d\n",a)...
Use theexternspecifier in a new compound statement. This way: ``` #include <stdio.h> int a = 12; int main(void) { int a = 15; printf("Inside a's main local a = : %d\n", a); { extern int a; printf("In a global a = %d\n", a); } ...
I would like to know what happens when there are more initializers than array size, e.g. : ``` int t[3] = { 1, 2, 3, 4 }; ``` Of course, my compiler warns it. I expected undefined behavior, but I didn't find any clause about it in C11 standard. So, did I miss something ?
The code is ill-formed in both C and C++. C++11 §8.5.1[dcl.init.aggr]/6 states: Aninitializer-listis ill-formed if the number ofinitializer-clausesexceeds the number of members or elements to initialize. C11 §6.7.9/2 states: No initializer shall attempt to provide a value for an object not contained within the ent...
I just wrote a program in c language which uses command line arguments and i tried to print the first argument. when i execute program with following command ``` ./a.out $23 ``` and try to print the first argument using the below code ``` printf("%s", argv[1]); ``` the output is just ``` 3 ``` Am i missing somet...
You need to escape the$character. Try this: ``` ./a.out \$23 ```
``` struct s1 { int a; int b; }; struct s2 { int a; int b; }; struct s2 test(void) { struct s1 s = { 1, 2 }; return s; // incompatible types } ``` In the above code, can I returnswithout creating a newstruct s2variable and populating it withs's values? It is guaranteed thatstruct s1will always be identical t...
You can't return the struct directly, but you can avoid creating a separate variable in your source code by using acompound literal, which is a feature of C99. ``` struct s2 test(void) { struct s1 s = { 1, 2 }; return (struct s2){s.a, s.b}; } ```
When I used openssl APIs to validate server certificate (self signed), I got following error : error 19 at 1 depth lookup:self signed certificate in certificate chain As per openssldocumentation, this error (19) is "X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: self signed certificate in certificate chain - the certifi...
You have a certificate which is self-signed, so it'snon-trustedby default, that's why OpenSSL complains. This warning is actually a good thing, because this scenario might also rise due to aman-in-the-middle attack. To solve this, you'll need to install it as a trusted server. If it's signed by a non-trusted CA, you'...
i call a python script from a C script using a system call (i know this isn't best practice, but for now it does the intended job). while the C is running at the command line, i can cancel it using Ctrl-C. when i am running the python script, when the code follows into particular if clauses, i would like to cancel t...
``` import signal import os os.kill(0, signal.CTRL_C_EVENT) ```
Can any one suggest any encryption algorithm which interop between c and c# means encrypt in c language and decrypt in c# & vice versa
Use something like AES available under System.Security.Cryptography. You can find an example of using it under C# here -Using AES encryption in C# When deriving IV and SALT you might find this utility class useful:http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes.aspx I cannot ...
The function RSA_public_encrypt requires that the variable where encrypted text will be saved, should have a length of RSA_size(*rsa) bytes. Now, I need to know how big could be the text to encrypt, because if I crypt a little string (for example "asdasd"), there's no problem, but if I try with a bigger string, just a...
Assuming you're talking aboutRSA_public_encrypt(), the docs state it pretty clearly: flen must be less than RSA_size(rsa) - 11 for the PKCS #1 v1.5 based padding modes, less than RSA_size(rsa) - 41 for RSA_PKCS1_OAEP_PADDING and exactly RSA_size(rsa) for RSA_NO_PADDING. Remember that these are block cryptos, in the ...
i have defined a value using ``` extern char WEBSRV_ADMIN_ID[31]; char WEBSRV_ADMIN_ID[31]= "admin"; ``` then i want to use the username in a char statement into sql as ``` const char *pSQL[1]; pSQL[1] = "update websrv_config set admin_id='" + WEBSRV_ADMIN_ID + "'"; ``` but it seems that there is an error ``...
in C++, usestd::string. It handles+will work as you want it to. In C, allocate a buffer big enough to contain the whole query and fill it part-by-part usingstrncat.
size_tis declared asunsigned intso it can't represent negative value.So there isssize_twhich is thesignedtype ofsize_tright?Here's my problem: ``` #include <stdio.h> #include <sys/types.h> int main(){ size_t a = -25; ssize_t b = -30; printf("%zu\n%zu\n", a, b); return 0; } ``` why i got: ``` 18446744073709551591 1...
In the first case you're assigning to an unsigned type -a. In the second case you're using the wrong format specifier. The second specifier should be%zdinstead of%zu.
When should a programmer use.binfiles? (practical examples). Is it popular (or accepted) to save different data types in one file? When iterating over the data in a file (that has several data types), the program must know the exact length of every data type, and I find that limiting.
If you mean for some idealized general purpose application data, text files are often preferred because they provide transparency to the user, and might also make it easier to (for instance) move the data to a different application and avoid lock-in. Binary files are mostly used for performance and compactness reason...
I am creating 1d arrays B and T of n size and a 2D array A of nxn size,where n has been computed earlier. But the program crashes after Pause, what am i possibly doing wrong?? ``` float *B = malloc(sizeof(int) * (n)); float *T = malloc(sizeof(int) * (n)); system("PAUSE"); float **A; ...
a 2D array A of nxn size You're passing the wrong types tosizeof. You should be usingsizeof(float)andsizeof(float *). But the more serious (and insidious) problem is: ``` A[j]=(float*)malloc(sizeof(int)*(j)); ^ ``` You wantninstead ofj.
As per my knowledge, enum can be used like ``` typedef enum { true, false, undefined }FLAGS; ``` trueandfalsecan be used like ``` int a = 1; if(a == true) .... else if(a == false) .... ``` Coming to my issue, I came across a enum usage like, ``` FLAGS Options[] = {true, undefined}; ``` i.e arr...
Anenumis just like an integer type, with the added bonus of having a bunch of named literals. There's nothing stopping you from declaring an array of enumerated values, it's basically just an array of integers.
I am writing a code like this usingsnprintf(): ``` char myId[10] = "id123"; char duplicateId[10] = ""; snprintf(duplicateId, 10, myId); ``` As you can see, I am not specifying the format specifier%sexplicitly. Do I need to explicitly specify the format specifier in the abovesnprintf()statement like thissnprintf(d...
No, you don't have to, technically. But it's better practice to do so, because without a constant format string, your format string remains modifiable thus your code will be more prone to format string attacks. Ah, and also usesizeof(duplicateId)instead of a constant10- also for security reasons (in order to avoid fu...
I can't think of any practical use of multiple asterisks in the function call: ``` void foo(int a, char b) { } int main(void) { (**************foo)(45, 'c'); //or with pointer to function: void (*ptr)(int, char) = foo; (******ptr)(32, 'a'); } ``` Why is this thing allowed both in C and C++?
One of the standard conversions, in both C and C++, is the function-to-pointer conversion; when a function name appears in an expression, it can be converted into a pointer to that function. So: foois equivalent to&foo*foois equivalent to*(&foo), orfoo**foois eqivalent to**(&foo), or*foo, orfoo and so on. This mean...
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he...
ISAPI on Windows/IIS. NSAPI is supported by a number of vendors.
I was able to do custom painting on the tooltip control, by disable its visual style. I am curious that if we can make the tooltip control to be "Layered" (i.e transparent). I tried to add WS_EX_LAYERED style on it and call ``` SetLayeredWindowAttributes(hwndTooltip, 0, 50, LWA_ALPHA); ``` But it doesn't become tr...
Cannot be done. Reference and explanation: http://tech.dir.groups.yahoo.com/group/wtl/message/14214
Here is my code , I want to print 15 and 12 but due to instance member hiding the local value of a is getting printed twice. ``` #include <stdio.h> int a = 12; int main() { int a = 15; printf("Inside a's main local a = : %d\n",a)...
Use theexternspecifier in a new compound statement. This way: ``` #include <stdio.h> int a = 12; int main(void) { int a = 15; printf("Inside a's main local a = : %d\n", a); { extern int a; printf("In a global a = %d\n", a); } ...
I would like to know what happens when there are more initializers than array size, e.g. : ``` int t[3] = { 1, 2, 3, 4 }; ``` Of course, my compiler warns it. I expected undefined behavior, but I didn't find any clause about it in C11 standard. So, did I miss something ?
The code is ill-formed in both C and C++. C++11 §8.5.1[dcl.init.aggr]/6 states: Aninitializer-listis ill-formed if the number ofinitializer-clausesexceeds the number of members or elements to initialize. C11 §6.7.9/2 states: No initializer shall attempt to provide a value for an object not contained within the ent...
I just wrote a program in c language which uses command line arguments and i tried to print the first argument. when i execute program with following command ``` ./a.out $23 ``` and try to print the first argument using the below code ``` printf("%s", argv[1]); ``` the output is just ``` 3 ``` Am i missing somet...
You need to escape the$character. Try this: ``` ./a.out \$23 ```
``` struct s1 { int a; int b; }; struct s2 { int a; int b; }; struct s2 test(void) { struct s1 s = { 1, 2 }; return s; // incompatible types } ``` In the above code, can I returnswithout creating a newstruct s2variable and populating it withs's values? It is guaranteed thatstruct s1will always be identical t...
You can't return the struct directly, but you can avoid creating a separate variable in your source code by using acompound literal, which is a feature of C99. ``` struct s2 test(void) { struct s1 s = { 1, 2 }; return (struct s2){s.a, s.b}; } ```
When I used openssl APIs to validate server certificate (self signed), I got following error : error 19 at 1 depth lookup:self signed certificate in certificate chain As per openssldocumentation, this error (19) is "X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: self signed certificate in certificate chain - the certifi...
You have a certificate which is self-signed, so it'snon-trustedby default, that's why OpenSSL complains. This warning is actually a good thing, because this scenario might also rise due to aman-in-the-middle attack. To solve this, you'll need to install it as a trusted server. If it's signed by a non-trusted CA, you'...
i call a python script from a C script using a system call (i know this isn't best practice, but for now it does the intended job). while the C is running at the command line, i can cancel it using Ctrl-C. when i am running the python script, when the code follows into particular if clauses, i would like to cancel t...
``` import signal import os os.kill(0, signal.CTRL_C_EVENT) ```
Can any one suggest any encryption algorithm which interop between c and c# means encrypt in c language and decrypt in c# & vice versa
Use something like AES available under System.Security.Cryptography. You can find an example of using it under C# here -Using AES encryption in C# When deriving IV and SALT you might find this utility class useful:http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes.aspx I cannot ...
The function RSA_public_encrypt requires that the variable where encrypted text will be saved, should have a length of RSA_size(*rsa) bytes. Now, I need to know how big could be the text to encrypt, because if I crypt a little string (for example "asdasd"), there's no problem, but if I try with a bigger string, just a...
Assuming you're talking aboutRSA_public_encrypt(), the docs state it pretty clearly: flen must be less than RSA_size(rsa) - 11 for the PKCS #1 v1.5 based padding modes, less than RSA_size(rsa) - 41 for RSA_PKCS1_OAEP_PADDING and exactly RSA_size(rsa) for RSA_NO_PADDING. Remember that these are block cryptos, in the ...
i have defined a value using ``` extern char WEBSRV_ADMIN_ID[31]; char WEBSRV_ADMIN_ID[31]= "admin"; ``` then i want to use the username in a char statement into sql as ``` const char *pSQL[1]; pSQL[1] = "update websrv_config set admin_id='" + WEBSRV_ADMIN_ID + "'"; ``` but it seems that there is an error ``...
in C++, usestd::string. It handles+will work as you want it to. In C, allocate a buffer big enough to contain the whole query and fill it part-by-part usingstrncat.
size_tis declared asunsigned intso it can't represent negative value.So there isssize_twhich is thesignedtype ofsize_tright?Here's my problem: ``` #include <stdio.h> #include <sys/types.h> int main(){ size_t a = -25; ssize_t b = -30; printf("%zu\n%zu\n", a, b); return 0; } ``` why i got: ``` 18446744073709551591 1...
In the first case you're assigning to an unsigned type -a. In the second case you're using the wrong format specifier. The second specifier should be%zdinstead of%zu.
When should a programmer use.binfiles? (practical examples). Is it popular (or accepted) to save different data types in one file? When iterating over the data in a file (that has several data types), the program must know the exact length of every data type, and I find that limiting.
If you mean for some idealized general purpose application data, text files are often preferred because they provide transparency to the user, and might also make it easier to (for instance) move the data to a different application and avoid lock-in. Binary files are mostly used for performance and compactness reason...
I am creating 1d arrays B and T of n size and a 2D array A of nxn size,where n has been computed earlier. But the program crashes after Pause, what am i possibly doing wrong?? ``` float *B = malloc(sizeof(int) * (n)); float *T = malloc(sizeof(int) * (n)); system("PAUSE"); float **A; ...
a 2D array A of nxn size You're passing the wrong types tosizeof. You should be usingsizeof(float)andsizeof(float *). But the more serious (and insidious) problem is: ``` A[j]=(float*)malloc(sizeof(int)*(j)); ^ ``` You wantninstead ofj.
As per my knowledge, enum can be used like ``` typedef enum { true, false, undefined }FLAGS; ``` trueandfalsecan be used like ``` int a = 1; if(a == true) .... else if(a == false) .... ``` Coming to my issue, I came across a enum usage like, ``` FLAGS Options[] = {true, undefined}; ``` i.e arr...
Anenumis just like an integer type, with the added bonus of having a bunch of named literals. There's nothing stopping you from declaring an array of enumerated values, it's basically just an array of integers.
I am writing a code like this usingsnprintf(): ``` char myId[10] = "id123"; char duplicateId[10] = ""; snprintf(duplicateId, 10, myId); ``` As you can see, I am not specifying the format specifier%sexplicitly. Do I need to explicitly specify the format specifier in the abovesnprintf()statement like thissnprintf(d...
No, you don't have to, technically. But it's better practice to do so, because without a constant format string, your format string remains modifiable thus your code will be more prone to format string attacks. Ah, and also usesizeof(duplicateId)instead of a constant10- also for security reasons (in order to avoid fu...
I am reviewing some C code, but having a hard time understanding what Callback is exactly. Does anyone know what this means? I'm guessing that it is defining "Callback and x to be both a void *? ``` typedef void (*Callback)(bool x); ```
It makes a new type nameCallback. EveryCallbackwill be a pointer to a function taking abooland returningvoid. In effectCallbackwill be an alias for that real type. So when you say: ``` Callback ptr = some_fun; ``` You're making a function pointer that points atsome_fun. Function pointers are typically passed to othe...
Has any C guru ever implemented a Epoll Non-blocking selector in C that I can call from Java so I don't have to use Java's NIO Epoll implementation?
You can find epoll sample program written in C by me. I hope that will help youCould you recommend some guides about Epoll on Linux
So I am making my Hello world program, and it is like this: ``` #include "lib-includes/capi324v221.h" void CBOT_main(void) { LCD_open(); if (!LCD_OPEN) { while (true); // loop forever } else { LCD_printf("Hello, World!"); while(true); // loop forever } } ``` ...
First of all what are thosewhileloops doing there? My first reaction is to get rid of those. I have no personal experience with programming CEENBots\your IDE, but based on the error description in the question title I suspect your source file has a!in it which messes up the build process (it complains about aWorld!.m...
When compiling something as simple as ``` inline int test() { return 3; } int main() { test(); return 0; } ``` withgcc -c test.c, everything goes fine. If the-ansikeyword added,gcc -ansi -c test.c, one gets the error message ``` test.c:1:8: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘int’ ```...
You need to use: ``` gcc -std=c99 -c test.c ``` The-ansiflag specifies c90: The -ansi option is equivalent to -std=c90. ANSI C was effectively the 1990 version of C, which didn't include theinlinekeyword.
Since the system/usr/share/zoneinfodatabase is updated fairly frequently, I would like to be able to load it (and reload it) dynamically in a very long running C++ program. Now I know the standard library will use this database, but I doubt it offers dynamic reloading of it (or at least I couldn't find anything about...
I'm an idiot. IANA which provides the zoneinfo database, also providesa libraryfor working with it. Funnily enough I discovered this by reading the postgresql source code. I'm not sure if this is sufficient, but it's public domain licensed so at the least I can pull it into my code and bend it to my needs.
This question already has answers here:Closed11 years ago. Possible Duplicate:Bidirectional (or reverse) debugging I've looked up the Omniscient Debugger (http://www.lambdacs.com/debugger/ODBDescription.html), but it's specific to Java. Is there any debugger with this same functionality for native apps, i.e., C/C++?...
In addition to the stack traces to examine past instructions already mentioned here on x86 targets newer gdb also supportsrecorded program execution and stepping backwardswhich should come pretty close to what you are looking for.
Can somebody tell me a workaround for#pragma oncedirective support for various compilers? I want to use in my header something like: ``` #if _MSC_VER > ... || __GNUC__ > ... || ... #pragma once #endif ``` Maybe it already exists in boost sources or in your code?
Useinclude guards: ``` #ifndef MY_HEADER_H #define MY_HEADER_H // ... #endif // MY_HEADER_H ``` Sometimes you'll see these combined with the use of#pragma once: ``` #pragma once #ifndef MY_HEADER_H #define MY_HEADER_H // ... #endif // MY_HEADER_H ``` #pragma onceis prettywidely supported.
Assuming I have a function that fills a buffer with binary data easily, how can I make that function return said buffer for further use? The way I am currently doing it is by having it write the buffer (based off the content-length field from recv) write a temp file, then returning the name of that temp file so I can...
You can use the same API as socket recv. Caller provides a buffer and max len, and function returns actual received length. http://linux.die.net/man/2/recv
I would like to write a function such asputchar, with the help ofwritefunction. ``` #include <unistd.h> ssize_t f(int fd, int c) { return write(fd, &c, 1); } ``` But I think there could be an endianness problem here, isn't it ? So should I usesizeof (int)? I am a bit confused, I don't know how to process (need ...
Yes, there is potentially an endianness problem here. The cure is to passcas anunsigned charrather than as anint. ``` ssize_t f(int fd, unsigned char c) { return write(fd, &c, 1); } ``` The<stdio.h>routines work withints mostly for historical reasons. They are very old, and contain many interface design decisi...
The below code snippet is used to convert a string to lower case. ``` int main() { unsigned char s[] = "AbS.d_"; tolower(s); printf("%s\n", s); return 0; } ``` I am getting theoutputas: ``` AbS.d_ ``` Why the string is not being converted?
tolowertakes int and return lowered int. This should work: ``` int i=0; for(i=0; s[i]; i++) { s[i]=tolower(s[i]); } ```
I have an open device descriptor, where I don't know the device name and the options passed to open(...). I want to open a new device descriptor with the same options passed to open. ``` int newFd = copy(referenceFd); ``` Where copy would do the job. dup() is certainly the wrong choice as a further ioctl() on newFd...
You can probably do it with a series offcntlcalls: F_GETFD- Get the file descriptor flags defined in that are associated with the file descriptor fildes.F_GETFL- Get the file status flags and file access modes, defined in , for the file description associated with fildes. I linked the SUSv4 page above; you might al...
I wrote the following program to understand the behavior of EOF: ``` #include<stdio.h> int main () char c = 0; printf("Enter some chars, EOF stops printing:"); while ((c == getc(stdin)) != EOF) printf("c = %c, (int) c = %d\n", c, (int) c); return 0; } ``` However, if I input something s...
You've got a==instead of a=so you never store whatevergetcreturns: ``` while ((c == getc(stdin)) != EOF) { ^^ ``` And of coursecshould beint, notchar.
I need a random function for number betwen 11 and 99. I wrote this: ``` int random (void){ int i2; i2=11+(rand()%99); return i2; } ``` but the numbers go over 99. Why?
Because ifrand()return98, then98 % 99is98and98 + 11 > 99. To do this, you need ``` i2 = 11 + ( rand() % 89 ); ``` rand() % 89will give you numbers[0, 88], so+11would become[11, 99]. By the way, don't forget tosrand( time( NULL ) ), otherwise it will (most probably) generate the same sequence of (pseudo) random n...
I am currently working on a embedded C project and I "inherited" some old code containing statements such as: ``` rxStruct = rxStruct; ``` where rxStruct is a variable. What could be the use of such statements?
Without further information, one use of such a statement is to prevent an unused parameter compiler warning ifrxStructis passed in as a parameter and then otherwise not used.
I have an image. I have to find the height of a particular object in it. If we directly take the pixel length it will not give the exact height.How to approach this problem?
After you calibrated your camera, you will have a transformation from image plane to world coordinates. Using this information you can predict the height of the object you are looking for, of course in this step you somehow need to identify the object that you are interested in. Generally speaking, this question is t...
The following program crashes when I try to print the value ofv. I'm trying to understand why. Any suggestions? ``` #include <stdio.h> int main() { int v[5000000]; printf("\n\nv = %p", v); return 0; } ``` EDIT: the program does not segfault if instead of allocating 5000000 elements I allocate 500000 o...
Congrats, you havestack overflow:) Find a way to increase the size of the stack or just allocate the array dynamically: ``` int* v = malloc( 5000000 * sizeof *v); /* do something */ free( v ); ```
These directories on my platform (Ubuntu) is required to be passed to clang so it can parse code that includes libc headers properly: /usr/include/x86_64-linux-gnu /usr/lib/gcc/x86_64-linux-gnu/4.6/include /usr/lib/gcc/x86_64-linux-gnu/4.6/include-fixed What is the simplest way to find the location of this directo...
llvm/tools/clang/lib/Driver/ToolChains.cppsearches for GCC installations, with various hard-coded paths for different platforms. On Gentoo, Debian, and Ubuntu, the distribution-providedclangsource patches this file to look in distribution-specific locations (e.g.gentoo/sys-devel/clang/files/clang-3.1-gentoo-runtime-g...
How do i read a 64-bit unsigned integer from a file? I've got it stored as actual binary data, not a string representation.
How is it encoded? Binary numbers usually differ inendianness. If you want to assume it's the same as the current host's endianness, you can usefreaddirectly. Otherwise, you'll need to byte-swap it after reading. For bonus points, assuming you have control over how it's serialized, you could indicate the endiannes...
I am reading through "The C Programming Language", and working through all the exercises with CodeBlocks. But I cannot get my character counter to work, despite copying it directly from the book. The code looks like this: ``` #include <stdio.h> main(){ long nc; nc = 0; while (getchar() != EOF) ...
This line: ``` while (getchar() != EOF) ``` means that it keeps reading until the end of input —notuntil the end of a line. (EOFis a special constant meaning "end of file".) You need to end input (probably with Ctrl-D or with Ctrl-Z) to see the total number of characters that were input.
Can somebody tell me a workaround for#pragma oncedirective support for various compilers? I want to use in my header something like: ``` #if _MSC_VER > ... || __GNUC__ > ... || ... #pragma once #endif ``` Maybe it already exists in boost sources or in your code?
Useinclude guards: ``` #ifndef MY_HEADER_H #define MY_HEADER_H // ... #endif // MY_HEADER_H ``` Sometimes you'll see these combined with the use of#pragma once: ``` #pragma once #ifndef MY_HEADER_H #define MY_HEADER_H // ... #endif // MY_HEADER_H ``` #pragma onceis prettywidely supported.
Assuming I have a function that fills a buffer with binary data easily, how can I make that function return said buffer for further use? The way I am currently doing it is by having it write the buffer (based off the content-length field from recv) write a temp file, then returning the name of that temp file so I can...
You can use the same API as socket recv. Caller provides a buffer and max len, and function returns actual received length. http://linux.die.net/man/2/recv
I would like to write a function such asputchar, with the help ofwritefunction. ``` #include <unistd.h> ssize_t f(int fd, int c) { return write(fd, &c, 1); } ``` But I think there could be an endianness problem here, isn't it ? So should I usesizeof (int)? I am a bit confused, I don't know how to process (need ...
Yes, there is potentially an endianness problem here. The cure is to passcas anunsigned charrather than as anint. ``` ssize_t f(int fd, unsigned char c) { return write(fd, &c, 1); } ``` The<stdio.h>routines work withints mostly for historical reasons. They are very old, and contain many interface design decisi...
The below code snippet is used to convert a string to lower case. ``` int main() { unsigned char s[] = "AbS.d_"; tolower(s); printf("%s\n", s); return 0; } ``` I am getting theoutputas: ``` AbS.d_ ``` Why the string is not being converted?
tolowertakes int and return lowered int. This should work: ``` int i=0; for(i=0; s[i]; i++) { s[i]=tolower(s[i]); } ```
I have an open device descriptor, where I don't know the device name and the options passed to open(...). I want to open a new device descriptor with the same options passed to open. ``` int newFd = copy(referenceFd); ``` Where copy would do the job. dup() is certainly the wrong choice as a further ioctl() on newFd...
You can probably do it with a series offcntlcalls: F_GETFD- Get the file descriptor flags defined in that are associated with the file descriptor fildes.F_GETFL- Get the file status flags and file access modes, defined in , for the file description associated with fildes. I linked the SUSv4 page above; you might al...