question
stringlengths
25
894
answer
stringlengths
4
863
I have a variableawhich can have only two valuesx1orx2. How to toggleabetween these values. I came up with this. Any other more efficient way? ``` a = (a == x1 ? x2: x1); ```
It's (highly) unlikely to be your bottleneck, but you could use theXORmethod: ``` togglex1x2 = (x1 ^ x2); // This is the combined toggle value a = x1; // Initialise to either x1 or x2 a ^= togglex1x2; // toggles a ^= togglex1x2; // toggles ... ``` [You should write code that is understandable ...
If I encounterfeof()and thenstatshows that the file has grown, is there a way to read the added data without doing afclose()andfopen()?
Yes. You can callclearerron the file, or perform any seek opereration such asfseek(f, 0, SEEK_CUR).
I have something that I need to do using uniform smoothing filter operation on an image. I was wondering if someone could just answer a few questions for me. What is "Square Odd Window Size"? What is the difference 2D smoothing and separable 1D smoothing? Thank you
Square Odd Window Size just means that the filter window is square (N by N) and N is odd. N being odd ensures a well defined center to the window. 1D separable smoothing is a method used to implement 2D smoothing. It allows for you to smooth and image in O(M²N) time rather than O(M²N²) where M is the height and width...
In the producer process, I have the following.say MEMKEY is key_t 234500, and*shared_ring is a pointer to the data structure (donut_ring) that is being shared.int shmid, semid[3];if((shmid = shmget (MEMKEY, sizeof(struct donut_ring), IPC_CREAT | 0600)) == -1){ perror("shared get failed: "); exit(1);}i...
Figured it out, the answer is Yes. Both calls are necessary in both files.
given this definition: ``` typedef enum mytype { FIRST = 0, TWO = 1, Three = 2 } mytype_t; ``` and ``` somefunction(mytype_t param_one) { (some code) } ``` How I can get the integer value of param_one inside the function or assign it to a integer variable?
You just use it - it is an integer type already: ``` int x = param_one; ```
consider the following structures: ``` struct intNode { int num; intNode* pNext; }; struct list { intNode* first; intNode* last; int size; }; ``` suppose I allocated memory for the list. If I call free(lst) will it also free the memory allocated to the intNode first and last? and what about the...
You need to free them all individually, but usually for linked lists this is done iteratively, not recursively: ``` void DeleteList(struct intNode *pHead) { struct intNode *pCur=pHead, *pDel=NULL; while(pCur != NULL) { pDel = pCur; pCur = pCur->pNext; free(pDel); } } ```
Can reassigning a C style string cause a memory leak? Like so: ``` char * s = "Hello!"; s = "Hello, world!"; ``` My question may appear as stupid, but please bear with me; I am currently still a dummie in C++. In the second line of code, the C style stringsis longer, so does it have it internally reallocate memory?...
Actually, technically no. String literals are provided special static allocation. See Is a string literal in c++ created in static memory?
This question already has answers here:Segmentation fault - char pointer(4 answers)Closed9 years ago. I am trying to understand why this works: ``` char myst1r[] = "hello\n"; memmove(myst1r , myst1r + 1 , 1 );//results in "eello" ``` while this one : ``` char *mystr = "hello\n"; memmove(mystr , mystr + 1 , 1 ); ...
myst1ris anarrayofcharthat holds acopyof its initializer.mystris apointertocharthat points to its initializer. In both cases, the initializer is a literal string. The difference is that you can modify the contents of an array, but you cannot modify the contents of a literal string.
Do you know which library or function should I use to change Console Application width and height in C without using windows or GUI header? Im using code:blocks .
In the case of the console, it is simply another window, except that it is considered "special" by Windows since it serves a certain purpose, which means you have two options: use the console API, a small subset of the Windows API, orget the window handle of the console somehow and resize it directly. Both require u...
I got some problem with RVCT compile environment, need your help. There is a function like this ``` int lib_func(int b) ``` but i don't have the source code of this function. I want to wrap this function and add some debug flag. In GCC, i can create__wrap_lib_func, and call__real_lib_func, then modify the makefi...
There is the $Super$$/$Sub$$ functionality in the linker, that lets you "intercept" calls:http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0474i/Chdefdce.html Of course that document is for version 5.03, but the functionality was there in 3.1 and I would be surprised if the syntax has changed.
``` void harmsec(){ int n = 1; float y = 1; printf("Harmonic sequence: "); while (y >= 0.11){ printf("%.2f", y); printf(", "); n = n + 1; y = 1*(1/n); } /*while*/ if (y < 0.11){ printf("%.2f", y); printf("\n")...
1/n is done as integer division, and n is 2 first time so 1/2 = 0 and y goes to zero. Change 1/n to 1./n which will then calculate the division in floating-point precision.
This question already has answers here:How to implement a timer in c?(7 answers)Creating a Timer in C(2 answers)Closed10 years ago. I need to loop for a certain amount of time based on user input ( in C Program ). Example: User says loop for 2 Minutes ( = 120 seconds). ``` while(time <= 2 Minutes) { do somethin...
If you need to perform some operation as many times as possible within the specific period of time you can usetime(): ``` time_t secs = 120; // 2 minutes (can be retrieved from user's input) time_t startTime = time(NULL); while (time(NULL) - startTime < secs) { ... } ```
In C,stdinis a valid file pointer, thus we could usestdin(and the 2 others) with the "file" version of the input functions if we want or need to. Why might us need to (Rather than just pipe in from shell)? Could anyone come up with some examples please?
Here's an example: ``` FILE * input = argc == 2 ? fopen(argv[1], "r") : stdin; fgets(buf, sizeof buf, input); ``` Now you can use your tool asmagic data.txtand asmagic < data.txt.
I want to write numbers into a file .dat in C++. I create a function, it uses ofstream. It's correct? ``` void writeValue(char* file, int value){ ofstream f; f.open(file); if (f.good()){ f<<value; } f.close(); } ``` Thanks.
Yes, it's correct. It can also be simplified, for example: ``` #include<fstream> #include<string> using namespace std; void writeValue(const char* file, int value){ ofstream f(file); if (f) f<<value; } int main() { string s = "text"; writeValue(s.c_str(), 12); } ``` It may be m...
While I'm running this code: ``` #include <stdio.h> #include <stdlib.h> int main ( int argc, char *argv[] ) { int i=0; int *arrNum = (int *) malloc(sizeof(int) * 5); if(arrNum == NULL) { puts("Failed to allocate memory !!!"); exit(1); } while(i<5) ...
In yourscanfyou are not providing the address of individual elements of array Fix : ``` scanf("%d", &arrNum[i]); ^ use & ```
In C,stdinis a valid file pointer, thus we could usestdin(and the 2 others) with the "file" version of the input functions if we want or need to. Why might us need to (Rather than just pipe in from shell)? Could anyone come up with some examples please?
Here's an example: ``` FILE * input = argc == 2 ? fopen(argv[1], "r") : stdin; fgets(buf, sizeof buf, input); ``` Now you can use your tool asmagic data.txtand asmagic < data.txt.
I want to write numbers into a file .dat in C++. I create a function, it uses ofstream. It's correct? ``` void writeValue(char* file, int value){ ofstream f; f.open(file); if (f.good()){ f<<value; } f.close(); } ``` Thanks.
Yes, it's correct. It can also be simplified, for example: ``` #include<fstream> #include<string> using namespace std; void writeValue(const char* file, int value){ ofstream f(file); if (f) f<<value; } int main() { string s = "text"; writeValue(s.c_str(), 12); } ``` It may be m...
While I'm running this code: ``` #include <stdio.h> #include <stdlib.h> int main ( int argc, char *argv[] ) { int i=0; int *arrNum = (int *) malloc(sizeof(int) * 5); if(arrNum == NULL) { puts("Failed to allocate memory !!!"); exit(1); } while(i<5) ...
In yourscanfyou are not providing the address of individual elements of array Fix : ``` scanf("%d", &arrNum[i]); ^ use & ```
I am currently working on a project that involves creating some DLL libraries withCthat will be shipped to customers. The DLL exports some functions and all exported functions use the__stdcallcalling convention. The library also contains some functions that are not exported but are used by the exported functions. Is i...
No, you do not need to worry about calling conventions of internal functions. Yes, you can leave them as they are. Calling convention is an instruction for a compiler. You need to worry about that only if you want to call your function "manually", e.g. from Assembly or other languages. Your DLL is already compiled a...
Usually when we initialize an array, we would probably do: ``` int arr[] = {1, 2, 3, 4, 5}; ``` But is it ok to explicitly limit the length of the array as below? : ``` int arr[3] = {1, 2, 3, 4, 5}; ``` Despite some warnings from the compiler, the executable doesn't seem to have any problems.
No, it's not OK. From C99, 6.7.8.2: ConstraintsNo initializer shall attempt to provide a value for an object not contained within the entity being initialized. In my read, this means that providing excess initializer elements is aconstraint violation,so it invokes undefined behavior.
I am trying to write a C function which checks if aintis positive or not. This is what i have: ``` int isPositive(int x){ return ~(x >> 31) & 0x1; } ``` Depending on the number, this should return 1 is positive and 0 is not. It works for all the numbers but not for-2147483648. That number should fit in a 32bit ...
How did you enter the-2147483648? If you just typed it directly into your program, that would be the unary-applied to the literal, not a literalincludingthe-. Since 2147483648 doesn't fit in anint, your literal gets theunsignedtype. Either useINT_MIN, or use the trick most libraries use to define it: ``` isPositive...
In Linux, how do I get the man pages for C functions rather than shell commands? For example, when I typeman bindI get the manual page for the shell commandbindand not the man page for socket binding C function.
``` man 2 bind ``` You need a result from a different section of the manual! Man searches various sections for the information you want. As devnull lists below, the number indicates which section to search. Incidentally,bindis a system call, not a C library function. System calls (kernel calls) are in section 2 of t...
I'm having thoughts about copying a string to a 2d array. I have a 2d char array initialized aschar labels[100][2]so it's a 100 * 2 array. I would like the first column of every row to contain a string and I know you can't simply assign a string, you must do a string copy. My thinking was I could do: ``` strcpy(label...
To process a column of a 2D array you can do as; ``` char labels[100][2], (*p)[2], i; .... for (p = &labels[i]; p < &labels[100]; P++) (*P)[i] = //assign a char ```
I am trying and using libevent in my eclipse c/c++ project. I downloaded the libevent library using this command ``` sudo apt-get install libevent-dev ``` It is working normally so that in the specific directory I was looking for alibevent.afile to include it as library in my eclipse project but I can only find alib...
do you see it with command: ``` dpkg -L libevent-dev|grep libevent.a ``` In normally, libevent-dev will install libevent to standard system library location, so you just need to addeventto Project Properties -> C/C++ General -> Path And Symbols -> Library Paths
This question already has answers here:How do you check the windows version in Win32 at runtime?(2 answers)Closed10 years ago. I wanted to ask, is there any possibility to determine the Windows version via the application, I have made some research, but haven't found, Thank you in advance ^^
Err... How aboutGetVersionEx()?
``` for(i = 0; str[i]; ++i) ++count[str[i]]; // Change count[i] so that count[i] now contains actual position of // this character in output array for (i = 1; i <= RANGE; ++i) count[i] += count[i-1]; // Build the output character array for (i = 0; str[i]; ++i) { output[count[str[i]]-1] = str[i]; --co...
In C, any expression can be evaluated for 'truth'. In this case, we're checking to see ifstr[i]is true or not. If it is'\0', then it is false and the loop ends - that way we can leave the loop once we find the end of the string. Any other character value is considered true, and the loop continues.
I tried to initialize a doubly linked list wich contains dummy nodes inside another doubly linked list (also with dummy nodes). For example, a node in the list of students has many friends stored in a linked list inside that node. Here's my code: As I tried to compile it, it gave me this:warning: assignment from inco...
You are assigning a pointer of type "friendt" to "friendh". newNode -> friendh -> next // is a pointer of type friendh. You are assigning it a pointer of type friendt. You're doing the opposite in the next line. Assigning friendh to friendt. Assuming both your structs do the same thing, keep one struct or change th...
I want to find out the (short / int / long / float / double / long double / char) size, so I wrote this code: ``` printf("short\t\t%d\n", sizeof(short)); printf("int\t\t%d\n", sizeof(int)); printf("long\t\t%d\n", sizeof(long)); printf("float\t\t%d\n", sizeof(float)); printf("double\t\t%d\n", sizeof(double)); pr...
sizeofevaluates to asize_t, not anint. So%dis not appropriate; you're invoking undefined behaviour. To correctly print data of typesize_t, I suggest e.g.printf("%zu\n", sizeof(float));, etc.
I have some huge libraries that are compiled with debug info; when linking them with some small object files I write, it still takes quite a lot of time and the generated executable contains a lot of debug information of the libraries. So is there an option to tell gcc/clang to discard those debug information inside ...
As already said in the comments, there's two ways out: Keep a local copy of said libraries, stripped of debug info.Link with-Wl,-sor-s, which makes the linker output a stripped executable.
In Linux, how do I get the man pages for C functions rather than shell commands? For example, when I typeman bindI get the manual page for the shell commandbindand not the man page for socket binding C function.
``` man 2 bind ``` You need a result from a different section of the manual! Man searches various sections for the information you want. As devnull lists below, the number indicates which section to search. Incidentally,bindis a system call, not a C library function. System calls (kernel calls) are in section 2 of t...
I'm having thoughts about copying a string to a 2d array. I have a 2d char array initialized aschar labels[100][2]so it's a 100 * 2 array. I would like the first column of every row to contain a string and I know you can't simply assign a string, you must do a string copy. My thinking was I could do: ``` strcpy(label...
To process a column of a 2D array you can do as; ``` char labels[100][2], (*p)[2], i; .... for (p = &labels[i]; p < &labels[100]; P++) (*P)[i] = //assign a char ```
I am trying and using libevent in my eclipse c/c++ project. I downloaded the libevent library using this command ``` sudo apt-get install libevent-dev ``` It is working normally so that in the specific directory I was looking for alibevent.afile to include it as library in my eclipse project but I can only find alib...
do you see it with command: ``` dpkg -L libevent-dev|grep libevent.a ``` In normally, libevent-dev will install libevent to standard system library location, so you just need to addeventto Project Properties -> C/C++ General -> Path And Symbols -> Library Paths
This question already has answers here:How do you check the windows version in Win32 at runtime?(2 answers)Closed10 years ago. I wanted to ask, is there any possibility to determine the Windows version via the application, I have made some research, but haven't found, Thank you in advance ^^
Err... How aboutGetVersionEx()?
``` for(i = 0; str[i]; ++i) ++count[str[i]]; // Change count[i] so that count[i] now contains actual position of // this character in output array for (i = 1; i <= RANGE; ++i) count[i] += count[i-1]; // Build the output character array for (i = 0; str[i]; ++i) { output[count[str[i]]-1] = str[i]; --co...
In C, any expression can be evaluated for 'truth'. In this case, we're checking to see ifstr[i]is true or not. If it is'\0', then it is false and the loop ends - that way we can leave the loop once we find the end of the string. Any other character value is considered true, and the loop continues.
I tried to initialize a doubly linked list wich contains dummy nodes inside another doubly linked list (also with dummy nodes). For example, a node in the list of students has many friends stored in a linked list inside that node. Here's my code: As I tried to compile it, it gave me this:warning: assignment from inco...
You are assigning a pointer of type "friendt" to "friendh". newNode -> friendh -> next // is a pointer of type friendh. You are assigning it a pointer of type friendt. You're doing the opposite in the next line. Assigning friendh to friendt. Assuming both your structs do the same thing, keep one struct or change th...
I want to find out the (short / int / long / float / double / long double / char) size, so I wrote this code: ``` printf("short\t\t%d\n", sizeof(short)); printf("int\t\t%d\n", sizeof(int)); printf("long\t\t%d\n", sizeof(long)); printf("float\t\t%d\n", sizeof(float)); printf("double\t\t%d\n", sizeof(double)); pr...
sizeofevaluates to asize_t, not anint. So%dis not appropriate; you're invoking undefined behaviour. To correctly print data of typesize_t, I suggest e.g.printf("%zu\n", sizeof(float));, etc.
I have some huge libraries that are compiled with debug info; when linking them with some small object files I write, it still takes quite a lot of time and the generated executable contains a lot of debug information of the libraries. So is there an option to tell gcc/clang to discard those debug information inside ...
As already said in the comments, there's two ways out: Keep a local copy of said libraries, stripped of debug info.Link with-Wl,-sor-s, which makes the linker output a stripped executable.
I have the following section of code in C: ``` int main(int argc, char *argv[]) { char *input; int lines; int p; input = (char*)malloc(10); input = argv[0]; for(p=0;p<10;p++) { printf("%c",input[p]); } ``` On my Unix system I make the following call: ``` ./program_name.exe...
argv[0]holds name of program being executed. And that's the only thing you print. What you're trying to do is to read from your file as it was stdin. But you still have to read it. Use getchar(), or any other function that reads input.
``` #include <stdio.h> #include <stdlib.h> struct NODE { char* name; int val; struct NODE* next; }; typedef struct NODE Node; Node *head, *tail; head = (Node*) malloc( sizeof( Node ) ); //line 21 ``` And I compiling like this: ``` cc -g -c -o file.tab.o file.tab.c ``` I'm getting this error message: ...
It looks like the line ``` head = (Node*) malloc( sizeof( Node ) ); //line 21 ``` is outside themain()function. You can't do that, because you can't execute code outside functions. The only thing you can do at global scope isdeclaring variables.Just move it inside themain()or any other function, and the problem sho...
i am trying query windows for a list of all usb hdi devices that are connected to my computer. Somehow i the microsoft dokumentation is not exactly to helpfull for me. Can anybody please point me to something? I would like to use c/c++ Thanks!
here you can find anything you want:https://github.com/signal11/hidapi
Could someone outline how to use c99 when my c-programs compile? I cannot use the for(int i = 0...) loop without it. Note - all the answers I have found are either outdated, or for the cygwin compiler. thanks in advance
In the project build settings set-std=c99in the "Other flags" text box.
For C programmers. How can I know if a pointerchar *, for example, was initialized by usingmallocorrealloc? I mean in kind of that function: ``` char* func(char** x){ /* need some reallocating of *x but * *x can be a pointer to const string */ } ```
There's noportableway to determine whether a pointer refers to a static or auto variable, or to memory allocated via the*allocfunctions, by looking at the pointer value alone. If you areintimatelyfamiliar with the memory model on your platform you could make some educated guesses, but that's about it. Otherwise, if ...
``` #include <stdio.h> #define dprintf(expr) printf(#expr "=%d\n",expr) int main() { int x=7; int y=3; dprintf(x/y); return 0; } ``` I am getting output as x/y=2 I am confused how "x/y" is getting printed
In a macro the#stringifiesthe operands so#exprwill take the arguments and turn them into a string and since adjacent string literals are concatenated it will be then be concatenated to"=%d\n"so you end up with: ``` printf( "x/y" "=%d\n",expr) ``` which will become: ``` printf( "x/y=%d\n",expr) ``` For complete sak...
I'm confused with a problem about the pointer and array in C. Let's see a piece of code first: ``` //case 1 int **a; a = (int **)malloc(sizeof(int*)*m); for(i = 0; i < m; i++) a[i] = (int *)malloc(sizeof(int)*n); //case 2 int b[m][n]; ``` then, we known that, the layout ofbin memory is as follow: ``` b[0][0] ...
That's becausea[i][j]equals to*(*(a+i) + j). Even thoughais not consecutively stored (possibly), the pointer*(a+i)will exactly point to the right place (wherea[i][0]is stored).
I have some old code of mine which i dont understand why i did some thing . I have a pointer which isint_16t *q, of 1024 ints . now i am trying to copy it with : ``` buffersRing[ringNum][0]=inNumberFrames; memcpy(buffersRing[ringNum]+1, q, inNumberFrames * sizeof *q); ``` when first place in array is some int...
No, ``` buffersRing[ringNum]+1 // refers to a pointer to an array element ``` is not the same as ``` buffersRing[ringNum][1] // refers to the actual array element ``` The first one is the one you want.
With compiler C18 when I want to use a specific address for a string I use: In .C ``` #pragma romdata idsoft const rom unsigned char _app_nfo[31]= {"V0.0 No - 05/12/12"}; #pragma romdata ``` in linker: ``` CODEPAGE NAME=idsoft START=0x78E0 END=0x78FE ``` How can i do same with XC8? I've t...
You have just to do this: ``` unsigned char _app_nfo[31] @ 0x78E0 = {"V0.0 No - 05/12/12"}; ``` See5.5.4.2 ABSOLUTE OBJECTS IN PROGRAM MEMORYinMPLAB XC8 C Compiler User’s Guide
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ...
You have to remember that preprocessor macros are simply substituted. If you do e.g. ``` #define TRUE FALSE ``` then the processor simply replaces all places where it findsTRUEwill be replaced by whateverFALSEis defined to. So indeed it's a good definition. And yes it will most likely change the program workflow, p...
I have some doubt regarding the following code. ``` #include <stdio.h> #include <sys/types.h> int main(void) { int pid=fork(); if(pid==0) sleep(5); printf("Hello World %d %d\n",getpid(),pid); if(pid>0) while(1){sleep(1);} if(pid==0) printf("In child process!\n"); return 0; } ``` Will the chi...
In your example, the child process dies but the parent doesn't know about it'sexitstatus. As such, the child (nowzombie) is left in the process table. Moreover, the parent continues towaitfor the child and keeps running.
I am very beginner in c and I am reading now the classic example of the TicTacToe game. I am not sure about what thisreturnstatement does: ``` {..... return (ch == X) ?O :X; ``` This must be some conditional statement on the variable ch (that in my case stands for the player (X or O) but I am not sure about its...
It means ``` if (ch == X) return O; else return X; ```
I have complete project in C, which can be built with gcc or Visual Studio. There are no calls to external libraries. I would like to know how many functions there is in that project. There are no unused functions in source code, and the project comes with tests which run it with different params, so for a dynamic a...
Withgcc: ``` $ nm elf_file | grep "T " | grep -v " _" | wc -l ``` Note thatgcccan inline some functions even with optimizations disabled, so you should compile with: -O0 -fno-builtin -fno-inline-functions-called-once (-finline-functions-called-onceis enabled by default even in-O0)
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question Is it possible to assign an user specified name to an object. Usually we declareSample s;Can we accept the...
No, that's not possible (directly) in C. Variable names are a compile-time construct and don't really exist at runtime. The best you can do is make some kind of associative data structure, and map the user-provided strings to your objects there.
how to create an array of structures dynamically? ``` struct arr { int a; float b; } *p; p = (struct arr *)malloc(2*sizeof(struct arr)); for (i = 0; i < 2; i++) { scanf("%d %f", &p[i]->a, &p[i]->b); } for (i = 0; i < 2; i++) { printf("%d %f", p[i]->a, p[i]->b); } ``` this code did not work and pro...
Thep[i]is equivalent to*(p + i). There is a dereference operation taking place. That means you don't want to be using->. Just use.to access the fields: ``` scanf("%d %f", &p[i].a, &p[i].b); printf("%d %f",p[i].a, p[i].b); ``` Your solution is equivalent, but more complicated.a.bjust happens to be the same as(&a)->...
Are there some rules or pattern on how to write the terminal help menu of a program on linux? Usually I use these arguments:-?or-hor-Hto display the help of my program but is there a rule about that as well?
The output for--helpis not really a menu, just a help message. There are some coding rules, in particular theGNU coding standardsspecify something about--help(and also--version). I strongly suggest supporting both of them; as a user, I am pissed off by the few programs not understanding--help. And the GNU libc provi...
I'm converting thisCGFloat: ``` CGFloat verticalTranslation = CGFLOAT_MAX; ``` ... toNSUIntegerusing the following code: ``` if (verticalTranslation > NSUIntegerMax) unsignedInteger = NSUIntegerMax; else unsignedInteger = verticalTranslation; ``` It works. However, as soon as I replaceifwith ternary operator,unsig...
Why dont you try: ``` NSUInteger unsignedInteger = verticalTranslation > NSUIntegerMax ? NSUIntegerMax : (NSUInteger)verticalTranslation; ```
This question already has answers here:Why do we need C Unions?(20 answers)Closed10 years ago. I read this linkwhat-is-the-point-behind-unions-in-cBut this answer doesn't look enough to me. Can I have more explanations about uses of unions. I don't want any memory related examples like, this will take max 4 bytes (f...
Probably the two most common uses for a union are: To implement your ownVariant type, auniongives you the ability to represent all the varying types without wasting memory.This answergives a good example.Type punningbut I would readUnderstanding Strict Aliasingas well since there are many cases wheretype punningisund...
``` typedef char* string; int func1(string s); char* func2(); // returns a new memory/ if(func1(func2()) == 4) { // code } ``` Assuming func2() is only needed in the condition. Since i need to free newly allocated memory, how can i free it up within the same line(i.e. with the same condition or paranthesis) ? My mot...
To do this cleanly, make a new function that does the work in a clear manner: ``` static int func3() { char *s = func2(); int result = func1(s); free(s); return result; } … if (func3() == 4) … ``` (Presumably, there is some assurance thatfunc2successfully allocates memory. If not, you must test its ...
I am writing a simple program to add two complex number using struct. All goes well except that when printing the values, I get an error that I am dereferencing an incomplete pointer. Here is the code: ``` struct complexNumber * n1 = (struct complexNumber *) createNumber(10,10); struct complexNumber * n2 = (struct c...
You need toincludethe header fine, which definesstruct complexNumber.
I have an 8 bit integer for, example 20 (binary - 00010100). How could I go about finding the position of the ones in the number's binary representation? I could do it for a single one using powers of 2 but for multiple one's i'm stuck
You can just test each bit in a loop, e.g. ``` char val = 0x42; for (int i = 0; i < CHAR_BIT; ++i) printf("bit %d = %d\n", i, (val & (1 << i)) != 0); ``` or perhaps more succinctly: ``` for (int i = 0; i < CHAR_BIT; ++i) printf("bit %d = %d\n", i, (val >> i) & 1); ```
It's quite a simple question but has it's gotchas.So here it goes. Does each new Lua state created using the lua_newthread C API method get it's own individual LUA_REGISTRYINDEX accessible through it's new created Lua state or does it use a global shared LUA_REGISTRYINDEX?
All threads of the same Lua state share a single registry, as can be seen in thesource. Different Lua states have different registries.
Using theCprogramming language, what is the best way to make a multicore Red Hat Linux processor, use only one core in a test application?
There is aLinux system callspecifically for this purpose calledsched_setaffinity Forexample, to run on CPU 0: ``` #include <sched.h> int main(void) { cpu_set_t mask; CPU_ZERO(&mask); CPU_SET(0, &mask); result = sched_setaffinity(0, sizeof(mask), &mask); return 0; } ```
I'm struggling to understand why I get an error in the following code when trying to compile: ``` #include <stdlib.h> #include <stdio.h> int main() { puts(""); int i = 0; return 0; } ``` If I comment out theputs("");, it will compile. I'm usingVisual Studio, and I complie this as C Code, using/TC.
Visual Studio C is somewhat dated and usesC89. For C89, you must declareall of your variablesat the beginning of ascope block. In the case of your code above, this should work ``` int main() { int i = 0; puts(""); return 0; } ``` Note that you could also do the following ``` int main() { puts("");...
So I have the following code: ``` #include <math.h> int main (void) { float max = fmax (1.0,2.0); return 0; } ``` Which compiles and runs fine, but if instead of passing 1.0 and 2.0 to the function I pass a, b with those values: ``` #include <math.h> int main (void) { float a = 1.0; float b = 2.0; float max = fmax ...
In the first casefmaxprobably gets optimised away at compile time. In the second case it does not and you then get a link error. Without knowing what compiler you are using it's hard to give a specific remedy, but if it's gcc then you may need to add-lm, e.g. ``` c99 -Wall fmax_test.c -lm ``` Note also thatfmaxis fo...
I am using thisprogram herefor reference to see how the algorithm is implemented. I understand most of it except this part: ``` /* * update all the buckets. If bucket[8] has 2, * then there are 2 elements present till bucket 8 */ for (i = 1; i < 10; i++) bucket[i] = bucket[i] + bucket[i-1]; ``` I don't un...
This function is taking the cumulative sum, now bucket[i] contains the cumulative sum of itself and all buckets before it. What the comment means is that bucket[8] == 2 would mean that the sum from of buckets 0 to 8 = 2 Edit: Personally I thinkhttp://www.youtube.com/watch?v=Nz1KZXbghj8&noredirect=1has a great radix s...
Example: ``` struct dummy { int var; }; ``` Why structures like this are used? Mostly I have seen them in some header files. Theatomic_ttype is also defined like this. Can't it be defined simply using: ``` typedef int atomic_t; ```
It's more extensible. Assume that in the future, you realize thatstruct dummyshould contain a name field, then you can change the definition of it to: ``` struct dummy { int var; char name[30]; }; ``` without changing much of your application code.
``` typedef char* string; int func1(string s); char* func2(); // returns a new memory/ if(func1(func2()) == 4) { // code } ``` Assuming func2() is only needed in the condition. Since i need to free newly allocated memory, how can i free it up within the same line(i.e. with the same condition or paranthesis) ? My mot...
To do this cleanly, make a new function that does the work in a clear manner: ``` static int func3() { char *s = func2(); int result = func1(s); free(s); return result; } … if (func3() == 4) … ``` (Presumably, there is some assurance thatfunc2successfully allocates memory. If not, you must test its ...
I am writing a simple program to add two complex number using struct. All goes well except that when printing the values, I get an error that I am dereferencing an incomplete pointer. Here is the code: ``` struct complexNumber * n1 = (struct complexNumber *) createNumber(10,10); struct complexNumber * n2 = (struct c...
You need toincludethe header fine, which definesstruct complexNumber.
I have an 8 bit integer for, example 20 (binary - 00010100). How could I go about finding the position of the ones in the number's binary representation? I could do it for a single one using powers of 2 but for multiple one's i'm stuck
You can just test each bit in a loop, e.g. ``` char val = 0x42; for (int i = 0; i < CHAR_BIT; ++i) printf("bit %d = %d\n", i, (val & (1 << i)) != 0); ``` or perhaps more succinctly: ``` for (int i = 0; i < CHAR_BIT; ++i) printf("bit %d = %d\n", i, (val >> i) & 1); ```
It's quite a simple question but has it's gotchas.So here it goes. Does each new Lua state created using the lua_newthread C API method get it's own individual LUA_REGISTRYINDEX accessible through it's new created Lua state or does it use a global shared LUA_REGISTRYINDEX?
All threads of the same Lua state share a single registry, as can be seen in thesource. Different Lua states have different registries.
Using theCprogramming language, what is the best way to make a multicore Red Hat Linux processor, use only one core in a test application?
There is aLinux system callspecifically for this purpose calledsched_setaffinity Forexample, to run on CPU 0: ``` #include <sched.h> int main(void) { cpu_set_t mask; CPU_ZERO(&mask); CPU_SET(0, &mask); result = sched_setaffinity(0, sizeof(mask), &mask); return 0; } ```
I'm struggling to understand why I get an error in the following code when trying to compile: ``` #include <stdlib.h> #include <stdio.h> int main() { puts(""); int i = 0; return 0; } ``` If I comment out theputs("");, it will compile. I'm usingVisual Studio, and I complie this as C Code, using/TC.
Visual Studio C is somewhat dated and usesC89. For C89, you must declareall of your variablesat the beginning of ascope block. In the case of your code above, this should work ``` int main() { int i = 0; puts(""); return 0; } ``` Note that you could also do the following ``` int main() { puts("");...
So I have the following code: ``` #include <math.h> int main (void) { float max = fmax (1.0,2.0); return 0; } ``` Which compiles and runs fine, but if instead of passing 1.0 and 2.0 to the function I pass a, b with those values: ``` #include <math.h> int main (void) { float a = 1.0; float b = 2.0; float max = fmax ...
In the first casefmaxprobably gets optimised away at compile time. In the second case it does not and you then get a link error. Without knowing what compiler you are using it's hard to give a specific remedy, but if it's gcc then you may need to add-lm, e.g. ``` c99 -Wall fmax_test.c -lm ``` Note also thatfmaxis fo...
I am using thisprogram herefor reference to see how the algorithm is implemented. I understand most of it except this part: ``` /* * update all the buckets. If bucket[8] has 2, * then there are 2 elements present till bucket 8 */ for (i = 1; i < 10; i++) bucket[i] = bucket[i] + bucket[i-1]; ``` I don't un...
This function is taking the cumulative sum, now bucket[i] contains the cumulative sum of itself and all buckets before it. What the comment means is that bucket[8] == 2 would mean that the sum from of buckets 0 to 8 = 2 Edit: Personally I thinkhttp://www.youtube.com/watch?v=Nz1KZXbghj8&noredirect=1has a great radix s...
Example: ``` struct dummy { int var; }; ``` Why structures like this are used? Mostly I have seen them in some header files. Theatomic_ttype is also defined like this. Can't it be defined simply using: ``` typedef int atomic_t; ```
It's more extensible. Assume that in the future, you realize thatstruct dummyshould contain a name field, then you can change the definition of it to: ``` struct dummy { int var; char name[30]; }; ``` without changing much of your application code.
Using theCprogramming language, what is the best way to make a multicore Red Hat Linux processor, use only one core in a test application?
There is aLinux system callspecifically for this purpose calledsched_setaffinity Forexample, to run on CPU 0: ``` #include <sched.h> int main(void) { cpu_set_t mask; CPU_ZERO(&mask); CPU_SET(0, &mask); result = sched_setaffinity(0, sizeof(mask), &mask); return 0; } ```
I'm struggling to understand why I get an error in the following code when trying to compile: ``` #include <stdlib.h> #include <stdio.h> int main() { puts(""); int i = 0; return 0; } ``` If I comment out theputs("");, it will compile. I'm usingVisual Studio, and I complie this as C Code, using/TC.
Visual Studio C is somewhat dated and usesC89. For C89, you must declareall of your variablesat the beginning of ascope block. In the case of your code above, this should work ``` int main() { int i = 0; puts(""); return 0; } ``` Note that you could also do the following ``` int main() { puts("");...
So I have the following code: ``` #include <math.h> int main (void) { float max = fmax (1.0,2.0); return 0; } ``` Which compiles and runs fine, but if instead of passing 1.0 and 2.0 to the function I pass a, b with those values: ``` #include <math.h> int main (void) { float a = 1.0; float b = 2.0; float max = fmax ...
In the first casefmaxprobably gets optimised away at compile time. In the second case it does not and you then get a link error. Without knowing what compiler you are using it's hard to give a specific remedy, but if it's gcc then you may need to add-lm, e.g. ``` c99 -Wall fmax_test.c -lm ``` Note also thatfmaxis fo...
I am using thisprogram herefor reference to see how the algorithm is implemented. I understand most of it except this part: ``` /* * update all the buckets. If bucket[8] has 2, * then there are 2 elements present till bucket 8 */ for (i = 1; i < 10; i++) bucket[i] = bucket[i] + bucket[i-1]; ``` I don't un...
This function is taking the cumulative sum, now bucket[i] contains the cumulative sum of itself and all buckets before it. What the comment means is that bucket[8] == 2 would mean that the sum from of buckets 0 to 8 = 2 Edit: Personally I thinkhttp://www.youtube.com/watch?v=Nz1KZXbghj8&noredirect=1has a great radix s...
Example: ``` struct dummy { int var; }; ``` Why structures like this are used? Mostly I have seen them in some header files. Theatomic_ttype is also defined like this. Can't it be defined simply using: ``` typedef int atomic_t; ```
It's more extensible. Assume that in the future, you realize thatstruct dummyshould contain a name field, then you can change the definition of it to: ``` struct dummy { int var; char name[30]; }; ``` without changing much of your application code.
Here is a program to find prime numbers using sieve of Eratosthenes. The program is compiling but on execution, it becomes non responsive.The print statement itself is not executed. Can I know where I have gone wrong? ``` #include<stdio.h> int main() { printf("Enter the range"); int n,i; scanf("%d",&n); ...
Your program is infinite looping the first time through the loop. When i = 0 this loop never ends: ``` for(j=2;(i*j)<n;j++) ```
``` typedef union status { int nri; char cit[2]; }Status; int main() { Status s; s.nri = 1; printf("%d \n",s.nri); printf("%d,%d,\n",s.cit[0],s.cit[1]); } ``` OUTPUT: ``` 1 0,1 ``` I know this output on the second line is depend on the endianess of the CPU. How I can write such in a platfo...
You can usehtonl()and/orntohl().htonl()stands for "host to network long", whilentohl()stands for "network to host long". The "host" and "network" refers to the byte order. Network byte order is "big-endian". The operations will be no-ops if the host platform is also "big-endian". Using these routines, the following pr...
So I'm trying to translate this MIPS assembly code into C. I'm confused on a certain part of what's going on. Here is the MIPS assembly code: Assume we have variables f, g, h, i, j stored in $s0, $s1, $s2, $s3 and $s4, respectively. Assume the base addresses of arrays A and B are at $s6 and $s7 respectively and they c...
It's look like to calculate pointer to next element of A array, one line later you load data from this address. Assuming in C: ``` Word4Byte A[],B[]; B[g] = A[f] + A[f+1]; ```
What am I doing wrong, when I pass an IP address, or any IP, it always fails in the no host found block. Any assistance would be greatly appreciated. ``` struct in_addr ip; inet_aton(argv[1], &ip); he= gethostbyaddr((const void *)&ip,len,AF_INET); printf("%s \n", he->h_name); ```
The second argument ofgethostbyaddr()is the length of the passedbinaryaddress, solenshould besizeof(in_addr). Remark: You should consider to usegetnameinfo()instead, which is "more modern" and can handle both IPv4 and IPv6 addresses.
I'm having a problem casting, so is there a way to cast a type of: ``` char *result; ``` to a type of ``` char *argv[100]; ``` ? If so, how would I do this or is there a safe way to do this?
char * resultis a string and char * argv[100]is array of strings. You cannot convert string into array of strings. However, you can create an array of strings where the first array value is result. ``` argv[0] = result; ```
This question already has answers here:How can I access a shadowed global variable in C?(6 answers)Closed10 years ago. If we have a variable "x" which is defined globally and another variable with the same name "x" inside a function. when we print the value of "x" why we always get the value which is assigned inside ...
In other languages, yes. In C, there is no way to access the global in the same scope. There is a way to declare a nested scope (see other answers) which would give you access to a non-static global, but it is not recommended -don't do it. If you want to get the global variable, don't hide it with a local variable of ...
Is there anyway I can load a c pointer into a specific register like eax? I want to take an array, like int array[10], and load array (or &array[0], but either way they're the same thing) into register eax.
This is compiler dependent. Gcc has an extension to theregisterkeyword ``` register unsigned* p __asm__("eax") = a; ```
I have a struct containing an int variable. ``` typedef struct _details_t{ int id; int offset; int buff[4]; }details_t; ``` in the main I have attached the shared memory to the pointer which is of structure type as above ``` int set_shm_data(details_t** details){ if(NULL == details || *details == NULL){ ...
The problem is here: ``` *details->id = 345; ``` The->operator binds more tightly than*, so you need to use parentheses: ``` (*details)->id = 345; ```
Is there a way to get my Spotify play history using either their js or C APIs? I saw a couple of examples, but that was using their outdated API version.
Spotify play history is not available through any API. Disclaimer: I'm a Spotify employee.
I have been programming for a while, and it seems to me the following two if statements would produce identical result, but I always question it, can someone help me to resuve this question? ``` int x, y; if (x - y) { //some code } ``` vs ``` int x, y; if (x != y) ( // some code } ``` Thanks...
It depends on the type ofxandy. Assumingxandyare bothint, the two statements are not equivalent asx - ywould invoke undefined behavior if the result is not representable in anint. Assumingxandyare bothunsigned int, the two statements are equivalent (unsigned intdo no overflow).
Will it be precise to say that in ``` void f() { int x; ... } ``` "int x;" means allocatingsizeof(int)bytes on the stack? Are there any specifications for that?
Nothing in the standard mandates that there is a stack. And nothing in the standard mandates that a local variable needs memory allocated for it. The variable could be placed in a register, or even removed altogether as an optimization.
I have this function: ``` void update(int something, int nothing) { something = something+4; nothing = 3; } ``` And then the function call: ``` int something = 2; int nothing = 2; update(something, nothing); ``` Inside the function, something would be 6 and nothing would be 3, but because we do not return...
Send values using&and receive them using* Example: ``` void update(int* something, int* nothing) { *something = *something+4; *nothing = 3; } int something = 2; int nothing = 2; update(&something, &nothing); ``` Two years without using C, but I think this is correct.
I am developing a Python application that needs to spawn a child process (written in C) from time to time, to feed it some binary data and to get a reply. The child process will only be spawned when needed and will only serve one request. What are my options here? Is it safe to use stdin/stdout?
``` from subprocess import Popen,PIPE # Example with output only p = Popen(["echo", "This is a test"], stdout=PIPE) out, err = p.communicate() print out.rstrip() # Example with input and output p = Popen("./TestProgram", stdin=PIPE, stdout=PIPE) out, err = p.communicate("This is the input\n") print out.rstrip() ``` ...
I have a struct containing an int variable. ``` typedef struct _details_t{ int id; int offset; int buff[4]; }details_t; ``` in the main I have attached the shared memory to the pointer which is of structure type as above ``` int set_shm_data(details_t** details){ if(NULL == details || *details == NULL){ ...
The problem is here: ``` *details->id = 345; ``` The->operator binds more tightly than*, so you need to use parentheses: ``` (*details)->id = 345; ```
Is there a way to get my Spotify play history using either their js or C APIs? I saw a couple of examples, but that was using their outdated API version.
Spotify play history is not available through any API. Disclaimer: I'm a Spotify employee.
I have been programming for a while, and it seems to me the following two if statements would produce identical result, but I always question it, can someone help me to resuve this question? ``` int x, y; if (x - y) { //some code } ``` vs ``` int x, y; if (x != y) ( // some code } ``` Thanks...
It depends on the type ofxandy. Assumingxandyare bothint, the two statements are not equivalent asx - ywould invoke undefined behavior if the result is not representable in anint. Assumingxandyare bothunsigned int, the two statements are equivalent (unsigned intdo no overflow).
I'm usingVS2010to write somewin32app. I normally add .lib files to linkage using to project property manager. yet, sometimes, when I just want to test an API function , I don't want to modify my project file , but rather just add a removable line for linking with the required lib What is the linker keyword for linkin...
You can use#pragma commentcommand Example: ``` #pragma comment (lib, "d3d9.lib") ``` Another example: ``` #pragma comment (lib, "yourlibrary.lib") ``` Just put in hmm.. beforeint main(){} http://support.microsoft.com/kb/153901 http://msdn.microsoft.com/en-us/library/7f0aews7%28v=vs.71%29.aspx If there are prob...
I'm trying to execute via command line a code written in C. I tried gcc -o file file.c, but it did not work. I need to learn how to compile and execute a code using gcc and llvm without graphical interface. Furthermore when I compile the program I cannot find the executable file in Finder (there's no Developer folder ...
You can use xcrun tool: ``` #/usr/bin/xcrun cc -o file file.c ``` Note: if you have several Xcode versions you can chose with xcode-select and your command above will use compiler and the rest of the tools from the selected SDK.
I have created a program in C that will read the contents of a file, then output it into a new file. However, I need to extend this program to skip HTML tags. Can someone point me in the right direction as to what I'm supposed to do or how I should do it? All I know how to do is to skip characters separately, but how...
First, you set up a flag (call ithtml_flag) and set it to 0 (false). You can do this by declaring it as anint. As you go over each character, you output everything ifhtml_flagis0, till you hit the<character. At that point, you sethtml_flagto 1. You do not output any scanned characters if the flag is a 1. You turn...
I'm compiling a C code in Xcode 4.6.3, however I don't know which compiler I'm using. I need to use gcc 4.2. Thanks in advance.
If youreallyneed to change to gcc, you can do so in the build settings:
Why the result of ~10 is -11? Shouldn't it be 5 as the ~ operations flips every bit. 10 = 1010 ~10= 0101 //5 in decimal ``` #include<stdio.h> int main() { unsigned int b =10; b= ~b; printf("bitwise %d\n ",b); return 0; } ```
Many things wrong with this. You're bit-negating an unsigned int and then printing it as a signed int (%dis for signed integers). Print the result as an unsigned int and you will realize...on a 32bit-intmachine,10(decimal) is not1010(binary) but000000000000000000000000000001010.Finally, convert everything back to sig...
When I debug any program with debugger (for example OllyDbg), in disassembled assembly code, I can see function names, for example: ``` push 0 call msvcrt.exit ``` How does the debugger know the function names? Where do they come from? In machine code, it is represented ascall address. So how debugger knows it?
Compilers generate "symbols" files, providing to debuggers a way to show the name of a symbol that corresponds to a particular address or an offset. This is highly system-dependent: for example, VS toolchain on Windows places these symbols in separate .pdb files, while on some UNIX flavors these debug symbols are embe...