question
stringlengths
25
894
answer
stringlengths
4
863
the flow in my program callspthread_join(thread_id, nullptr);2 times for the samethread_idfrom the same calling thread. First time the call returns successfully but the second time it just hangs indefinitely. The documentation does not say clearly that it's forbidden to call pthread_join multiple times for the same thread_id. Is it indeed the case? I know that I can implement thread synchornization using pthread_cond_t but I would like to understand pthread_join limitations first.
Have a look at thedocumentation forpthread_join- in the Notes section it is stated that: Joining with a thread that has previously been joined results in undefined behavior. Lots of other good information on joining threads (and other aspects, if you search for some of the other pthread functions) in the link too.
There is a problem which confuses me a lot. ``` int main(int argc, char *argv[]) { int i = 12345678; return 0; } ``` ``` int main(int argc, char *argv[]) { int i = 0; return 0; } ``` The programs have the same bytes in total. Why? And where the literal value indeed stored? Text segment or other place?
The programs have the same bytes in total.Why? There are two possibilities: The compiler is optimizing out the variable. It isn't used anywhere and therefore doesn't make sense.If 1. doesn't apply, the program sizes are equal anyway. Why shouldn't they?0is just as large in size as12345678. Two variables of typeToccupy the same size in memory. And where the literal value indeed stored? On the stack. Local variables are commonly stored on the stack.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed7 years ago.Improve this question I have the basic knowledge of preprocessor.But i have never understood how it works.Can some body explain me how it works?I would prefer practical explanation.Thank you.
``` #define A 1234 ``` Literally as far as the compiler is concerned, every instance of A is now 1234. Its useful for code readability and modifieability. If you have a constant number for instance thats used in 7-8 different functions, you can #define it and use atokeninstead, and then change it in 1 place rather then 7-8. Alternatives to using #define are using constant variables or enums. ``` #define myVar 755 const int myVar = 755; enum{ myVar = 755 }; ``` Are all functionally equivalent in most cases.
This question already has answers here:What is the proper #include for the function 'sleep()'?(6 answers)Closed7 years ago. How can I sleep or pause the program excecution by a few seconds in C? I'm looking for something like this that is used in Java: ``` Thread.sleep(interval); ``` Is possible do this using C ? Thanks in advance.
``` #include <stdio.h> #include <unistd.h> int main (void){ sleep(3); return 0; } ``` Read morehere.
I am writing a program in c which traverse a tree in in-order, pre-order and post-order . this code is not compiling properly . it shows a error saying "unknown type name 'node'" ``` struct node { int value; node* left; node* right; }; struct node* root; struct node* insert(struct node* r, int data); void inOrder(struct node* r); void preOrder(struct node* r); void postOrder(struct node* r); ``` what i am missing ?
change inside structure ``` struct node { int value; struct node* left; //Changed struct node* right; }; ```
I want to find straight lines marked in the image, the coordinates point A, point B is the beginning and end of the segment. Please help me! img:enter image description heresource:enter image description here
It is called the "Hough Transform" You could experiment using something like Mathlab, and then implement it using opencv houghtransform. https://github.com/Itseez/opencv/blob/master/samples/cpp/houghlines.cpp
I am unable to usemicrocoaplibrary (https://github.com/1248/microcoap) in Arduino IDE. When I try to compile it produces following error ``` main-posix.c:1:24: fatal error: sys/socket.h: No such file or directory #include <sys/socket.h> ^ ``` This question has already been answered in (Cant use Micro-Coap library for arduino) but the answer doesn't make sense.
Delete that main-posix.c because this is necessary for linux, not Arduino. It will definitely work.
I have two files. I want to copy source file to destionation file. If they are different, then I just want to copy different line not all file. In the below case, two line are same, but destination has extra line. How can I just delete last line of destination file? For example: ``` Source File: test1 test2 Destionation File: test1 test2 test3 ```
On POSIX systems, if you want to delete some ending bytes in a file, you could useftruncate(2) There is no portable way to remove bytes in the middle of a file.
I created signals. One of them prints "1" 20 times. Another prints "2" 20 times.I want these signals to print their numbers in turn:1,2,1,2...But the program prints only "1".Can someone help me with that?
Run this code and see what when you send SIGUSR1 or SIGUSR2 to the pid printed. ``` #include <stdio.h> #include <signal.h> void handler1(int signal) { printf("Foo\n"); } void handler2(int signal) { printf("Bar\n"); } int main() { printf("PID: %d\n", getpid()); sigset(SIGUSR1,handler1); sigset(SIGUSR2,handler2); while (1); return(0); } ```
I have a string which is always has two forward slashes as/709/nviTemp1I would like to extract the/709/from that string and return it in char*, how would I use strstr for that purpose? I also might have many forward slashes in the path like/709/nvitemp1/d/s/ so I only need to get the first token/709/
You may try something like this: ``` char str[100] = "/709/nviTemp1"; char resu[100]; char *tmp; tmp = strchr(str+1, '/'); strncpy(resu, str, (size_t)(tmp - str) + 1); resu[(size_t)(tmp - str) + 1] = '\0'; ``` Thestrchrsearch the 1st '/', but starting atstr+1skips the real first one. Then compute "size" beetween start and found '/' and usestrncpyto copy stuff, and add a trailing '\0'.
I need the basic symbol jumping feature while I navigate my source code. I mean while I open a C source code folder into the VScode-0.9.1, then I want to jump to one function's definition usingF12orCtrl+Shift+O, there is no response forF12, or an error message like “unfortunately we have no symbol information for the file”. How can I get the symbol jump function? I think this is a basic and critical feature as a source code editor. Could you please give me some information or support? Thanks a lot!
There is currently no deeper language support for C files in Visual Studio Code. This will probably change in the future when the extension API for the editor will be public. For now you have only syntax highlighting for C files.
Why does gets() ask for string here. I mean, why doesn't it consume the newline character from the previous printf() and the program just terminate? And yes i know i should use fgets() and stuff like that. Please don't mention about it. code for reference- ``` #include <stdio.h> main() { char str[30]; printf("\n"); gets(str); puts(str); } ```
From the manual ofchar *gets(char *str): Reads a line from stdin and stores it into the string pointed to by, str. It stops when either the newline character is read or when the end-of-file is reached, whichever comes first. From the manual for printf : The functions printf() and vprintf() write output to stdout, the standard output stream; As the manual mentions,getsreads a line fromstdin. The functionprintfwrites tostdout. Thereforegetswon't read whatprintfis writing.
``` int n = 0; int temp = 0; while ((temp != 1) || (n <= 0)){ puts("enter array count"); temp = scanf("%d", &n); printf("\n%d\n", temp); } ``` I need to check input value for the fact it must be an integer and be > 0. scanfreturns count of success set values and if it's not an integer it will return 0. So the problem is that when I'm typing any char except number it starts non-finished cycle Why?
When you type something invalid, such as a character, forscanf("%d", &n);, thescanffails, returns 0, andleaves the invalid data in thestdin. In the next iterationscanfsees this invalid data prevailing in thestdin, fails again and this process is repeated. The fix is to clear thestdinin each iteration of the loop. Add ``` int c; while((c = getchar()) != '\n' && c != EOF); ``` or ``` scanf("%*[^\n]"); scanf("%*c"); ``` just after thescanfto clear thestdin.
I want to set a a break-point in the C implementation for model.matrix. I tried Selva's solution inHow can I view the source code for a function?: ``` > debug(C_modelmatrix) Error in debug(C_modelmatrix) : object 'C_modelmatrix' not found > debug(modelmatrix) Error in debug(modelmatrix) : object 'modelmatrix' not found ``` The function I'm interested can be foundhere. ``` SEXP modelmatrix(SEXP call, SEXP op, SEXP args, SEXP rho ``` I'm building and running from R source code. How do I set a break-point?
There is still-useful video tutorial by Seth Falcon onhow to debug R packages with native codewhich shows this. In essence, launchRwithR -d gdbto invoke thegdbdebugger which you then instruct to set breakpoints in the right places. If you (or your operating system) prefers a different compiler, youobviouslyneed to substitute it in the invocation:R -d lldb.
``` char *name= "tony"; name[2] = 'z'; printf("%s",name); ``` why does this give me a bus error 10? and what does it mean? This book tells me its because "tony" string literal is saved in read only memory and you can't alter it, but i don't understand because i can do things like this.. ``` char *name= "tony"; name = "another"; printf("%s",name); ``` In this case i just changed the read only memory and it works fine. Thanks pointer give me a headache
``` char *name= "tony"; name = "another"; printf("%s",name); ``` In this case you did not change the data in the read only memory. You just madenamepointer to point to another read only memory (where "another" is stored). ``` char *name= "tony"; name[2] = 'z'; printf("%s",name); ``` In this case, you are actually editing the data stored in the read only memory.
I'm brand new to working with c. I've got a file with the following format style: ``` number:number,number,number ``` Is there anyway I can usefscanfto obtain the numbers from the file? My code below is not working: ``` fscanf(file,"%d%[^:]:%d%[^,],%d%[^,],%d",&one,something,&two,something3,&three,something4,&four); ```
You don't need the%[^:]parts there, you can put delimiters into the format string directly: ``` int a, b, c, d; while (scanf("%d:%d,%d,%d",&a,&b,&c,&d) == 4) { printf("%d %d %d %d\n", a, b, c, d); } ``` Demo.
``` int n = 0; int temp = 0; while ((temp != 1) || (n <= 0)){ puts("enter array count"); temp = scanf("%d", &n); printf("\n%d\n", temp); } ``` I need to check input value for the fact it must be an integer and be > 0. scanfreturns count of success set values and if it's not an integer it will return 0. So the problem is that when I'm typing any char except number it starts non-finished cycle Why?
When you type something invalid, such as a character, forscanf("%d", &n);, thescanffails, returns 0, andleaves the invalid data in thestdin. In the next iterationscanfsees this invalid data prevailing in thestdin, fails again and this process is repeated. The fix is to clear thestdinin each iteration of the loop. Add ``` int c; while((c = getchar()) != '\n' && c != EOF); ``` or ``` scanf("%*[^\n]"); scanf("%*c"); ``` just after thescanfto clear thestdin.
I want to set a a break-point in the C implementation for model.matrix. I tried Selva's solution inHow can I view the source code for a function?: ``` > debug(C_modelmatrix) Error in debug(C_modelmatrix) : object 'C_modelmatrix' not found > debug(modelmatrix) Error in debug(modelmatrix) : object 'modelmatrix' not found ``` The function I'm interested can be foundhere. ``` SEXP modelmatrix(SEXP call, SEXP op, SEXP args, SEXP rho ``` I'm building and running from R source code. How do I set a break-point?
There is still-useful video tutorial by Seth Falcon onhow to debug R packages with native codewhich shows this. In essence, launchRwithR -d gdbto invoke thegdbdebugger which you then instruct to set breakpoints in the right places. If you (or your operating system) prefers a different compiler, youobviouslyneed to substitute it in the invocation:R -d lldb.
``` char *name= "tony"; name[2] = 'z'; printf("%s",name); ``` why does this give me a bus error 10? and what does it mean? This book tells me its because "tony" string literal is saved in read only memory and you can't alter it, but i don't understand because i can do things like this.. ``` char *name= "tony"; name = "another"; printf("%s",name); ``` In this case i just changed the read only memory and it works fine. Thanks pointer give me a headache
``` char *name= "tony"; name = "another"; printf("%s",name); ``` In this case you did not change the data in the read only memory. You just madenamepointer to point to another read only memory (where "another" is stored). ``` char *name= "tony"; name[2] = 'z'; printf("%s",name); ``` In this case, you are actually editing the data stored in the read only memory.
I'm brand new to working with c. I've got a file with the following format style: ``` number:number,number,number ``` Is there anyway I can usefscanfto obtain the numbers from the file? My code below is not working: ``` fscanf(file,"%d%[^:]:%d%[^,],%d%[^,],%d",&one,something,&two,something3,&three,something4,&four); ```
You don't need the%[^:]parts there, you can put delimiters into the format string directly: ``` int a, b, c, d; while (scanf("%d:%d,%d,%d",&a,&b,&c,&d) == 4) { printf("%d %d %d %d\n", a, b, c, d); } ``` Demo.
I know that i C , you always have to add a null terminator\0so that the processor knows when a word was ended . But i get hard time to understand when you have to do it . so for example this code works for me without it : ``` char connectcmd[50]={0}; sprintf(connectcmd,"AT+CWJAP=\"%s\",\"%s\"",MYSSID,MYPASS); ``` How is that possible ? When do you really have to add them ?
sprintfalways terminates it withnull character, so no need to mannually add it. From C99 standard - 7.21.6.6 The sprintf function[...]A null character is written at the end of the characters written; it is not counted as part of the returned value. If copying takes place between objects that overlap, the behavior is undefined.
I want to know there are how many functions I can call in C library, e.g. Gnu C library? or Approximately?
If you are in unix like OS, you can usenmutility, part ofgnu binutils. In my cygwin environment,nmlists 1570 symbols defined in the text section. ``` % nm -C /usr/lib/libc.a | grep -w T | wc -l 1570 ``` Let's exclude the_variants ``` % nm -C /usr/lib/libc.a | grep -w T | grep -v _ | wc -l 751 ``` If you are on windows, trydumpbinutility. ``` % dumpbin /exports msvcr110.dll ``` -Cin thenmcommand demangles the symbol names. I do not know how to getdumpbinto print original symbol names. If anyone knows how to, please suggest. Some functions might be defined in another object file - like libm for math, libnsl for network services etc. To be sure, also look at the library documentation/source.
I looked up the manual of iso_8859-1 and found the degree symbol: ``` Oct Dec Hex Char Description 260 176 B0 ° DEGREE SIGN ``` Code: ``` int main( int argc, char *argv[]) { char chr = 176; //stores the extended ASCII of a symbol printf("Character with an ascii code of 251: %c \n", chr); return 0; } ``` But it printed out as?. How could I output a degree symbol in a C programme? Do I need to include some files?
the ASCII code for the degree celsius is 248. You can declare this as a char in C. ``` #include<stdio.h> void main() { char ch=248; printf("Today's temperature was 23%cC",ch); } ```
This question already has answers here:C : #define usage [duplicate](3 answers)Closed7 years ago. ``` #include <stdio.h> #define SQR(x) x*x int main() { printf("%d",225/SQR(15)); return 0; } ``` The output to this code is 225. I'm unable to understand as what really is happening here. If I use#define SQR(x) (x*x)Then it works fine which i get as we are supposed to use parentheses if we have an expression with some operator. But in the previous case I'm not clear as to what is really happening. Why is the answer 225?
#definemacros aren't functions - they are just macros, text replacement. If you take the expression225/SQR(15)and replaceSQRwith15*15, you'll get225/15*15, and since/and*have the save precedence and are left associative -255/15*15 = 255.
So the question in one of my assignments is: .. A function whose signature is int int2seq( bool* X, int8_t x ); that should extract and then store each i-th bit of x in the i-th element of array X; it should return the total number of elements stored. my Question is What is thebool* XI've never come across it before,it sounds like a boolean value,but is it supposed to behave like an array?
I think you need to seethisit will help you to understand bool in C. In your casebool *Xpointer to bool array is what I understand. But it also can point to single variable also.
When I am trying to generate a random number 0 throughint: ``` //Populate Currently Allocated Reasource for each customer for (i = 0; i < NUMBER_OF_CUSTOMERS; i++) { printf("%d:[ ",i); for (j = 0; j < NUMBER_OF_RESOURCES; j++) { allocation[i][j] = rand() % maximum[i][j]; printf("%d ",allocation[i][j]); } printf("] \n\n"); } ``` I get a floating point exception whenmaximum[i][j]is 0. Are there any better means of creating a random number without thefloating point errorcaused byrand() % 0? EDIT: When maximum is 0, the random number output should just be 0.
Takinga % bgives you the remainder whenais divided byb. As such, it will always give you a result that is less thanb, and it doesn't work whenbis zero, because you can't divide by zero. If you want a random number between 0 andx, you need to takerand() % (x + 1).
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.Closed7 years ago.Improve this question How to create the left and right aligned printout of the string by placing exactly the required number of characters (including white spaces) per line. For example, given: ``` Hello world! And so on ``` output should be: ``` Hello world! And so on ```
Here is something you can start with: ``` function strReplace(char str[]) { char s[STR_LEN); int i; for(i = 0, j = 0; i < STR_LEN; ++i, ++j) { if(str[i++] == ' ') s[j++] = '\t'; s[j] = str[i]; } } ``` what this will do is insert `\t' into string instead of ' ' which in turn will add up to n spaces and alight each word like to form of a grid.
I know that i C , you always have to add a null terminator\0so that the processor knows when a word was ended . But i get hard time to understand when you have to do it . so for example this code works for me without it : ``` char connectcmd[50]={0}; sprintf(connectcmd,"AT+CWJAP=\"%s\",\"%s\"",MYSSID,MYPASS); ``` How is that possible ? When do you really have to add them ?
sprintfalways terminates it withnull character, so no need to mannually add it. From C99 standard - 7.21.6.6 The sprintf function[...]A null character is written at the end of the characters written; it is not counted as part of the returned value. If copying takes place between objects that overlap, the behavior is undefined.
I want to know there are how many functions I can call in C library, e.g. Gnu C library? or Approximately?
If you are in unix like OS, you can usenmutility, part ofgnu binutils. In my cygwin environment,nmlists 1570 symbols defined in the text section. ``` % nm -C /usr/lib/libc.a | grep -w T | wc -l 1570 ``` Let's exclude the_variants ``` % nm -C /usr/lib/libc.a | grep -w T | grep -v _ | wc -l 751 ``` If you are on windows, trydumpbinutility. ``` % dumpbin /exports msvcr110.dll ``` -Cin thenmcommand demangles the symbol names. I do not know how to getdumpbinto print original symbol names. If anyone knows how to, please suggest. Some functions might be defined in another object file - like libm for math, libnsl for network services etc. To be sure, also look at the library documentation/source.
I looked up the manual of iso_8859-1 and found the degree symbol: ``` Oct Dec Hex Char Description 260 176 B0 ° DEGREE SIGN ``` Code: ``` int main( int argc, char *argv[]) { char chr = 176; //stores the extended ASCII of a symbol printf("Character with an ascii code of 251: %c \n", chr); return 0; } ``` But it printed out as?. How could I output a degree symbol in a C programme? Do I need to include some files?
the ASCII code for the degree celsius is 248. You can declare this as a char in C. ``` #include<stdio.h> void main() { char ch=248; printf("Today's temperature was 23%cC",ch); } ```
This question already has answers here:C : #define usage [duplicate](3 answers)Closed7 years ago. ``` #include <stdio.h> #define SQR(x) x*x int main() { printf("%d",225/SQR(15)); return 0; } ``` The output to this code is 225. I'm unable to understand as what really is happening here. If I use#define SQR(x) (x*x)Then it works fine which i get as we are supposed to use parentheses if we have an expression with some operator. But in the previous case I'm not clear as to what is really happening. Why is the answer 225?
#definemacros aren't functions - they are just macros, text replacement. If you take the expression225/SQR(15)and replaceSQRwith15*15, you'll get225/15*15, and since/and*have the save precedence and are left associative -255/15*15 = 255.
So the question in one of my assignments is: .. A function whose signature is int int2seq( bool* X, int8_t x ); that should extract and then store each i-th bit of x in the i-th element of array X; it should return the total number of elements stored. my Question is What is thebool* XI've never come across it before,it sounds like a boolean value,but is it supposed to behave like an array?
I think you need to seethisit will help you to understand bool in C. In your casebool *Xpointer to bool array is what I understand. But it also can point to single variable also.
Assume there is a structfakes: ``` struct fakes { .... }; ``` And there is a pointer: ``` struct fakes *fakes; ``` I'm wondering whethersizeof(struct fakes)andsizeof(*fakes)are the same.
I'm wondering whethersizeof(struct fakes)andsizeof(*fakes)are the same. Yes, they are guaranteed to be the same.
I want to generate five random numbers each time using srand() function within the range 1 to 10. Here is a sample program: ``` #include<stdio.h> #include<math.h> #define size 10 int main() { int A[5]; for(int i=0;i<5;i++) { A[i]=srand()%size } } ``` But I am getting an error saying too few arguments for the function srand(). What will be the solution?
srandsets the seed forrand, the pseudo-random number generator. Corrected code: ``` #include <stdio.h> #include <math.h> /* Unused header */ #include <stdlib.h> /* For `rand` and `srand` */ #include <time.h> /* For `time` */ #define size 10 int main() { int A[5]; srand(time(NULL)); /* Seed `rand` with the current time */ for(int i = 0; i < 5; i++) { A[i] = rand() % size; // `rand() % size` generates a number between 0 (inclusive) and 10 (exclusive) } } ```
What is the difference between ``` float f = (float) 99.32 ; ``` and ``` float f = 99.32f ; ``` Both of them compiled and ran successfully.
``` float f = 99.32f ; ``` That is afloatliteral, which means a float variable being assigned with afloatvalue directly. ``` float f = (float) 99.32 ; ``` That is afloatvariable that is assigned adoublevalue that is cast tofloatbefore being assigned.
This question already has answers here:What does void* mean and how to use it?(10 answers)Closed7 years ago. I'm learning about dynamics data structure e.g.mallocfunction. Why sometimes programmers usevoid*as a pointer parameter to (for example) dynamic variables of integers and chars? What are the differences? What are the advantages?
Every pointer type can be cast tovoid*safely. Generic functions that need to work with pointers of all sorts of objects, such asmallocandrealloccan work only if they usevoid*in their interface.
Say if I concatenate one string to another, check if it has passed the line length limit, and if it has passed that limit is there a way to un-concatenate it?
If you concatenate a string and it passes the length limit, it is usually too late to undo it: assuming that the limit is based on the size of allocated memory, concatenation causesundefined behavior. At this point it's all over: your program may crash or do other unexpected things. That is why you need to check the limitbeforeperforming concatenation, and if the new length is over the limit, do not perform concatenation.
Suppose I have a text file which has three lines: apple man womanpearbanana I used ``` char name[100]; fgets(name,100,inputfile) ``` So nownameshould be "apple man woman"`. All three words separates by blank spaces, right? I want to put these three words in a singlearray. I think I need to usefgetsbut I'm new to C language and I don't know how. Can someone give me an example on how to store this?
``` #include <stdio.h> #include <string.h> int main(void){ char name[] = "apple man woman"; char *array[sizeof(name)/2]; int n = 0; for(char *word = strtok(name, " \t\n"); word; word = strtok(NULL, " \t\n")){ array[n++] = word; } for(int i = 0; i < n; ++i) puts(array[i]); return 0; } ```
What is the difference between ``` float f = (float) 99.32 ; ``` and ``` float f = 99.32f ; ``` Both of them compiled and ran successfully.
``` float f = 99.32f ; ``` That is afloatliteral, which means a float variable being assigned with afloatvalue directly. ``` float f = (float) 99.32 ; ``` That is afloatvariable that is assigned adoublevalue that is cast tofloatbefore being assigned.
This question already has answers here:What does void* mean and how to use it?(10 answers)Closed7 years ago. I'm learning about dynamics data structure e.g.mallocfunction. Why sometimes programmers usevoid*as a pointer parameter to (for example) dynamic variables of integers and chars? What are the differences? What are the advantages?
Every pointer type can be cast tovoid*safely. Generic functions that need to work with pointers of all sorts of objects, such asmallocandrealloccan work only if they usevoid*in their interface.
Say if I concatenate one string to another, check if it has passed the line length limit, and if it has passed that limit is there a way to un-concatenate it?
If you concatenate a string and it passes the length limit, it is usually too late to undo it: assuming that the limit is based on the size of allocated memory, concatenation causesundefined behavior. At this point it's all over: your program may crash or do other unexpected things. That is why you need to check the limitbeforeperforming concatenation, and if the new length is over the limit, do not perform concatenation.
Suppose I have a text file which has three lines: apple man womanpearbanana I used ``` char name[100]; fgets(name,100,inputfile) ``` So nownameshould be "apple man woman"`. All three words separates by blank spaces, right? I want to put these three words in a singlearray. I think I need to usefgetsbut I'm new to C language and I don't know how. Can someone give me an example on how to store this?
``` #include <stdio.h> #include <string.h> int main(void){ char name[] = "apple man woman"; char *array[sizeof(name)/2]; int n = 0; for(char *word = strtok(name, " \t\n"); word; word = strtok(NULL, " \t\n")){ array[n++] = word; } for(int i = 0; i < n; ++i) puts(array[i]); return 0; } ```
In one of my assignments I am seeing this line used: ``` int index = -1, k; ``` Im not sure what is happening when there are to entries for the one variable. What exactly is the variable "index" holding when it has two entries?
This is the definition of 2 variables, both of the same typeint:indexandk. Onlyindexis initialized with-1, andkis left un-initialized.
Say if I concatenate one string to another, check if it has passed the line length limit, and if it has passed that limit is there a way to un-concatenate it?
If you concatenate a string and it passes the length limit, it is usually too late to undo it: assuming that the limit is based on the size of allocated memory, concatenation causesundefined behavior. At this point it's all over: your program may crash or do other unexpected things. That is why you need to check the limitbeforeperforming concatenation, and if the new length is over the limit, do not perform concatenation.
Suppose I have a text file which has three lines: apple man womanpearbanana I used ``` char name[100]; fgets(name,100,inputfile) ``` So nownameshould be "apple man woman"`. All three words separates by blank spaces, right? I want to put these three words in a singlearray. I think I need to usefgetsbut I'm new to C language and I don't know how. Can someone give me an example on how to store this?
``` #include <stdio.h> #include <string.h> int main(void){ char name[] = "apple man woman"; char *array[sizeof(name)/2]; int n = 0; for(char *word = strtok(name, " \t\n"); word; word = strtok(NULL, " \t\n")){ array[n++] = word; } for(int i = 0; i < n; ++i) puts(array[i]); return 0; } ```
In one of my assignments I am seeing this line used: ``` int index = -1, k; ``` Im not sure what is happening when there are to entries for the one variable. What exactly is the variable "index" holding when it has two entries?
This is the definition of 2 variables, both of the same typeint:indexandk. Onlyindexis initialized with-1, andkis left un-initialized.
I am encountering this weird message at the moment with my file. I have a very basic C file that reads from a file and outputs upon request. I am running the following command in Linux: ``` filename <filenametest.txt >filenameoutput ``` and it brings the following message: ``` filename: command not found ``` Any idea why it's not working? Really frustrating.
Assuming thatfilenameis the name of the executable generated on compiling your C code, maybe you should try using ./filename < filename.txt > filenameoutput. Sincefilenameis not in the search path by default.
I am attempting to create a two dimensional array of strucs, albeit not in the most pretiest of ways, and am running into some syntax errors. My code is as follows: ``` struct Page { char Column[4]; int variable; }; ``` . . . ``` int main() { struct Page Test[2][2]; Test[0][0].Column = "ABC"; Test[0][0].variable = 124; Test[0][1].Column = "DEF"; Test[0][1].variable = 368; Test[1][0].Column = "GHI"; Test[1][1].variable = 763; } ``` When compiling I get this error: syntax error before '.' token <-- this is for every declaration of Test[x][x].whatever. What exactly did I declare incorrecly?
The assignment operator cannot be used with arrays in C. You could use initialization instead (which is not assignment despite using the=symbol): ``` struct Page Test[2][2] = { { "ABC", 124 }, { "DEF", 368 }, { "GHI", 763 } }; ```
I would like to determine during compile time what the specified TARGET_PLATFORM has been specified. As an example, I would like to do something like the following: ``` #if (TARGET_PLATFORM == 21) #include <sys/system_properties.h> #else #include <sys/_system_properties.h> #endif ``` I would prefer an ndk built-in preprocessor, but other alternatives are also welcome. Thanks!
``` #include <android/api-level.h> #if __ANDROID_API__ == 21 .... #else .... #endif ```
Why this code is showing Segmentation fault (core dumped)? ``` #include<stdio.h> void swap(int*,int*); int main(){ int x=5,y=10; swap(&x,&y); printf("%d%d",x,y); return 1; } void swap(int *a,int *b){ int *temp; *temp = *a; *a = *b; *b = *temp; } ```
int *temp;is the problem. It is not pointing to any memory that you own. The behaviour on dereferencingtempis undefined. Useint temp;instead, (preferablyint temp = *a;since thentempis never in an uninitialised state) andtemprather than*tempin the assignments. (By the way,0is conventionally the return value frommainthat indicates success.)
How to generate assembly from a cross-compiled binary? Compile command used is: ``` arm-none-linux-gnueabi-gcc test.c -o test ``` How can I disassemble the binarytest? I have used: ``` objdump -d test -m arm ``` But it says: ``` test: file format elf32-little objdump: can't use supplied machine arm ``` Any help?
GCC generates the assembly already, you only need to tell it not to throw the files away when finished: ``` arm-none-linux-gnueabi-gcc -save-temps test.c -o test ``` Note that the generated files will only contain the assembly language of your code and not the stuff that is linked in from the C libraray, e.g. forprintf(). To see the full disassembly including library code, you can usearm-none-linux-gnueabi-objdump -d test. Side note: "test" is a bad example binary name, as there is a binary namedtestalready in/bin/or/usr/bin/on any unix or linux system.
I am using google test and google mock to test some C code: ``` struct msghdr message; int retval; retval = recvmsg(fd,&message,0); if(retval == EINTR || retval == EAGAIN) { // do something here } ``` in my mock file, I mocked therecvmsgfunction: ``` MOCK_CONST_METHOD3(recvmsg, int(int fd, struct msghdr *msg, int flags)); ``` but how to set theerrnoas EINTR orEAGAINwhen I set the return value of the mock functionrecvmsgas -1?
There is a standard action calledSetErrnoAndReturn(errnum, value)which is described inGoogle Mock docs.
I have a client server system using MPI (using ports) in C++. Its running good. Is doing what I intend it to do. I recently read about remote memory access (RMA) in MPI usingMPI_Winmemory windows. I'm wondering if it is possible to create a system similar to client-server using RMA. (Lets say the synchronization between the clients to access same chunk of memory is handled somehow.) I would like to create a window on the server and make the clients access memory through this window. Does someone already have some experience with this model? Any comments are welcome.
Creation of RMA windows is a collective operation that involves the process group of an intracommunicator. To make it work with an intercommunicator, you must first merge the two process groups viaMPI_INTERCOMM_MERGEand then use the resultant intracommunicator for RMA operations. Note that doing so removes part of the insulation benefits that intercommunicators provide.
How do you make a code in C that will output this sequence? ``` 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ``` ...easy! ``` #include <stdio.h> int main(){ int f = 10, s = 1; while (s <= 5) printf("%d %d ",f--,s++); getch(); } ``` There are many ways to do it, but as you might have noticed, it uses two variables. So how do you re-create this using only ONE variable?
This is your code using a single var: ``` int main() { int s = 1; while (s <= 5) { printf("%d %d ", (11-s), s); s++; } printf("\n"); } ```
I'm trying to send the child process a blank(SIGUSR1) signal from the parent. As far as I know, I have the signal set up properly. I feel like I am messing up on the Kill() function call. I expect some sort of printed output, but I get nothing. Not from inside the child nor from the signal function itself. code: ``` void my_handler(int signum); int main() { pid_t pid; if((pid = fork()) == -1) { printf("Error on fork().\n"); exit(1); } if(pid == 0) { if(signal(SIGUSR1, my_handler)) { printf("+1"); } } else if(pid > 0) { sleep(2); kill(pid, SIGUSR1); } } void my_handler(int signum) { if (signum == SIGUSR1) { printf("Received SIGUSR1!\n"); } } ```
The child process exits before the parent process has a chance to send a signal to it. Try addingsleep(5)in the child process after callingsignal.
I'm trying to make a single makefile file that compiles two different set of files. Is this posible? What I tried so far is: ``` target1: OBJ = foo1.o foo2.o target1: application target2: OBJ = foo3.o foo4.o target2: application application: $(OBJ) $(LD) $(OBJ) ``` What happens is thatLDis called with the correct parameters but make never actually checks the dependencies therefore the implicit rules that compile .c files to .o are never executed so linker fails with: ``` ld: cannot find foo1.o: No such file or directory ld: cannot find foo2.o: No such file or directory ``` What is the right way to do this?
You could go with this for instance (considering you won't call make with multiple target at once): ``` OBJ := foo1.o foo2.o ifeq "$(MAKECMDGOALS)" "target2" OBJ := foo3.o foo4.o endif target1 target2: application application: $(OBJ) $(LD) $^ ```
I want to compile this code: ``` #include <stdalign.h> #include <stdio.h> #include <stddef.h> int main ( int argc , char ** argv ) { printf ("%zu\n", alignof ( max_align_t )); return 0; } ``` But compiler says that: ``` error: ‘max_align_t’ undeclared". ``` stddef.his included and everything must be ok, isn't it? P.S. I already tried to compile this code under gcc4.8 and gcc4.9, but I have error as described.
To use a C11 feature you need to tell the compiler to run in C11 compliant mode. For gcc this can be achieved by specifying the option-std=c11.
Is there any difference in below two castings ? ``` int a=10; int *p=&a; (void)p; //does not give any warning or error ``` or ``` (void *)p; //error: statement with no effect [-Werror=unused-value] ``` when complied withgcc -Wall -Werror --std=c99 -pedantic Just saw that in this answer.(clearly I misunderstood something )
When you do ``` (void) p; ``` You tell the compiler to simply disregard the result of the expressionp. It's effectively the same as an empty statement: ``` ; ``` When you do ``` (void *) p; ``` You tell the compiler to treat the variablepas a generic pointer, and that's the full expression for the statement, an expression which doesn't really do anything and you get the error message.
I'm working with an external project that uses.cfile extension for C++ files (they will not change this, I have even sent them a full patch). Is there any way to force Eclipse (autotools project) to index all.c/.hfiles as C++?
Enter in Preferences->C/C++->FileTypes You can see the file association there. It doesn't let me change it in my Eclipse Luna CDT, but what you can do is to override it per project. Properties->C/C++ General->FileTypes->Use project settings
I wrote a simple C socket program that sends an INIT package to the server to indicate to prepare a text transfer. The server does not sends any data back at that time. After sending the INIT package the client sends a GET package and waits for chunks of data from the server. So every time the server receives a GET package it will send a chunk of data to the client. So far so good. The buffer has a size of 512 bytes, a chunk is 100 Bytes plus a little overhead big. But my problem is that the client does not receive the second message. So my guess is that read() will blpck until the buffer is full. Is that right or what might be the reason for that?
It depends. For TCP socketsreadmay return before the buffer is full, and you may need to receive in a loop to get a whole message. For UDP sockets the size you read is typically the size of a single packet (datagram) and thenreadmay block until it has read all the requested data.
i don't know where is the problem i'm assigning the address to other 2 dimensional array. Please help me to fix this problem ``` int main() { int a[3][2]; int b[2]={0,1}; a[2]=b; return 0; } ``` prog.cpp:8:9: error: invalid array assignment
You can't copy an array using=. Neither can you assign an array's address;x = y;doesn't work either whenxandyhave typeschar[1]for example. To copy the contents ofbtoa[2], usememcpy: ``` memcpy(a[2], b, sizeof(a[2])); ```
The following code fails becauseatoi()requires achar *and I'm only passing achar. I want to store the value of only the first digit. Any idea how I can do this? ``` int main () { char a[]= "123"; int b = atoi(a[0]); printf("%d",b); } ``` Here's the exact error message: ``` division.c:9:16: warning: incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'; take the address with & [-Wint-conversion] int b = atoi(a[0]); ^~~~ & ```
Yeah, a single character is not a string asatoi()requires. If you just want the value of the single digit, you can do it like this: ``` int b = (a[0] - '0'); ```
The following code fails becauseatoi()requires achar *and I'm only passing achar. I want to store the value of only the first digit. Any idea how I can do this? ``` int main () { char a[]= "123"; int b = atoi(a[0]); printf("%d",b); } ``` Here's the exact error message: ``` division.c:9:16: warning: incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'; take the address with & [-Wint-conversion] int b = atoi(a[0]); ^~~~ & ```
Yeah, a single character is not a string asatoi()requires. If you just want the value of the single digit, you can do it like this: ``` int b = (a[0] - '0'); ```
I was working with IAR Embedded Workbench, using C language. I had some trouble while dividing my project into the usual main/.h/.c form. For example, if i create an example.h ``` #ifndef EXAMPLE_H #define EXAMPLE_H void function(int [], int); #endif ``` And than an example.c ``` #include "example.h" void function (int[] array, int number) {number = 1; //code } ``` It says: ``` Error[Pe147]: declaration is incompatible with "__interwork __softfp void function(int *, int)" (declared at line 4 of (path) Error[Pe141]: unnamed prototyped parameters not allowed when body is present (path) Error[Pe020]: identifier "number" is undefined (path) Error while running C/C++ Compiler ```
The problem is invoid function(int [], int). Change tovoid function(int name[], int)orvoid function(int *, int). Another error is inint[] array- it has to beint array[]orint * array.
The docs don't really say whatstatusis. What exactly isstatus? http://man7.org/linux/man-pages/man2/exit_group.2.html
From theexit(3) man page: The C standard specifies two constants,EXIT_SUCCESSandEXIT_FAILURE, that may be passed to exit() to indicate successful or unsuccessful termination, respectively. which is mentioned on the group_exit page you referred to. I think it is a typo that it is equivalent toexit(2)because there is no exit(2), only exit(3) in the standard library. I've confirmed this by reading the stdlib6 source code. Sincegroup_exit(2)is claimed equivalent toexitthat meansstatushas two defined values and all the rest (up to 255) are up to your definition. The rule still holds though, anything but EXIT_SUCCESS represents a failure of the program.
This question already has answers here:Most efficient way to create a zero filled JavaScript array?(45 answers)Closed7 years ago. If I make this line in C\C++: ``` int myArray[10] = { 0 }; // all elements 0 ``` I will have an array of ten zeros. How can I make in the same mode an array in Javascript, withoutfor loopandpushcommands?
Create an array of11undefinedelementsjointhem by using0as stringsplitthe array by empty stringUsemapto convert the strings to number var myArray = new Array(11).join('0').split('').map(Number); console.log(myArray); document.write('<pre>' + JSON.stringify(myArray, 0, 2) + '</pre>');
This question already has answers here:Most efficient way to create a zero filled JavaScript array?(45 answers)Closed7 years ago. If I make this line in C\C++: ``` int myArray[10] = { 0 }; // all elements 0 ``` I will have an array of ten zeros. How can I make in the same mode an array in Javascript, withoutfor loopandpushcommands?
Create an array of11undefinedelementsjointhem by using0as stringsplitthe array by empty stringUsemapto convert the strings to number var myArray = new Array(11).join('0').split('').map(Number); console.log(myArray); document.write('<pre>' + JSON.stringify(myArray, 0, 2) + '</pre>');
I am working on a project for university. One of the small things that make me lose points is that my answer is correct but it doesn't have four figure number. For example say I print my answer which is17and on other test files it could change to 6. Is there a way I can ensure that it would always print either 0017 -> testfile_10006 -> testfile_20123 -> testfile_3 so it always has four digits no matter what the solution is? I made lots of test cases to check if the value is a single number or multiple to work it out but is there a simple way to do this so it automatically adds the zeros?
Try to use ``` printf( "%04d", myValue); ``` 04will make sure that yourmyValuewill always have, at least, 4 digits.
I am new in Makefile. I have wrote hello.c and when I do "make hello" then it gives executable named as "hello". Internally it showing "cc hello.c -o hello". But without Makefile how make works? How make is gives executable as same name as source?
make has a database of built in rules. These rules include recipes for a number of common operations. The GNU Make Manual covers (some at least) of these recipes in theCatalogue of Built-Inf Rulessection. Additionally, the output from the-p/--print-data-baseoption will show you all of the rules/recipes and variables that make has built-in.
I'm writing an SMT program, and I'm trying to workaround an interesting problem. I need all my functions to exit together, however some of the threads get stuck at barriers, even when i don't want them to. My question is: what happens when i delete a barrier? Do threads stuck at the barrier release? Is there a way to signal a release to a certain barrier, even if the number of threads at the barrier hasn't been achieved? Thanks
It's not legal to callpthread_barrier_destroy()if there's any threads blocked on the barrier. When your thread decides to exit early in a situation where other threads could be waiting on it at a barrier, it should callpthread_barrier_wait()before exiting.
So I am new to CDT (even though I have worked with C and Eclipse Java before), and seem to be getting the error as shown in the picture below: Now, when I check theRun Configurations, the application field of the debug applicaiton seems to be empty, as shown below: Finally, when I check the actual physical location of where the debug executable should be, the folder seems to be empty, even though I am going through the build process. Does anyone know why this problem is being caused, and why exactly eclipse isn't building/compiling my executable? NOTE: I am currently using Eclipse Luna.
It seems that your program doesn't compile correctly, maybe because you have a build error at the compiler level... Try to pressCTRL+Band see if in the problems section you get some errors of the compiler .
I have a simple question which is not easily found. Lets say I want to make a functional prototype for a function containing pointers, for example: ``` int insert(char *word, char *Table[], int n) ``` Is there any special rules for function prototypes regarding pointers? Or will the functional prototype for this be: ``` int insert(char, char, int) ```
If you want to write the prototype without parameter names, it will be ``` int insert(char *, char **, int); ``` The type of the first argument ischar *. The type of the second argument ischar **(recall that as a parameter,char *Table[]really meanschar **Table). The type of the third argument isint. The return type isint. You don't have to leave out the parameter names, by the way. This works too: ``` int insert(char *word, char **Table, int n); ``` or: ``` int insert(char *word, char *Table[], int n); ```
Check the min ex: ``` #include <stdio.h> #include <string.h> int main(void) { char newline = '\n'; char* p = &newline; if(strcmp(p, "\n") == 0) { printf("ok\n"); } else { printf("wrong\n"); } return 0; } ``` Is it undefined behaviour? Or is it simply wrong (i.e. it will always return not equal)? Whatever it is, please explain why!
It's UB for the simple reason thatpis not a null-terminated string, andstrcmpis UB if input a non null-terminated string.
Code: ``` #include <stdio.h> int main() { long cn=1; char ch; while((ch=getchar())!=EOF) { printf("%ld\t%c\n",cn++,ch); } } ``` When I input word "secret" and hit enter it shows count up to 7 and not 6,why?
Because the "enter" character is read as well. This is in fact a "newline", ASCII code 10 (or hex 0A).
I am working on a project for university. One of the small things that make me lose points is that my answer is correct but it doesn't have four figure number. For example say I print my answer which is17and on other test files it could change to 6. Is there a way I can ensure that it would always print either 0017 -> testfile_10006 -> testfile_20123 -> testfile_3 so it always has four digits no matter what the solution is? I made lots of test cases to check if the value is a single number or multiple to work it out but is there a simple way to do this so it automatically adds the zeros?
Try to use ``` printf( "%04d", myValue); ``` 04will make sure that yourmyValuewill always have, at least, 4 digits.
I am new in Makefile. I have wrote hello.c and when I do "make hello" then it gives executable named as "hello". Internally it showing "cc hello.c -o hello". But without Makefile how make works? How make is gives executable as same name as source?
make has a database of built in rules. These rules include recipes for a number of common operations. The GNU Make Manual covers (some at least) of these recipes in theCatalogue of Built-Inf Rulessection. Additionally, the output from the-p/--print-data-baseoption will show you all of the rules/recipes and variables that make has built-in.
I'm writing an SMT program, and I'm trying to workaround an interesting problem. I need all my functions to exit together, however some of the threads get stuck at barriers, even when i don't want them to. My question is: what happens when i delete a barrier? Do threads stuck at the barrier release? Is there a way to signal a release to a certain barrier, even if the number of threads at the barrier hasn't been achieved? Thanks
It's not legal to callpthread_barrier_destroy()if there's any threads blocked on the barrier. When your thread decides to exit early in a situation where other threads could be waiting on it at a barrier, it should callpthread_barrier_wait()before exiting.
I'm trying to check some homework answers about overflow for 2's complement addition, subtraction, etc. and I'm wondering if I can specify the size of a data type. For instance if I want to see what happens when I try to assign -128 or -256 to a 7-bit unsigned int.
On further reading I see you wanted bit sizes that are not normal ones, such as 7 bit and 9 bit etc. You can achieve this using bitfields ``` struct bits9 { int x : 9; }; ``` Now you can use this typebits9which has one field in itxthat is only 9 bits in size. ``` struct bits9 myValue; myValue.x = 123; ```
I am trying to get a hexadecimal memory address from a text file and shift the 3 most bits and then print the result. The memory address is A3BC88A0 and I just want to print A3BC8? However, when I run the code, addr = A3BC88AO but result = 14779114. Can someone help me figure out why this is happening or what to do? ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, const char * argv[]) { FILE *f; myfile = fopen("Test.txt", "r"); unsigned addr; fscanf(f, "%x", &addr); printf("%x\n",addr); unsigned result = addr >> 3; printf("%x\n",result); fclose(myfile); return 0; } ```
What you want is not to shift by 3 bits, but by 3 hex digits, each of which is 4 bits. So do this instead: ``` unsigned result = addr >> 12; ```
I have a function I need to implement, which gets thei_node(struct inode *)andd_entry(struct dentry *) as input arguments. How can I create thevfsmountfrom these two inputs?
Generally, you cannot.vfsmountobject is accessible forfileobject, not fordentryone (inodecan be viewed as strictly connected todentry, so it doesn't add something new todentry). dentryobject has novfsmountobject, universally corresponded to it: it depends frommnt_namespaceobject. You can get namespace for e.g. current process:current->nsproxy->mnt_ns, but you shouldn't iterate mounts in this object without takingnamespace_semsemaphore, which is declared as static infs/namespace.c. If you want to implement some access policy, based on files, you may found thisconversationhelpfull: There is no canonical full path for a given dentry. (pathobject has a field, denoted correspondedvfsmountobject).
I have two programs in the same directory main and example, if I execute./example file.txtit manages simple tasks with that file. Then my main program is ``` #include<stdio.h> #include<stdlib.h> #include <sys/types.h> #include <sys/wait.h> int main (int argc, char* argv[]){ pid_t const pid1 = fork(); if(pid1==0){ execv(); } else{ wait(NULL); } } ``` So I want to execute./main file.txtand the child process should execute./example file.txtwith the same file that main has received in argv[1]. My question is how to use the execv parameters to accomplish this.Sorry if I did not explained myself simple. Thank You
The easiest way to do this would be: ``` execl("./example", "example", argv[1], (char *)NULL); ``` Alternatively, ``` char *args[] = { "example", argv[1], NULL }; execv("./example", args); ```
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed7 years ago. I am unable to findout the problem with the code below. I get warning message "operation on 'ptr' may be undefined" on printf statement. Also the the result is printed in reverse order (7 is printed aganst Element1 and 2 against element2) ``` int main() { int a[4] = {2,7,9,0}; int *ptr=a; printf("Element1 = %d Element 2 = %d", *ptr, *ptr++); ptr++; return 0; } ```
The C standard does not define in what order the parameters get evaluated. Try using *(ptr+1) instead of *ptr++, which also can be replaced with ptr[1].
Here is the Part of the program that i am trying to compile using gcc compiler on ubuntu 14.04. ``` #include<stdio.h> #include<string.h> main() { int i; char str[50], pat[3]; char sep; printf("Enter the sting to seperate\n "); scanf("%s", str); fpurge(stdin); printf("Enter the patern in Numbers to seperate Example : 1 2 3\n"); //__fpurge(stdin); scanf("%s", pat); fpurge(stdin); printf("Enter the seperator Example: ; or enter ,space"); scanf("%c", &sep); } ``` this is the Error: ``` /tmp/cc0bHLkO.o: In function `main': str_sepert.c:(.text+0x4d): undefined reference to `fpurge' str_sepert.c:(.text+0x95): undefined reference to `fpurge' collect2: error: ld returned 1 exit status ```
fpurgeis not in the standard C library. It is nonstandard and not portable. It is a BSD function. http://bytes.com/topic/c/answers/845246-fpurge
I am developing a code in c, which simply FTPs the files on FTP server by using curl utility, by following thisexample now i have one simple thing to do, specify curl to use particular interface (IP) of the server for upload, as other interface of the server is associated with other socket connection. is there any way to do it?
Seems like curl support--interfaceoption ``` curl --interface eth0 ```
I have a function I need to implement, which gets thei_node(struct inode *)andd_entry(struct dentry *) as input arguments. How can I create thevfsmountfrom these two inputs?
Generally, you cannot.vfsmountobject is accessible forfileobject, not fordentryone (inodecan be viewed as strictly connected todentry, so it doesn't add something new todentry). dentryobject has novfsmountobject, universally corresponded to it: it depends frommnt_namespaceobject. You can get namespace for e.g. current process:current->nsproxy->mnt_ns, but you shouldn't iterate mounts in this object without takingnamespace_semsemaphore, which is declared as static infs/namespace.c. If you want to implement some access policy, based on files, you may found thisconversationhelpfull: There is no canonical full path for a given dentry. (pathobject has a field, denoted correspondedvfsmountobject).
I have two programs in the same directory main and example, if I execute./example file.txtit manages simple tasks with that file. Then my main program is ``` #include<stdio.h> #include<stdlib.h> #include <sys/types.h> #include <sys/wait.h> int main (int argc, char* argv[]){ pid_t const pid1 = fork(); if(pid1==0){ execv(); } else{ wait(NULL); } } ``` So I want to execute./main file.txtand the child process should execute./example file.txtwith the same file that main has received in argv[1]. My question is how to use the execv parameters to accomplish this.Sorry if I did not explained myself simple. Thank You
The easiest way to do this would be: ``` execl("./example", "example", argv[1], (char *)NULL); ``` Alternatively, ``` char *args[] = { "example", argv[1], NULL }; execv("./example", args); ```
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed7 years ago. I am unable to findout the problem with the code below. I get warning message "operation on 'ptr' may be undefined" on printf statement. Also the the result is printed in reverse order (7 is printed aganst Element1 and 2 against element2) ``` int main() { int a[4] = {2,7,9,0}; int *ptr=a; printf("Element1 = %d Element 2 = %d", *ptr, *ptr++); ptr++; return 0; } ```
The C standard does not define in what order the parameters get evaluated. Try using *(ptr+1) instead of *ptr++, which also can be replaced with ptr[1].
Here is the Part of the program that i am trying to compile using gcc compiler on ubuntu 14.04. ``` #include<stdio.h> #include<string.h> main() { int i; char str[50], pat[3]; char sep; printf("Enter the sting to seperate\n "); scanf("%s", str); fpurge(stdin); printf("Enter the patern in Numbers to seperate Example : 1 2 3\n"); //__fpurge(stdin); scanf("%s", pat); fpurge(stdin); printf("Enter the seperator Example: ; or enter ,space"); scanf("%c", &sep); } ``` this is the Error: ``` /tmp/cc0bHLkO.o: In function `main': str_sepert.c:(.text+0x4d): undefined reference to `fpurge' str_sepert.c:(.text+0x95): undefined reference to `fpurge' collect2: error: ld returned 1 exit status ```
fpurgeis not in the standard C library. It is nonstandard and not portable. It is a BSD function. http://bytes.com/topic/c/answers/845246-fpurge
I am developing a code in c, which simply FTPs the files on FTP server by using curl utility, by following thisexample now i have one simple thing to do, specify curl to use particular interface (IP) of the server for upload, as other interface of the server is associated with other socket connection. is there any way to do it?
Seems like curl support--interfaceoption ``` curl --interface eth0 ```
When I typectags -R .it produces a file called tags, and vim uses that file to navigate tags. How do I make the file name to be .tags and make vim use it?
How to specify the name of thetagsfile is explained very early in$ man ctags: ``` $ ctags -Rf .tags . ``` How to tell Vim where to look fortagsfiles is explained in:help 'tags'(and linked sections). A goodgenericdefault value is: ``` set tags=./tags;,tags; ``` Since you want.tagsinstead oftagsyou should add that case to the value above (safe and somewhat universal): ``` set tags=./tags;,tags;./.tags;,.tags; ``` or only use a value that fitsyourusage pattern: ``` set tags=./.tags;,.tags; ```
I have really been confused about this 2D char array ``` char **arg = malloc(sizeof(char*) * argc) for (int i = 0; i < argc; i++) arg[i] = malloc(sizeof(char) * size) ... ... ``` Now suppose after a series of operations, I forget the variable argc, how can I free those memory? Can I do something like this? Is this absolutely correct under all circumstances? ``` char **tmp = arg; while (*tmp != NULL){ free(*tmp); tmp++; } free(arg); ```
No ``` while(*tmp != NULL){ ``` you may reach above a point where you will dereference memory which hasn't been assigned to and trigger undefined behaviour. Or as suggested you can explicitly assign aNULLto the last allocated pointer, and in that case it will work.
Is the address of a global variable guaranteed to say the same during the whole process execution? That is, I have ``` static int dummy; ``` and I use ``` something(&dummy); ``` in a few different places across my code. Will&dummyever change, or can I safely use it as a key that is unlikely to be reused by another library (e.g. in a hashmap)? This is, of course, assuming I don't restart the program or reload the library. (Context: This was recommended to me by some people on the Lua mailing list. I've been using ithere.)
Yes. From the C99 spec: [6.2.4]The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists,has a constant address, and retains its last-stored value throughout its lifetime.
I have recently downloaded the MinGw compiler and for some reason it does not display and warning messages when I should be doing a explicit casts. For example: ``` double x=9.97; int y=x; ``` This seems to be ok with the compiler. I was just wondering do I need to install some other package
There is no cast required when assigning adoubleto anint. The decimal part is simply truncated. If you want warnings on this you can use-Wconversionor-Wfloat-conversion.
``` int main() { char *a1[10] = {"123","121"}; int i =0; char *a=NULL; for(i=0;i<2;i++) { a=strcat(a1[i],"0000"); printf("values %s",a); } } ``` Output of this code comes out to be this: ``` $ ./a.exe values 1230000 values 0000000 ``` but it should be: ``` $ ./a.exe values 1230000 values 1210000 ``` Please tell me where i am wrong.
You want an array of array of char, but char *a1[10] is an array of pointers to char (tipically placed in read-only segments / string literals), trying to modify a string literal usually leads to a segmentation fault. Change ``` char *a1[10] = {"123","121"}; /* Array of string literals (read only) */ ``` to ``` char a1[][10] = {"123","121"}; /* Array of array of char (read - write) */ ```
``` int array[2] = {1, 1}; int (*pointer_array)[2] = {NULL, NULL}; ``` The first line can be correctly compiled but not the second one? Why? GCC compiler will pop up a warning,excess elements in scalar initializer. How to initialize a pointer array in C? EDITED I declared a pointer array in a wrong way. It should be like this: ``` int *pointer_array[2] = {NULL, NULL}; ```
It should be ``` int (*pointer_array)[2]=(int[]){1,2}; ``` This is pointer to array ofint.I don't know you want pointer to array ofintor array of pointers. To declare as array of pointer you need to do this - ``` int *pointer_array[2]; ```
This question already has answers here:Generating a random bit - lack of randomness in C rand()(4 answers)Closed4 years ago. I want to generate a random boolean for use in a game, so it does not need to be cryptographically secure. I will usestdbool.hin my code, and I have also done#include <stdlib.h>. Preferably, it should be very fast (as I will be generating many of them), and it should be able to be done in C89 (just preference). I am not interested at all in doing this in C++. Here are some of the ways I've come up with: read from /dev/urandom, filter out single digits and >5 = true, <5 = false.keep calling rand() and filter out low/high values.
Just callrand()and get the LSB of its return value. ``` bool randbool = rand() & 1; ``` Remember to callsrand()at the beginning.
I am trying to create a new pointer every iteration. Each pointing to its own memory location, holding the value of i at the time it is assigned. My approach is below but when I print the address of id, it is the same for each iteration. code ``` for(i=1;i<=n;i++){ int id = i; printf("i[%p], ",&i); printf("id[%p]\n",&id); } ``` output ``` i[565782000], id[565782004] i[565782000], id[565782004] i[565782000], id[565782004] ```
iandidare both local variables with automatic storage (commonly referred to ason the stack). Nonewinstances arecreatedupon each iteration of the loop, the same space is reused and a new value is stored inid, hence the same addresses printed byprintf. Note that the value ofidis not guaranteed to be preserved across iterations since it goes out of scope at the end of the block forming the body of theforloop.
I'm trying to calculate the distance between 2 coordinates in 3D, however, when complied, and entered (1,1,1), (1,1,1), output returns 2 instead of 0. Code here ``` #include <stdio.h> #include <math.h> int get_dist(int x_i,int y_i,int z_i,int x_o,int y_o,int z_o){ int coord_dist = 0; coord_dist = sqrt(((x_o - x_i)^2) + ((y_o - y_i)^2) + ((z_o - z_i)^2)); return coord_dist; } int main(void){ int x0,y0,z0,x1,y1,z1; int dist0_1 = 0; printf("coord 0:"); scanf("%d %d %d", &x0, &y0, &z0); printf("coord 1:"); scanf("%d %d %d", &x1, &y1, &z1); dist0_1 = get_dist(x0,y0,z0,x1,y1,z1); printf("%d\n", dist0_1); return 0; } ```
^ is XOR, not exponent. You want the pow() function.
I write a C program mentioned below: ``` #include <stdio.h> int sum(int&, int*); int main(int argc, const char * argv[]) { int array[] = {1,2,3}; int temp = 0; int _result = sum(temp, 3); return 0; } int sum(int &sum, int *array) { } ``` But, my program have a error for declaration, it don't know declare "&" for functionint sum(int&, int*); How do you fix this problem?
References are not available incSecond parameter calling sum does not make sense. I guess you want something like ``` #include <stdio.h> int sum(int*, int*, int); int main(int argc, const char * argv[]) { int array[] = {1,2,3}; int temp = 0; int result = sum(&temp, array, 3); return 0; } int sum(int *sum, int *array, int array_size) { // sum stuff return *sum; } ```
This question already has answers here:C sizeof a passed array [duplicate](7 answers)How to find the size of an array (from a pointer pointing to the first element array)?(17 answers)Closed7 years ago. I wrote the following function in C: ``` void dummy(int* my_array, int size) { //my implementation } ``` Is there any way to check whether size is REALLY the size ofmy_array? For example, if I call the function and use formy_arrayan array with 4 elements but pass 5 forsize, is there any way to know that 5 is not really the size of the array? Thank you in evidence.
You're looking at it the wrong way. An array is contiguous piece of memory. In C, you can represent this concept with a pointer to its start and its size. Since your array is represented by a<my_array, size>tuple, it doesn't make sense to talk aboutmy_array's size, since it's only the start-pointer of the array.