question
stringlengths
25
894
answer
stringlengths
4
863
I am trying to recompile a gtk application and instead of launching theg:helpbrowser, I want to launch the default browser and html file on my file system. I modified the source code to: ``` #define APP_HELP "file://usr/local/share/doc/APP/APP.html" /*ret = gtk_show_uri (gtk_widget_get_screen (GTK_WIDGET (paren...
Closing the question after the useful remark from Kwariz: ``` because the URI should begin with file:///usr/.... ```
If a zval is a callable object, how can I run it in my extension c code ? or how to convert azvalto azend_fcall_info
after search for thezend_is_callableand dive into the php src code, I know how to call a callable zval: ``` zval ret; zval* params[] = { param }; // param is zval* too if (SUCCESS == call_user_function(CG(function_table), NULL, callable, &retval, 1, params TSRMLS_CC)) { // callable is a zval* // you can do ...
``` /* squeeze: delete all c from s */ void squeeze(char s[], int c) { int i, j; for (i = j = 0; s[i] != '\0'; i++) if (s[i] != c) s[j++] = s[i]; s[j] = '\0'; } int main(void) { squeeze("squeeze", 'z'); return 0; } ``` I compiled it with gcc and ran it, and got a segmentation fault as a result. A...
Your example shows that you're trying to applysqueeze()to a string literal ("squueze"). This is not correct, since string literals are not always modifiable so it's invalid to try to modify them. You need to call it with a character array: ``` #include <stdlib.h> int main(void) { char test[] = "squeeze"; squ...
I am puzzled at what my program outputs: ``` #include<stdio.h> int main() { if(11==011) printf("True"); else printf("False"); } ``` The output is"False".
In C a number beginning with0is consideredoctal, i.e. base 8. So011is actually9. 6.4.4.1A decimal constant begins with a nonzero digit and consists of a sequence of decimal digits.An octal constant consists of the prefix 0optionally followed by a sequence of the digits 0 through 7 only.
i have a file hello.txt and a pointer *i pointing to the file, i have opened the file using c open(*i) function. i want to get the size of file using getpagesize(2) to read the content of the file and further write that content to a destination file. so getting the size of the file i required to now how big is the fil...
If you are using theopensystem function to open the file, you should look into thefstatfunction to get the size: ``` int fd = open(...); struct stat st; fstat(fd, &st); printf("File size: %ld bytes\n", st.st_size); ```
``` char ch[2]; ch[0] = 'h'; ch[1] = '\0'; ``` or can i just do ``` char ch[1]; ch[0] = 'h'; ``` in which '\0' would already be implied? The reason why i'm doing it this way is because my program has a loop in it in which i would constantly be changing this character and concatenating it to a longer string.
Assigning justch[0]will not assign zero to thech[1]. You can initialize both characters in the array with a string literal in a single line, like this: ``` char ch[2] = "h"; ``` This will put'h'intoch[0], and a terminating zero intoch[1].
I need to store random numbers between 500 and 600 to an array using a pointer and then print out those numbers. I get a segmentation error...core dump, I don't really understand what that means. The error happens after the printf statement ("%15d\n", aPtr[i]); ``` int main(){ int size; int j, i; int te...
i <= size;should bei < size; If you have an array of 50 items, the valid indices are [0,49].
I'm learning iOS but have an issue extracting data from a multidimensionalNSMutableArray, I've looked at various solutions but have not yet found one.. I have anNSMutableArraylike ``` { "service_0" = { "name" = "name1"; "description" = "description1"; }; "service_2" = { "name" = "name2"; "descripti...
Assuming that is an array of dictionaries, unlike in the question... ``` NSArray *newArray = [oldArray valueForKeypath:@"name"]; ``` You can make it mutable usingmutableCopy, if you wish.
I need to create an array that's size is determined by user input, and then has pointers to said array. All the array will hold is random numbers between 500-600. I can't seem to use malloc correctly. I am still new to C, so help is appreciated. ``` int main(){ int size; printf("Enter size of array"); ...
You only need: ``` int *aptr = malloc(sizeof(int) * size); ``` and then you can access it just like an array. ``` aptr[0] = 123; ```
I'm new to C and I'm wondering what the difference is between these two: ``` char* name; struct book *abook; ``` I know the struct constructs a book, but with the char how come the*is place before the variable name?
TYPE * variableName, TYPE* variableName and TYPE *variableName are all syntactically the same. It's a matter of notation how you use them. Personally I prefer the last form. It's simply because the star operator works on the token to the right of it. In a declaration like ``` TYPE* foo, bar; ``` only foo is a point...
I am very new to C and I am wondering if this is allowed and if so, how do I do it correctly? This code gives me tons of compiler errors. I am trying to create a structure with 3 character arrays (initialized to null characters'\0') and initialize one of these structs with the nameS. ``` struct Structure{ char ...
No. That is not allowed. Types (yourstruct Structureis a type) in C have no value. What has values are objects. You can create an object of a struture type and initialize all of it,recursively if needed, to 0 with what I call theuniversal zero initializer. ``` struct Structure { char array1[3]; char array2[...
I am trying to recompile a gtk application and instead of launching theg:helpbrowser, I want to launch the default browser and html file on my file system. I modified the source code to: ``` #define APP_HELP "file://usr/local/share/doc/APP/APP.html" /*ret = gtk_show_uri (gtk_widget_get_screen (GTK_WIDGET (paren...
Closing the question after the useful remark from Kwariz: ``` because the URI should begin with file:///usr/.... ```
If a zval is a callable object, how can I run it in my extension c code ? or how to convert azvalto azend_fcall_info
after search for thezend_is_callableand dive into the php src code, I know how to call a callable zval: ``` zval ret; zval* params[] = { param }; // param is zval* too if (SUCCESS == call_user_function(CG(function_table), NULL, callable, &retval, 1, params TSRMLS_CC)) { // callable is a zval* // you can do ...
``` /* squeeze: delete all c from s */ void squeeze(char s[], int c) { int i, j; for (i = j = 0; s[i] != '\0'; i++) if (s[i] != c) s[j++] = s[i]; s[j] = '\0'; } int main(void) { squeeze("squeeze", 'z'); return 0; } ``` I compiled it with gcc and ran it, and got a segmentation fault as a result. A...
Your example shows that you're trying to applysqueeze()to a string literal ("squueze"). This is not correct, since string literals are not always modifiable so it's invalid to try to modify them. You need to call it with a character array: ``` #include <stdlib.h> int main(void) { char test[] = "squeeze"; squ...
I am puzzled at what my program outputs: ``` #include<stdio.h> int main() { if(11==011) printf("True"); else printf("False"); } ``` The output is"False".
In C a number beginning with0is consideredoctal, i.e. base 8. So011is actually9. 6.4.4.1A decimal constant begins with a nonzero digit and consists of a sequence of decimal digits.An octal constant consists of the prefix 0optionally followed by a sequence of the digits 0 through 7 only.
I need to calculate the additive inverse of a large (BIGNUM) prime in C. So, basically, i need to multiply by -1. Is there an easy way to do this that i've missed? I don't see any functions in the documentation. All i've come up with is this, which i think is rather ugly: ``` //bigprime = my big prime inverse = B...
The simpler solution is to just subtract the prime from zero. ``` inverse = BN_new(); nil = BN_new(); BN_zero(nil); BN_sub(inverse,nil,bigprime); ``` should do it.
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...
I suppose the standard answer to this question issqlite.
The following code segfaults whenever I use short-circuit-or (|), and compiles flawlessly when not short-circuited (||)? Compiled usinggcc -Wall ../IsNull/IsNull.c ../IsEmpty/IsEmpty.c *.c -o IsNullOrEmpty: ``` #include <stdbool.h> #include "../IsNull/IsNull.h" #include "../IsEmpty/IsEmpty.h" #include "IsNullOrEmp...
You should be using||(logicalor operator) instead of|(bitwiseor operator). The former short-circuits whilst the latter doesnot, hence the segmentation fault.
This question already has answers here:Closed10 years ago. Possible Duplicate:Is array name a pointer in C?C++ Static array vs. Dynamic array? I'm learning C and I'm confused at what the difference is between the following two arrays: ``` int a[10]; ``` and ``` int *b = (int *) malloc(10 * sizeof(int)); ``` Just...
``` int a[10]; ``` is allocated on stack and is de-allocated as soon as the scope ends. ``` int *b = (int *) malloc(10 * sizeof(int)); ``` is allocated on heap and is alive throughout the lifetime of the program unless it's explicitlyfreed.
This question already has answers here:Closed11 years ago. Possible Duplicate:What is the difference between char s[] and char *s in C? There's a program: ``` #include<stdio.h> int main() { char str[20] = "Hello"; char *const p=str; *p='M'; printf("%s\n", str); return 0; } ``` This prints Mell...
It's a contant pointer, exactly. You can't changewhere it points. You can changewhat it points. ``` const char *p; // a pointer to const char char * const p; // a const pointer to char const char * const p; //combined... ``` The easiest way to memorize the syntax is to not memorize it at all.Just read the declarati...
Can some one tell me how to check if there is any message in message queue. the message queue is implemented in C in linux based operating system. I just want to check if there is any message in the message queue at a particular time.
Just checking the amount (if any) of messages is done using the ``` msgctl() ``` function, and examining the msqid_ds structure on return, the msg_qnum in this structure is the amount of messages in the queue. Here is a link with an example:msgctl example, it does more then you want, but after the msgctl() call you ...
``` void pass_arr(int arr[]); void pass_arr_test() { int arr[5] = {1,2,3,4,5}; printf( "arr = %p\n" "&arr = %p\n\n", arr, &arr); pass_arr(arr); } void pass_arr(int arr[]) { printf( "passed arr = %p\n" "passed &arr = %p\n\n", arr, &arr); } ``` Output:arr = 0x28ccd0&arr ...
That's because in the functionarris actually a pointer, not an array. Taking the address of a pointer does not yield the same address, the way it does for an array.
I want toincludethe result of a macro expansion. It seemsincludeonly knows <> ""? This fails: ``` #define audio sinwave #ifdef audio #include audio".c" /*#include "sinwave.c"*/ #endif ``` But this works: ``` #ifdef audio if(i==0){set_audio((char *)audio);return;} #endif ```
You could do something like this: ``` #define audio audio #define FF(X) #X #define F(X) FF(X.c) #ifdef audio #include F(audio) #endif ``` that is you'd have to append the.cbefore you place everything into a string. The usual concatenation"audio" ".c" -> "audio.c"of adjacent strings happens in a later compilation p...
Using c: ``` char ptr[n]; free(ptr); ``` In my opinion: when "char ptr[n];" is used, the memory is allocated, and ptr is pointed to it, free(ptr) should work. And the program failed, why?(n == 5 e.g.) Any deep analysis?
Because you calledfreeon a variable not allocated withmalloc.This causesUndefined Behavior. Luckily for you it crashes and you can detect it, else it can crash at most awkward times. You callfreefor deallocating memory of heap allocated variables, What you have is an array on local storage(assuming it to be in a func...
I'm reading aboutTypedefon wikipedia. Example mentioned on that page is ``` typedef int km_per_hour ; typedef int points ; km_per_hour current_speed ; points high_score ; ... void congratulate(points your_score) { if (your_score > high_score) ... ``` Going further it says this which I'm not able to understand why?...
You cannot prependsignedorunsignedbefore atypedef'd type.signedandunsignedcan only modify basic integer types and do that directly. The compiler parsessignedorunsignedeither alone or nearchar,short,intandlong. In all other cases they are considered invalid/unexpected/misplaced. In that sense,signedandunsigneddon't w...
I am new to C.I have a code that reads first word from the line, Here is a piece of it: ``` scanf(Line, "%s", Word); printf("%s\n", Word); ``` This code reads and prints the first word in the line. However, I need to compare the first word of the line to another word. Any suggestions?
strcmp(str1,str2)Compares the C string str1 to the C string str2. This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached. Returns an integral value indicating...
using only bitwise operators(|, &, ~, ^, >>, <<), is it possible to replace the!=below? ``` // ... if(a != b){ // Some code } /// ... ``` this is mainly out of self interest, since I saw how to do it with==but not!=.
``` if(a ^ b) { //some code } ``` should work. You can also use your preferred method for==and add^ 0xFFFFFFFFbehind it (with the right amount of Fs to match the length of the datatype). This negates the value (same as!in front of it).
As a programmer of long standing, it's sobering to realise that even the humbleforloop is not fully comprehended. Why does the following program print a single1to the console? I fully expect the first loop to also produce a1! Compiled with-ansiswitch. ``` /* gcc installed version: 4:4.4.4-1ubuntu2 */ #include <stdio...
the first loop is equivalent to: ``` for(i=0; ; i++) { if( !((i<SIZE) && (a[i]!=0))) break; printf("%i\n",a[i]); } ```
So this is the scenario that I'm looking at: I have 3 libraries - A, B and C. Library A implements functionfoo()and exposes it as an API.Functionfoo()calls the POSIXwrite()call to write some data.Library B writes a wrapper to thewrite()glibc call using the linker -wrap option.Library C links to both A and B. Anywri...
IfAis linked with-wrap=write,foowill call the wrapper. If it's not, it won't. The same is true about calls towriteinC. There's no difference whatsoever betweenAandCas far as callingwriteis concerned.
I've got a question regarding writing applications for Windows. Can I use WinAPI and DWMApi (aero glass, ribbon, etc.) when programming in ANSI C? I'm looking at MSDN right now and they use c++.
The Windows API is a C API and can be used with any compiler that supports the 'standard' calling convention. Microsoft has made the strategic decision to put their own C compiler on life support, though, and you're stuck with C90 (with some specific extension) when using Visual Studio. You can use 3rd party compiler...
From definitiondouble strtod ( const char * str, char ** endptr ); C reference sites provide an example for that mighty function: ``` char szOrbits[] = "365.24 29.53"; char * pEnd; double d1, d2; d1 = strtod (szOrbits,&pEnd); d2 = strtod (pEnd,NULL); ``` Ifendptrshould be of typechar **why ischar *pEndused here ? A...
The type ofpEndischar *. The type of&pEndischar **. C passes arguments to functions by value, so to modify a pointer you need to pass a pointer to the pointer. You could define achar **directly but you would need to initialize it to achar *as the idea is thatstrtodis modifying achar *. Like: ``` char *q; char **p ...
``` void slice_first_char(char ** string) { *string = &(*string[1]); } int main(int argc, char * argv[]) { char * input = "abc"; input = &(input[1]); puts(input); // "bc" as expected. slice_first_char(&input); puts(input); // \372\277_\377 // What‘s going on? } ``` How can I...
You got the parentheses in ``` &(*string[1]); ``` wrong. I guess you meant ``` &((*string)[1]); ``` Your original version dereferences the pointer of the first element of thestringsarray, and then takes the address of that whereas you actually want to dereference the given pointer (because it just points to a sing...
So I want to toggle the most significant bit of my number. Here is an example: ``` x = 100101 then answer should be 00101 ``` I have a 64 bit machine and hence I am not expecting the answer to be100000..<51 0's>..100101One way I thought of was to count the number of bits in my number and then toggle the MSB, but not...
The cheat is to pawn it off to the compiler: There are instructions in most CPUs for doing work like this. The following should do what you want. ``` i ^ (1 << (sizeof i * CHAR_BIT - clz(i) - 1)) ``` This will translate into theCLZinstruction, which counts the leading zeros. For GCC, see:http://gcc.gnu.org/onlined...
As the title says, in my program I (after many procedures) get tokenized words. Unfortunately due to reversing them they hold punctuation characters at the beginning of a word eg. ,moose How to move that,from the beginning to the end -> moose, Up to now I've tried(ptrischar *): ``` temp = strdup(ptr); temp = &ptr[0...
Something like this: ``` void swap_last(char *str) { const size_t len = strlen(str); if(len > 1) { const char first = str[0]; memmove(str, str + 1, len - 1); str[len - 1] = first; } } ``` Note that the above assumesstrto be valid.
If we have to hold an address of any data type then we require a pointer of that data type. But a pointer is simply an address, and an address is alwaysinttype. Then why does the holding address of any data type require the pointer of that type?
There are several reasons: Not all addresses are created equal; in particular, in non Von Neuman (e.g.Harvard) architectures pointers to code memory (where you often store constants) and a pointers to data memory are different.You need to know the underlying type in order to perform your accesses correctly. For examp...
This question already has answers here:Closed11 years ago. Possible Duplicate:What is the difference between char s[] and char *s in C? There's a program: ``` #include<stdio.h> int main() { char str[20] = "Hello"; char *const p=str; *p='M'; printf("%s\n", str); return 0; } ``` This prints Mell...
It's a contant pointer, exactly. You can't changewhere it points. You can changewhat it points. ``` const char *p; // a pointer to const char char * const p; // a const pointer to char const char * const p; //combined... ``` The easiest way to memorize the syntax is to not memorize it at all.Just read the declarati...
Can some one tell me how to check if there is any message in message queue. the message queue is implemented in C in linux based operating system. I just want to check if there is any message in the message queue at a particular time.
Just checking the amount (if any) of messages is done using the ``` msgctl() ``` function, and examining the msqid_ds structure on return, the msg_qnum in this structure is the amount of messages in the queue. Here is a link with an example:msgctl example, it does more then you want, but after the msgctl() call you ...
``` void pass_arr(int arr[]); void pass_arr_test() { int arr[5] = {1,2,3,4,5}; printf( "arr = %p\n" "&arr = %p\n\n", arr, &arr); pass_arr(arr); } void pass_arr(int arr[]) { printf( "passed arr = %p\n" "passed &arr = %p\n\n", arr, &arr); } ``` Output:arr = 0x28ccd0&arr ...
That's because in the functionarris actually a pointer, not an array. Taking the address of a pointer does not yield the same address, the way it does for an array.
I want toincludethe result of a macro expansion. It seemsincludeonly knows <> ""? This fails: ``` #define audio sinwave #ifdef audio #include audio".c" /*#include "sinwave.c"*/ #endif ``` But this works: ``` #ifdef audio if(i==0){set_audio((char *)audio);return;} #endif ```
You could do something like this: ``` #define audio audio #define FF(X) #X #define F(X) FF(X.c) #ifdef audio #include F(audio) #endif ``` that is you'd have to append the.cbefore you place everything into a string. The usual concatenation"audio" ".c" -> "audio.c"of adjacent strings happens in a later compilation p...
Using c: ``` char ptr[n]; free(ptr); ``` In my opinion: when "char ptr[n];" is used, the memory is allocated, and ptr is pointed to it, free(ptr) should work. And the program failed, why?(n == 5 e.g.) Any deep analysis?
Because you calledfreeon a variable not allocated withmalloc.This causesUndefined Behavior. Luckily for you it crashes and you can detect it, else it can crash at most awkward times. You callfreefor deallocating memory of heap allocated variables, What you have is an array on local storage(assuming it to be in a func...
I'm reading aboutTypedefon wikipedia. Example mentioned on that page is ``` typedef int km_per_hour ; typedef int points ; km_per_hour current_speed ; points high_score ; ... void congratulate(points your_score) { if (your_score > high_score) ... ``` Going further it says this which I'm not able to understand why?...
You cannot prependsignedorunsignedbefore atypedef'd type.signedandunsignedcan only modify basic integer types and do that directly. The compiler parsessignedorunsignedeither alone or nearchar,short,intandlong. In all other cases they are considered invalid/unexpected/misplaced. In that sense,signedandunsigneddon't w...
I am new to C.I have a code that reads first word from the line, Here is a piece of it: ``` scanf(Line, "%s", Word); printf("%s\n", Word); ``` This code reads and prints the first word in the line. However, I need to compare the first word of the line to another word. Any suggestions?
strcmp(str1,str2)Compares the C string str1 to the C string str2. This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached. Returns an integral value indicating...
using only bitwise operators(|, &, ~, ^, >>, <<), is it possible to replace the!=below? ``` // ... if(a != b){ // Some code } /// ... ``` this is mainly out of self interest, since I saw how to do it with==but not!=.
``` if(a ^ b) { //some code } ``` should work. You can also use your preferred method for==and add^ 0xFFFFFFFFbehind it (with the right amount of Fs to match the length of the datatype). This negates the value (same as!in front of it).
As a programmer of long standing, it's sobering to realise that even the humbleforloop is not fully comprehended. Why does the following program print a single1to the console? I fully expect the first loop to also produce a1! Compiled with-ansiswitch. ``` /* gcc installed version: 4:4.4.4-1ubuntu2 */ #include <stdio...
the first loop is equivalent to: ``` for(i=0; ; i++) { if( !((i<SIZE) && (a[i]!=0))) break; printf("%i\n",a[i]); } ```
So this is the scenario that I'm looking at: I have 3 libraries - A, B and C. Library A implements functionfoo()and exposes it as an API.Functionfoo()calls the POSIXwrite()call to write some data.Library B writes a wrapper to thewrite()glibc call using the linker -wrap option.Library C links to both A and B. Anywri...
IfAis linked with-wrap=write,foowill call the wrapper. If it's not, it won't. The same is true about calls towriteinC. There's no difference whatsoever betweenAandCas far as callingwriteis concerned.
So this is the scenario that I'm looking at: I have 3 libraries - A, B and C. Library A implements functionfoo()and exposes it as an API.Functionfoo()calls the POSIXwrite()call to write some data.Library B writes a wrapper to thewrite()glibc call using the linker -wrap option.Library C links to both A and B. Anywri...
IfAis linked with-wrap=write,foowill call the wrapper. If it's not, it won't. The same is true about calls towriteinC. There's no difference whatsoever betweenAandCas far as callingwriteis concerned.
I've got a question regarding writing applications for Windows. Can I use WinAPI and DWMApi (aero glass, ribbon, etc.) when programming in ANSI C? I'm looking at MSDN right now and they use c++.
The Windows API is a C API and can be used with any compiler that supports the 'standard' calling convention. Microsoft has made the strategic decision to put their own C compiler on life support, though, and you're stuck with C90 (with some specific extension) when using Visual Studio. You can use 3rd party compiler...
From definitiondouble strtod ( const char * str, char ** endptr ); C reference sites provide an example for that mighty function: ``` char szOrbits[] = "365.24 29.53"; char * pEnd; double d1, d2; d1 = strtod (szOrbits,&pEnd); d2 = strtod (pEnd,NULL); ``` Ifendptrshould be of typechar **why ischar *pEndused here ? A...
The type ofpEndischar *. The type of&pEndischar **. C passes arguments to functions by value, so to modify a pointer you need to pass a pointer to the pointer. You could define achar **directly but you would need to initialize it to achar *as the idea is thatstrtodis modifying achar *. Like: ``` char *q; char **p ...
``` void slice_first_char(char ** string) { *string = &(*string[1]); } int main(int argc, char * argv[]) { char * input = "abc"; input = &(input[1]); puts(input); // "bc" as expected. slice_first_char(&input); puts(input); // \372\277_\377 // What‘s going on? } ``` How can I...
You got the parentheses in ``` &(*string[1]); ``` wrong. I guess you meant ``` &((*string)[1]); ``` Your original version dereferences the pointer of the first element of thestringsarray, and then takes the address of that whereas you actually want to dereference the given pointer (because it just points to a sing...
So I want to toggle the most significant bit of my number. Here is an example: ``` x = 100101 then answer should be 00101 ``` I have a 64 bit machine and hence I am not expecting the answer to be100000..<51 0's>..100101One way I thought of was to count the number of bits in my number and then toggle the MSB, but not...
The cheat is to pawn it off to the compiler: There are instructions in most CPUs for doing work like this. The following should do what you want. ``` i ^ (1 << (sizeof i * CHAR_BIT - clz(i) - 1)) ``` This will translate into theCLZinstruction, which counts the leading zeros. For GCC, see:http://gcc.gnu.org/onlined...
As the title says, in my program I (after many procedures) get tokenized words. Unfortunately due to reversing them they hold punctuation characters at the beginning of a word eg. ,moose How to move that,from the beginning to the end -> moose, Up to now I've tried(ptrischar *): ``` temp = strdup(ptr); temp = &ptr[0...
Something like this: ``` void swap_last(char *str) { const size_t len = strlen(str); if(len > 1) { const char first = str[0]; memmove(str, str + 1, len - 1); str[len - 1] = first; } } ``` Note that the above assumesstrto be valid.
If we have to hold an address of any data type then we require a pointer of that data type. But a pointer is simply an address, and an address is alwaysinttype. Then why does the holding address of any data type require the pointer of that type?
There are several reasons: Not all addresses are created equal; in particular, in non Von Neuman (e.g.Harvard) architectures pointers to code memory (where you often store constants) and a pointers to data memory are different.You need to know the underlying type in order to perform your accesses correctly. For examp...
A bitmap sort programme,in which the assign part is: ``` for(i = MAX/64-1;i >= 0;i--){ for(j = 0;j < 64;j++){ if(0 != (arr[i] & (1 << j))){ *p++ = j + 64 * i; } } } ``` I gdb it,sometimes when the if condition returns 0 and the program still enter the block and execute the...
My guess is that you have 32 bit ints but your array data type isint64_t. In which case you need to change: ``` if(0 != (arr[i] & (1 << j))){ ``` to: ``` if(0 != (arr[i] & (1LL << j))){ ``` since1 << jis undefined forj >= sizeof(int) * CHAR_BIT(i.e.j >= 32in your case).
I am getting this following error, I have a "A.c" file in which I have included a "b.h" file, which has a "c.h" file. Now this c.h has structures which are getting used and they are all int. the structures are used in the following way: In "c.h" file ``` struct abc{ int a;<---- error }; ``` In "b.h" ``` struc...
You probably have some nesting error, a missing;or something that confuses the compiler. I would recommend trying to get hold of the preprocessor output, so you can see what the compiler sees, once the#includeshave been executed.
I have to work with eclipse in C. I wrote a simple program, but I have a problem with aprintfcommand which doesn't work properly. Any idea? Here is the code : ``` #include <stdio.h> void change(double *x, double *y) { double help = *x; *x = *y; *y = help; return; } int main() { double x=0, y=0; printf("please...
All your values aredoublefor which you have to use%lf. Buut you are using%fwhich invokes undefined behaviour. Change%fto%lfin your scanfs and prints.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago. I need to use incov library to conv...
The easiest way to convert ASCII to UTF-8 isstrcpyormemcpy...
I have have two .c files (main.c and support.c). Support.c is compiled first and then main.c is compiled and linked with support.o. I have several non-static global variables in support.c. How are those global variables from support.c stored? If main.c is multithreaded and has two threads calling the functions in ...
A global variable is a global variable, and there's always just one, no matter in how many pieces you compile and link your program. If multiple threads access global data concurrently, you need to ensure the proper synchronization yourself. The only way to get a separate copy of a global or block-static variable is ...
I am having this problem whenever I try to debug my project: It's in French, here is my translation: "Error while trying to run project: Failed Loading assembly "DBZ buu's Fury Text Editor" or one of it's dependencies. The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)" Can ...
If you are usingAssembly.Load()to load file try to change it withAssembly.LoadFile()instead.
``` - (void)change:(int)a { int number = a; int max = 10; switch(max) { case number: //Do something break; //.... more cases } } ``` This is just a small example of the issue I can't seem to solve. I have looked at similar posts and answers usually include using constants via a...
In a nutshell,casestatements can only operate on constant expressions, so if you need more dynamic conditionals, you will have to useifstatements.
Is it possible to define a macro in a C file, and then change behavior of another C file using this definition? For instance, suppose we have a file namedb.c: ``` #include <stdio.h> #define ABC void function() { printf("b.c\n"); } ``` And another file nameda.c: ``` #include <stdio.h> int main() { #ifdef ...
Use global variables or use callbacks. The "best" solution depends on precisely how much flexibility you need.
I declare hws globally and try to return it in this method but I get a pointer error. I was wondering if anyone knew why that is and could suggest a solution? Randomize just get a random number. ``` extern int hws[100][20]; int randomize() { int value; int tru_fals = 0; value = -1; while ( tru_fal...
there is a bug: the array is declared as 100x20 but then you iterate through it like it is 20x100.
I'm dealing with some code written in manner that is really, honestly, ugly. Is there a way to auto enforce proper tabs and remove all of the random multi-line white space entries?
Old Unix people have a solution for everything, including lazy programmers. EnterGNU indent.
This question is geared for iOS version compatibility. I know how to check if a function exists if it is a typical Objective-C style method using respondsToSelector. i.e. For a method such as: ``` - (void) someMethod:(NSInteger)someParameter; ``` You can use: ``` if ([self respondsToSelector:@selector(someMethod:s...
Xcode (at least since 4.3) supports weak linking and you can do the following to see if you can call a C function: ``` // UIGraphicsBeginImageContextWithOptions() was introduced in iOS 4 in order to support the Retina displays. if (UIGraphicsBeginImageContextWithOptions != NULL) { UIGraphicsBeginImageContextWithO...
I',m probably doing some incredibly stupid mistake, but i cannot find it, it is simple that: ``` int main() { typedef struct drzemka typ; struct drzemka { int strukcje; }; typ *d; d->strukcje = 1; } ``` and it is not working
Right now your pointer is not set to a valid piece of memory. You need to allocated this memory for thestruct: ``` #include <stdlib.h> /* ... */ typ *d = malloc(sizeof(typ)); ``` As with any memory you allocate, remember to free it after you're done: ``` free(d); ```
Why wouldprintf("%c ", 2293552);print0? ASCII values are from 0 to 127 I know this must be some cyclic thing but I want a clear explanation. Thank you
The number2293552corresponds to0x22ff30. Whenprintfinterprets it as ASCII, it ignores all bits beyond the last eight bits containing0x30, which is the code for'0'. From the C99 standard: 7.19.1.6.8 --%c: If nollength modifier is present, the int argument is converted to anunsigned char, and the resulting character i...
Has anyone managed to build the CUnit library for Windows? I want to run the same unit tests under Windows that I have currently developed under linux, so I need a windows version of the cunit shared library to link to I'm struggling badly have MinGW and MinGW MSYS tools installed so have a gcc compiler and Make an...
The answer above is wrong. The correct answer is as follows: ``` libtoolize automake --add-missing autoreconf ./configure --prefix=/mingw make make install ```
I am readingGoogletest doc, and I am learning that there is one syntax for comparing string, and another for comparing C string. I dont see what is referred to as C string and as string. How are these different?
If you try to useASSERT_EQto C-Strings, you only compare two pointers, but not really null-terminated C-Strings. For that existsASSERT_STREQsyntax.
As the topic says - for what characters wouldisblank(int c)return true ? Haven't found any entry about that function here on SO.
Unless you've set the current locale to something other than"C", it will only return true for' 'and'\t'. N1570: 7.4.1.3 Theisblankfunction...2 Theisblankfunction tests for any character that is a standard blank character or is one of a locale-specific set of characters for whichisspaceis true and that is used to sepa...
I was trying to find a way to allocate a single block of memory, but use multi-dimensional syntax, and I found the exact thing I was looking for on SO. malloc in C, but use multi-dimensional array syntax But after cut/pasting the code there: ``` int (*MAGICVAR)[200] = malloc(400 * sizeof *MAGICVAR); MAGICVAR[20...
First, use a C compiler and not a C++ compiler to compile C code, second, if you have to use a C++ compiler, cast the return value ofmallocto the declared type, ``` int (*MAGICVAR)[200] = (int(*)[200])malloc(400*sizeof *MAGICVAR); ```
How can I check if a directory exists on Linux in C?
You can useopendir()and check ifENOENT == errnoon failure: ``` #include <dirent.h> #include <errno.h> DIR* dir = opendir("mydir"); if (dir) { /* Directory exists. */ closedir(dir); } else if (ENOENT == errno) { /* Directory does not exist. */ } else { /* opendir() failed for some other reason. */ } `...
I'm writing some code that makes use of computed goto. The syntax checker is flagging every instance ofgoto *ptrand&&labelas syntax error. Is there anyway to stop this? Addition by alk: Example for computed gotos (gcc extension): ``` ... void * pLbl = NULL; if (<some expression>) pLbl = &&lbl1; /* gcc extensio...
No way other then filing a bug to theCDT bugtracker, preferably with a patch for the parser.
I have ``` #define ADD 5 #define SUB 6 ``` Can I print ADD and SUB given their values 5 and 6?
No. The names of thedefined symbols are removed by the preprocessor, so the compiler never sees them. If these names are important at runtime, they need to be encoded in something more persistent than just preprocessor symbol names. Perhaps a table with strings and integers: ``` #define DEFINE_OP(n) { #n, n } stat...
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer...
PolarSSLseems to have quite good coverage.
I want to convert an array ofuint8_tto auint32_tinNesC. Does anyone know how I can do this?
The solution that i were found is the use of the function : ``` void * memcpy ( void * destination, const void * source, size_t num ); ``` There is also the function : ``` void * memset ( void * ptr, int value, size_t num ); ``` In my code i use memcpy and it works fine. Thanks to all people that answer my questio...
I am new to Windows programming. On Windows OS, almost every application opens a window, and I want to know that if all these applications invoke the same APICreateWindow()to create their windows? Or, another way to ask my question: Do Games, Music Players, Browsers, Instant Messaging, IDEs, etc create their window a...
Yes, that andCreateWindowExare the only APIs that can create a window (other related APIs such asDialogBoxandAllocConsolealso do this internally). No matter what graphics stack each application uses (WPF, DirectX etc) in the end it all boils down to aCreateWindow.
Sorry if this is a primitive question but I am really new in linux. Is there a way to replace constants in source code while building the application usingmakecommand? I know the next possible method is to change the header files used in the source code, but I ask this because I have to program multiple microcontroll...
You could use aC language macropassed on the command line to the compiler. The usualMakefilesnippet would look something like ``` CFLAGS = -DVERSION_INT=42 -DVERSION_STRING=\"Frobozz Magic Frobnicator (TM)\" main: main.c $(CC) $(CFLAGS) -o $@ main.c ``` In main.c you might have ``` static int version = VE...
How can I find all words with at least one non latin letter (arabic, chinese...) in them using regex.h library? cityدبي
How about: ``` (?=\pL)(?![a-zA-Z]) ``` This will match a letter in any alphabet that is not a latin letter: ``` not ok - cityدبي ok - city not ok - دبي ```
Why the below program gives the output :A. what is use of\nafter the format specifier%d? I have tried it on Linux, Windows andideone. ``` #include <stdio.h> int main(void) { char p[]="%d\n"; p[1]='c'; printf(p,65); return 0; } ```
First, your program modifies the format string: it becomes "%c\n". Then it prints 65, which is re-interpreted as an ASCII code, which is an upper-caseA. This is identical to ``` printf("%c\n", 65); ``` or even ``` printf("%c\n", 'A'); ``` becausecharvalues are converted tointwhen passed to variadic functions such...
Are there any generally-applicable tips to reduce the accumulation of floating-point roundoff errors in C or C++? I'm thinking mainly about how to write code that gets compiled into optimal assembly language instructions, although strategies on overall algorithm design are also welcome.
Numerical analysisis a whole field of mathematics and it isn't reduced to some tips one can apply blindly.
Today I was messing around with malloc and integer pointer. The program is setup so it allocates a memory location to an integer pointer and then fills the memory location with bunch of integers like an array and then print all the integers. The problem is when ever it finishes running it crashes. And I suspect that m...
``` name = malloc(sizeof(int)); ``` is the problem. That way you can store only one int in the array. Try ``` name = malloc(sizeof(int) * 500); ``` instead.
``` #include <stdio.h> #include <sys/time.h> int main() { float time; struct timeval tv; gettimeofday( &tv, NULL ); time = tv.tv_sec + ( tv.tv_usec / 1000000.0 ); printf( "time: %f\n", time ); return 0; } ``` Running binary generated by this code repeatedly, I tend to get the same time value: ``` ...
It appears thatfloatis too small to contain the result oftv.tv_sec + ( tv.tv_usec / 1000000.0 ). Usedoubleinstead: ``` #include <stdio.h> #include <sys/time.h> int main() { double time; struct timeval tv; gettimeofday( &tv, NULL ); time = tv.tv_sec + ( tv.tv_usec / 1000000.0 ); printf( "time: %f\n", t...
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer...
PolarSSLseems to have quite good coverage.
I want to convert an array ofuint8_tto auint32_tinNesC. Does anyone know how I can do this?
The solution that i were found is the use of the function : ``` void * memcpy ( void * destination, const void * source, size_t num ); ``` There is also the function : ``` void * memset ( void * ptr, int value, size_t num ); ``` In my code i use memcpy and it works fine. Thanks to all people that answer my questio...
I am new to Windows programming. On Windows OS, almost every application opens a window, and I want to know that if all these applications invoke the same APICreateWindow()to create their windows? Or, another way to ask my question: Do Games, Music Players, Browsers, Instant Messaging, IDEs, etc create their window a...
Yes, that andCreateWindowExare the only APIs that can create a window (other related APIs such asDialogBoxandAllocConsolealso do this internally). No matter what graphics stack each application uses (WPF, DirectX etc) in the end it all boils down to aCreateWindow.
Sorry if this is a primitive question but I am really new in linux. Is there a way to replace constants in source code while building the application usingmakecommand? I know the next possible method is to change the header files used in the source code, but I ask this because I have to program multiple microcontroll...
You could use aC language macropassed on the command line to the compiler. The usualMakefilesnippet would look something like ``` CFLAGS = -DVERSION_INT=42 -DVERSION_STRING=\"Frobozz Magic Frobnicator (TM)\" main: main.c $(CC) $(CFLAGS) -o $@ main.c ``` In main.c you might have ``` static int version = VE...
How can I find all words with at least one non latin letter (arabic, chinese...) in them using regex.h library? cityدبي
How about: ``` (?=\pL)(?![a-zA-Z]) ``` This will match a letter in any alphabet that is not a latin letter: ``` not ok - cityدبي ok - city not ok - دبي ```
Why the below program gives the output :A. what is use of\nafter the format specifier%d? I have tried it on Linux, Windows andideone. ``` #include <stdio.h> int main(void) { char p[]="%d\n"; p[1]='c'; printf(p,65); return 0; } ```
First, your program modifies the format string: it becomes "%c\n". Then it prints 65, which is re-interpreted as an ASCII code, which is an upper-caseA. This is identical to ``` printf("%c\n", 65); ``` or even ``` printf("%c\n", 'A'); ``` becausecharvalues are converted tointwhen passed to variadic functions such...
Are there any generally-applicable tips to reduce the accumulation of floating-point roundoff errors in C or C++? I'm thinking mainly about how to write code that gets compiled into optimal assembly language instructions, although strategies on overall algorithm design are also welcome.
Numerical analysisis a whole field of mathematics and it isn't reduced to some tips one can apply blindly.
I have something like this: ``` DIR *dir = opendir(curdir); struct dirent *de = readdir(dir); struc stat st; lstat(de->d_name, &st); ``` I would like to know ifdeis a directory or a file, what should I do with st?
The correct and simple way is to checkif (de->d_type == DT_DIR). You don't have to uselstatfor that.
Currently I have some C code which will every time an arrow key is pressed it will reprint an array of characters to the screen and change only the player's position one spot. I would like to know how to only reprint the two characters that are actually changing, instead of reprinting the entire array of characters. ...
ncursesis a nice portable library which handles terminal graphics; I'd definitely recommend it for your purposes.
Recently I'm studying the source code of NginX. I found it quite interesting while I'm curious about the memory management design, what's the concern when they define the size of NGX_POOL_ALIGNMENT and NGX_DEFAULT_POOL_SIZE? And why they have such memory alignment design? I really hope somebody could give me some tip...
You should probably ask the developers of NginX. My guess is that they are just aligning stuff to a cacheline (or multiple of a cacheline). Obviously they do that for performance.
In Java, I can have something like this: ``` Process p = Runtime.getRuntime().exec("su"); DataOutputStream pOut = new DataOutputStream(p.getOutputStream()); pOut.writeBytes("find / -perm -2000 -o -perm -4000\n"); pOut.writeBytes("ps\n"); pOut.writeBytes("ls\n"); pOut.writeBytes("exit\n"); pOut.flush(); p.waitFor(); `...
I don't see what's the point for you to use system() to execute, system() doesn't return you stream to read the output. I think you should try popen() instead
I have a C array of shorts and an array of longs. I want to be able to define when one of the array slots is not able to be filled by a function that calls it because there is insufficient or missing data. The valid values in both cases can be positive or negative, but I can safely assume that the values will never co...
I assume you're using the maximum value to indicate anullparameter in the array. This is a common technique and is totally valid. As for the max double, you wantDBL_MAXfrom<float.h>.
Single threaded application (C++) continuously locks, writes and unlocks shared memory -four times a second(the loop is programically set to run once a second and there are 4 writes in the loop and no reads). EnterCriticalSection(cs);WriteToSharedMem();LeaveCriticalSection(cs); Another application (C) will access th...
The rate you give (four times a second) won't cause a problem, butyou can't use critical sections across processes. You need a kernel level synchronization object like amutex.
I have a project wherein i need to write an application for an USRP device. But the gnuradio software which i use to interact with the device driver and ultimately the hardware provides apis in c++ and python. I am comfortable programming in c and thus would like a way which would let me to call the apis from my c pro...
C++ adds a lot to C, but doesn't take much away. Except for a few corner cases (which can be worked around) most valid C code is also valid C++ code, so you won't encounter many problems when you compile it as C++. Just write your whole project in a C style and only use C++ features where they are necessary to interfa...
I have a C program that uses some resources located in the same directory as the executable. When I execute the program from a random working directory (not the directory where the program is located) the resources don't load, because the relative path I use in the code is not the path where the executable is. How can...
Pass the path of the directory that contains the resources to the program as an argument and either: change the current directory of the process to the directory (chdir()on Unix andSetCurrentDirectory()on Windows), orconstruct absolute paths to the resources If it is Windows, as the comment on the question suggest...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago. Ok so I want to preface this by say...
You can use the functions declared in the header filectype.h, in particular the functionisdigit.
I allready build clang(3.2) with MSVC and MinGW succesfully. But I think it's not the "purely" clang. So could someone give me some instructions or materials about how to use clang to build clang(Windows/Linux)? And could we use clang indepently(Not depent on GCC or MSVC). Thanks all!
Well get an older version of clang like 3.1. (You can pretty much install any version that comes precompiled for your OS) Get the sources for a newer version like 3.2. Then (i like cmake+ninja (http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html)) if you unpacked llvm source to ~/llvm_source/llvm ``` cd ~/llv...
I was just going through some C code, when I got stuck upon this piece of code. ``` void someFunction(Int32 someVariable) { /* someVariable is hard coded to 2 */ (void)someVariable; //some processing that has nothing to do with someVariable. } ``` What does the author meant by the comment, "someVariable...
Most likely this (casting of a function argument tovoid) is done to shut up the compiler, which otherwise would warn or error out because of the unused argument. Whether the value is "hard-coded" somewhere is irrelevant to the presented code.
I have something like this: ``` DIR *dir = opendir(curdir); struct dirent *de = readdir(dir); struc stat st; lstat(de->d_name, &st); ``` I would like to know ifdeis a directory or a file, what should I do with st?
The correct and simple way is to checkif (de->d_type == DT_DIR). You don't have to uselstatfor that.