question
stringlengths
25
894
answer
stringlengths
4
863
Need to send messages on PC without configured IP using MAC address in C language as a reply on PC's broadcast message. I suppose I should work with ethernet-header and use some (linux) kernel's structures and subroutines, however I couldn't find good links and samples about my question.
Example of sending a raw Ethernet frame in Linux: https://gist.github.com/austinmarton/1922600
I'm new to these Intrinsics but was wondering if you could help me out. My program won't compile because of this error. Any ideas on how to fix it? I would assume that this should work because r2_v is also of data type __m128d ``` error: initializing '__m128d' (vector of 2 'double' values) with an expression of incompatible type 'int' __m128d r2inv_v = _mm_rsqrt_pd(r2_v); ^ ~~~~~~~~~~~~~~~~~~ ``` Thanks. This is the code it errors around ``` __m128d r2_v = _mm_add_pd(_mm_add_pd(_mm_mul_pd(rx_v, rx_v),_mm_mul_pd(ry_v, ry_v)),_mm_add_pd(_mm_mul_pd(rz_v, rz_v),eps_v)); __m128d r2inv_v = _mm_rsqrt_pd(r2_v); ```
You need to create a variable of the type__m128d. You can create one using __m128d _mm_set_pd (double e1, double e0) or use it directly in the call ``` _mm_rsqrt_pd( _mm_set_pd( d1, d2 ) ); ```
i am trying to make a simple program to detect the UP key. here is my c code: ``` #include <stdio.h> #include <ncurses.h> int main() { initscr(); noecho(); printw("hello\n"); refresh(); int ch = getch(); if (ch == KEY_UP) { printw("up!\n"); refresh(); } getch(); endwin(); return 0; } ``` when i compile and run the program, it doesn't work. when i press up key it just exits. thanks in advance.
You should callkeypadto tell curses to interpret special keys: ``` keypad(stdscr, TRUE); ``` afterinitscr(). Without that, your program will read (separately)escape[andA. Further reading: Initialization(ncurses manual)keypad(3)
I save the random array on text file so I can load it again. Is there any better way to save it without using txt file? ``` for(i=0;i<10000;i++); clientdata[i]=rand(); FILE * fp; fp = fopen ("client.txt", "w+"); fwrite(clientdata, sizeof clientdata[0], sizeof clientdata / sizeof clientdata[0], f); fclose(f); ```
You can use random seed like this to ensure that you generate the same random number every time: ``` #include <stdio.h> #include <stdlib.h> int main() { int seed = 1892; //any number, this is the random seed srand(seed); //call this with the random seed argument for(i=0;i<10000;i++); clientdata[i]=rand(); //do something, you will generate the same random data every time } ```
Need to send messages on PC without configured IP using MAC address in C language as a reply on PC's broadcast message. I suppose I should work with ethernet-header and use some (linux) kernel's structures and subroutines, however I couldn't find good links and samples about my question.
Example of sending a raw Ethernet frame in Linux: https://gist.github.com/austinmarton/1922600
I'm new to these Intrinsics but was wondering if you could help me out. My program won't compile because of this error. Any ideas on how to fix it? I would assume that this should work because r2_v is also of data type __m128d ``` error: initializing '__m128d' (vector of 2 'double' values) with an expression of incompatible type 'int' __m128d r2inv_v = _mm_rsqrt_pd(r2_v); ^ ~~~~~~~~~~~~~~~~~~ ``` Thanks. This is the code it errors around ``` __m128d r2_v = _mm_add_pd(_mm_add_pd(_mm_mul_pd(rx_v, rx_v),_mm_mul_pd(ry_v, ry_v)),_mm_add_pd(_mm_mul_pd(rz_v, rz_v),eps_v)); __m128d r2inv_v = _mm_rsqrt_pd(r2_v); ```
You need to create a variable of the type__m128d. You can create one using __m128d _mm_set_pd (double e1, double e0) or use it directly in the call ``` _mm_rsqrt_pd( _mm_set_pd( d1, d2 ) ); ```
i am trying to make a simple program to detect the UP key. here is my c code: ``` #include <stdio.h> #include <ncurses.h> int main() { initscr(); noecho(); printw("hello\n"); refresh(); int ch = getch(); if (ch == KEY_UP) { printw("up!\n"); refresh(); } getch(); endwin(); return 0; } ``` when i compile and run the program, it doesn't work. when i press up key it just exits. thanks in advance.
You should callkeypadto tell curses to interpret special keys: ``` keypad(stdscr, TRUE); ``` afterinitscr(). Without that, your program will read (separately)escape[andA. Further reading: Initialization(ncurses manual)keypad(3)
I save the random array on text file so I can load it again. Is there any better way to save it without using txt file? ``` for(i=0;i<10000;i++); clientdata[i]=rand(); FILE * fp; fp = fopen ("client.txt", "w+"); fwrite(clientdata, sizeof clientdata[0], sizeof clientdata / sizeof clientdata[0], f); fclose(f); ```
You can use random seed like this to ensure that you generate the same random number every time: ``` #include <stdio.h> #include <stdlib.h> int main() { int seed = 1892; //any number, this is the random seed srand(seed); //call this with the random seed argument for(i=0;i<10000;i++); clientdata[i]=rand(); //do something, you will generate the same random data every time } ```
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 I know what it does, and it is a format specifier.but I have no clue on how this works.It gets the last input, and just doesn't save it. But how?
The starting asterisk indicates that the data is to be read from the stream but ignored (i.e. it is not stored in the location pointed by an argument). Reference:http://www.cplusplus.com/reference/cstdio/scanf/ So the data would not be saved in the variable.
I am creating, writing to and reading from a shared segment on Linux using the ftok/shmget/shmat/shmdt functions. If I write to the segment in one program which then exits, and subsequently read the segment from another program later, I am surprised to find the data still there. I would have expected that when the last process sharing a segment does a shmdt, the segment would be free'd. Can I rely on this behavior? Or is it analogous to continuing to use a pointer after free()'ing it?
The shared memory area remains until it is deleted viashmctl(shmid,IPC_RMID,...)[or system reboot]. This will take effect after every process has doneshmdt[or terminated]. The semantics are very similar to a file.shmatis likeopen.shmdtis likecloseand the [above]shmctlis likeunlink. If you close a file, you'd like it to persist until specifically deleted, wouldn't you? So, shared memory segments operate similarly
Part of the text file used: ``` Maths H B2 Irish O C3 English O B1 ``` I am trying to split the strings into three arrays storing for example; maths into a subject array, H(higher level) into a level array and B2 into a grade array. Im doing this so it is then accessible later and easier to sort separately etc. The following is a code of me trying to split the strings in the array into three but want to store each one in a different array. This is my first assignment using structs so am new to this syntax and do not know how to do it. ``` SubjectResult split; for(i=0; i<lineNum; i++){ sscanf(ResultsArr[i],"%s %s %s",split.subject, split.level, split.grade); } ``` Thanks in advance!
You need to make an array of structs. ``` SubjectResult split[MAXLINES]; for (i = 0; i < lineNum; i++) { sscanf(ResultsArr[i],"%s %s %s", split[i].subject, split[i].level, split[i].grade); } ```
This should return 451,845,518,507 when I pass in "ice" but it is returning 873,952,427 can anyone tell me why? (MAX_STR_SIZE = 501) ``` unsigned long hash_code(const char *str){ char temp[MAX_STR_SIZE]=""; unsigned long multiplied; if(str == NULL){ return SUCCESS; } else if(strlen(str)==0 || str==""){ return SUCCESS; } else{ strncpy(temp,str, strlen(str)-1); temp[strlen(str)-1]=0; multiplied = (hash_code(temp)*65599 + (int) str[strlen(str)-1]); return multiplied; } } ```
unsigned longis only 32-bit on your machine. Need a wider type for 451,845,518,507 ``` 451,845,518,507 mod pow(2,32) --> 873,952,427 ```
I just have simple question, I am aware of C language, A while ago i came across this piece of code: ``` int a; a=12/8*8; ``` I tried it using codeblocks and result was that a=8 !!!!!How did the compiler deal with that? Thanks.
The multiplication operator and division operator have the same precedence level, and are evaluated from left to right. So the above is equivalent to: ``` a=(12/8)*8; ``` The division is integer division, so the result is1since the fractional part gets truncated. That is then multiplied by8, resulting in8being assigned toa.
I'm curious if there is a way to merge two struct fields without having to explicitly check each field? ``` typedef struct NSPoint { int x; int y; int z; } NSPoint; NSPoint point1 = { .x = 5, .y = 4, .z = 3}; // Somewhere down the code NSPoint point2 = { .x = 10 }; // Merge so it ends with: // { .x = 10, .y = 4, z = 3}; NSPoint point3 = point1 + point2; ```
No, this is not possible. Once you realize that this: ``` NSPoint point2 = { .x = 10 }; ``` Is semantically identical to this: ``` NSPoint point2 = { .x = 10, .y = 0, .z = 0 }; ``` you'll understand why.
I've been following this tutorial to create a system call in Minix. http://homepages.cs.ncl.ac.uk/nick.cook/csc2025/minix/syscall-exercise1.html I can use the system call correctly when I use _syscall and now I would like to create a libc library function to allow it to be easily used. However, following the last steps of the tutorial are not working for me. When I try to compile my code, I receive undefined reference to [my library function]. I've added the prototype to unistd.h, I think something is going wrong in my Makefile. All I did was add SRCS += myfile.c. Is there something more I need to do?
Ok, so I was putting SRCS+=... in libc/sys/Makefile.inc but this Makefile is mostly under a conditional which I just realized is false. I moved over to libc/misc and added everything there and it worked like a charm.
input(string): E2 output: The char is E The num is 2 How can I get that? Thanks I use strtol, but it just work for only the first char is num if my input was 2E, it works, but if it was E2,then fail. ``` int main() { char str[30] = "2E"; char *ptr; long ret; ret = strtol(str, &ptr, 10); printf("The number(unsigned long integer) is %ld\n", ret); printf("String part is %s", ptr); return(0); } ``` What I want is if I input E2, the ret is 2 and the ptr is E
You could usesscanf: ``` char c; int i; if (sscanf(input, "%c%d", &c, &i) == 2) /* make sure 2 objects were read */ printf("The char is %c and the int is %d\n", c, i); ```
In a c program. I am trying to use the left shift operator on uint64_t variable. E.g. ``` // with shift of 24 bits uint64_t x = 0; x = (((uint64_t)76) << (24)); Output is: x = 1275068416 --------------------------------------------- // with shift of 32 bits uint64_t x = 0; x = (((uint64_t)76) << (32)); Output is: x = 0 ``` If I perform left shift till 24 bits then it works fine, but at 32 bits it outputs 0. Whereas what I think is as the size of uint64_t i.e. unsigned long long is 64 bits. So shouldn't it work till the 64 bit shift ?
You're using the wrong format specifier to print the output. The%dformat specifier expects anint, which apparently is 32-bit on your system. So passing a 64-bit value (and an unsigned one at that) leads to undefined behavior. You should use thePRIu64macro to get the correct format specifier for an unsigned 64-bit value. ``` printf("%"PRIu64"\n", x); ```
WHAT will be time complexity of relation T(n)=nT(n-1)+n in my prog something like this ``` f(int n) { c++; if(n>0) for(i=1;i<=n;i++) f(n-1); } ``` i took a counter to count how many time function called it gives answer between n to n! thanks.
Your code lacks the+npart of the recursion, so I assume that the code is wrong and the recursion ``` T(n) = n*T(n-1) + n ``` is correct. Letf(n)=T(n)/n!, then ``` f(n) = T(n)/n! = n(T(n-1)+1)/n! = T(n-1)/(n-1)! + 1/(n-1)! = f(n-1) + 1/(n-1)! = sum(1,n-1, 1/k!) ~ e ``` ThusT(n) ~ e*n!.
I am trying to modify value of one string using other . ``` #include <stdio.h> #include <string.h> int main(void) { char ch[10],s[3]; int c; fgets(ch,10,stdin); fgets(s,2,stdin); c=(int)s[1]; ch[3]+=c;//s[1]; printf("%c\n",s[1]); printf("%s",ch); return 0; } ``` Output is blank for s[1] and ch remains unchanged . However the program works fine if i remove the second gets and use a constant in place of c. I would like to know the my error as well as the best simple approach for string manipulation . EDIT : changed s[2] to s[3] , still same result
If the secondfgets()read something (1 character), a terminating null character will be written tos[1]. Bits in terminating null character are all zero, and it means that the value ofs[1]will become0. Adding zero means almost nothing.
I'm curious if there is a way to merge two struct fields without having to explicitly check each field? ``` typedef struct NSPoint { int x; int y; int z; } NSPoint; NSPoint point1 = { .x = 5, .y = 4, .z = 3}; // Somewhere down the code NSPoint point2 = { .x = 10 }; // Merge so it ends with: // { .x = 10, .y = 4, z = 3}; NSPoint point3 = point1 + point2; ```
No, this is not possible. Once you realize that this: ``` NSPoint point2 = { .x = 10 }; ``` Is semantically identical to this: ``` NSPoint point2 = { .x = 10, .y = 0, .z = 0 }; ``` you'll understand why.
I've been following this tutorial to create a system call in Minix. http://homepages.cs.ncl.ac.uk/nick.cook/csc2025/minix/syscall-exercise1.html I can use the system call correctly when I use _syscall and now I would like to create a libc library function to allow it to be easily used. However, following the last steps of the tutorial are not working for me. When I try to compile my code, I receive undefined reference to [my library function]. I've added the prototype to unistd.h, I think something is going wrong in my Makefile. All I did was add SRCS += myfile.c. Is there something more I need to do?
Ok, so I was putting SRCS+=... in libc/sys/Makefile.inc but this Makefile is mostly under a conditional which I just realized is false. I moved over to libc/misc and added everything there and it worked like a charm.
input(string): E2 output: The char is E The num is 2 How can I get that? Thanks I use strtol, but it just work for only the first char is num if my input was 2E, it works, but if it was E2,then fail. ``` int main() { char str[30] = "2E"; char *ptr; long ret; ret = strtol(str, &ptr, 10); printf("The number(unsigned long integer) is %ld\n", ret); printf("String part is %s", ptr); return(0); } ``` What I want is if I input E2, the ret is 2 and the ptr is E
You could usesscanf: ``` char c; int i; if (sscanf(input, "%c%d", &c, &i) == 2) /* make sure 2 objects were read */ printf("The char is %c and the int is %d\n", c, i); ```
In a c program. I am trying to use the left shift operator on uint64_t variable. E.g. ``` // with shift of 24 bits uint64_t x = 0; x = (((uint64_t)76) << (24)); Output is: x = 1275068416 --------------------------------------------- // with shift of 32 bits uint64_t x = 0; x = (((uint64_t)76) << (32)); Output is: x = 0 ``` If I perform left shift till 24 bits then it works fine, but at 32 bits it outputs 0. Whereas what I think is as the size of uint64_t i.e. unsigned long long is 64 bits. So shouldn't it work till the 64 bit shift ?
You're using the wrong format specifier to print the output. The%dformat specifier expects anint, which apparently is 32-bit on your system. So passing a 64-bit value (and an unsigned one at that) leads to undefined behavior. You should use thePRIu64macro to get the correct format specifier for an unsigned 64-bit value. ``` printf("%"PRIu64"\n", x); ```
WHAT will be time complexity of relation T(n)=nT(n-1)+n in my prog something like this ``` f(int n) { c++; if(n>0) for(i=1;i<=n;i++) f(n-1); } ``` i took a counter to count how many time function called it gives answer between n to n! thanks.
Your code lacks the+npart of the recursion, so I assume that the code is wrong and the recursion ``` T(n) = n*T(n-1) + n ``` is correct. Letf(n)=T(n)/n!, then ``` f(n) = T(n)/n! = n(T(n-1)+1)/n! = T(n-1)/(n-1)! + 1/(n-1)! = f(n-1) + 1/(n-1)! = sum(1,n-1, 1/k!) ~ e ``` ThusT(n) ~ e*n!.
I am trying to modify value of one string using other . ``` #include <stdio.h> #include <string.h> int main(void) { char ch[10],s[3]; int c; fgets(ch,10,stdin); fgets(s,2,stdin); c=(int)s[1]; ch[3]+=c;//s[1]; printf("%c\n",s[1]); printf("%s",ch); return 0; } ``` Output is blank for s[1] and ch remains unchanged . However the program works fine if i remove the second gets and use a constant in place of c. I would like to know the my error as well as the best simple approach for string manipulation . EDIT : changed s[2] to s[3] , still same result
If the secondfgets()read something (1 character), a terminating null character will be written tos[1]. Bits in terminating null character are all zero, and it means that the value ofs[1]will become0. Adding zero means almost nothing.
I've been following this tutorial to create a system call in Minix. http://homepages.cs.ncl.ac.uk/nick.cook/csc2025/minix/syscall-exercise1.html I can use the system call correctly when I use _syscall and now I would like to create a libc library function to allow it to be easily used. However, following the last steps of the tutorial are not working for me. When I try to compile my code, I receive undefined reference to [my library function]. I've added the prototype to unistd.h, I think something is going wrong in my Makefile. All I did was add SRCS += myfile.c. Is there something more I need to do?
Ok, so I was putting SRCS+=... in libc/sys/Makefile.inc but this Makefile is mostly under a conditional which I just realized is false. I moved over to libc/misc and added everything there and it worked like a charm.
input(string): E2 output: The char is E The num is 2 How can I get that? Thanks I use strtol, but it just work for only the first char is num if my input was 2E, it works, but if it was E2,then fail. ``` int main() { char str[30] = "2E"; char *ptr; long ret; ret = strtol(str, &ptr, 10); printf("The number(unsigned long integer) is %ld\n", ret); printf("String part is %s", ptr); return(0); } ``` What I want is if I input E2, the ret is 2 and the ptr is E
You could usesscanf: ``` char c; int i; if (sscanf(input, "%c%d", &c, &i) == 2) /* make sure 2 objects were read */ printf("The char is %c and the int is %d\n", c, i); ```
In a c program. I am trying to use the left shift operator on uint64_t variable. E.g. ``` // with shift of 24 bits uint64_t x = 0; x = (((uint64_t)76) << (24)); Output is: x = 1275068416 --------------------------------------------- // with shift of 32 bits uint64_t x = 0; x = (((uint64_t)76) << (32)); Output is: x = 0 ``` If I perform left shift till 24 bits then it works fine, but at 32 bits it outputs 0. Whereas what I think is as the size of uint64_t i.e. unsigned long long is 64 bits. So shouldn't it work till the 64 bit shift ?
You're using the wrong format specifier to print the output. The%dformat specifier expects anint, which apparently is 32-bit on your system. So passing a 64-bit value (and an unsigned one at that) leads to undefined behavior. You should use thePRIu64macro to get the correct format specifier for an unsigned 64-bit value. ``` printf("%"PRIu64"\n", x); ```
WHAT will be time complexity of relation T(n)=nT(n-1)+n in my prog something like this ``` f(int n) { c++; if(n>0) for(i=1;i<=n;i++) f(n-1); } ``` i took a counter to count how many time function called it gives answer between n to n! thanks.
Your code lacks the+npart of the recursion, so I assume that the code is wrong and the recursion ``` T(n) = n*T(n-1) + n ``` is correct. Letf(n)=T(n)/n!, then ``` f(n) = T(n)/n! = n(T(n-1)+1)/n! = T(n-1)/(n-1)! + 1/(n-1)! = f(n-1) + 1/(n-1)! = sum(1,n-1, 1/k!) ~ e ``` ThusT(n) ~ e*n!.
I am trying to modify value of one string using other . ``` #include <stdio.h> #include <string.h> int main(void) { char ch[10],s[3]; int c; fgets(ch,10,stdin); fgets(s,2,stdin); c=(int)s[1]; ch[3]+=c;//s[1]; printf("%c\n",s[1]); printf("%s",ch); return 0; } ``` Output is blank for s[1] and ch remains unchanged . However the program works fine if i remove the second gets and use a constant in place of c. I would like to know the my error as well as the best simple approach for string manipulation . EDIT : changed s[2] to s[3] , still same result
If the secondfgets()read something (1 character), a terminating null character will be written tos[1]. Bits in terminating null character are all zero, and it means that the value ofs[1]will become0. Adding zero means almost nothing.
This question already has answers here:How do I properly compare strings in C?(11 answers)Closed7 years ago. So I am getting 2 strings from files I open and read. They are exactly the same but it doesnt seem to work this way. How would i make it work/do it differently? This is the code: ``` FILE *file; FILE *file2; file = fopen("hey1.txt", "r"); file2 = fopen("hey2.txt", "r"); char line[32]; char line2[32]; while (fgets(line, 32, file) != NULL) { printf("%s\n", line); } while (fgets(line2, 34, file2) != NULL) { printf("%s\n", line2); } if (line==line2) { printf("The same\n"); } else { printf("Not the same\n"); } ```
You can't use==to compare strings. Use ``` strcmp() ```
I currently have a code that checks whether a file is a directory or not, it goes as follows; ``` file = readdir (dir); if(file->d_type & DT_DIR){ \* some code*\ } ``` I was wondering, what is the if statement for the exact opposite of this. Something along the line "if file is not directory".
Any boolean expression can be negated with thenotoperator (!): ``` if (!(file->d_type & DT_DIR)) { ```
I've noticed in C on Windows platformprintf(0);can crash any program, since there is no format specifier mentioned in argument. Usually I've seen it triggers __invoke_watson(). I want to know if there is any security implication associated with this type of scenarios, considering parameter of printf() cannot be controlled attacker.
There are no security implications here. printf(0)is dereferencing a NULL pointer. While this will likely make the program crash, there's no room for an attacker to inject anything.
Here is my code in C Language: ``` #include<stdio.h> int main(){ printf("This line is written before return keyword."); return 0; //terminator printf("This line is written after return keyword."); //does not display } ``` I know that anything written after a return keyword in a function will not be executed. My question is, "Does the code after return keyword be compiled in the first place?" Please clarify. Thanks.
Yes the code is compiled and the compiler can issue an error if the code is invalid. Also it can issue a warning saying that the code after the return statement will not be executed. The compiler is allowed not to generate object code for such unreachable code.
This question already has answers here:printf not printing to screen(3 answers)Why does printf not flush after the call unless a newline is in the format string?(10 answers)Closed7 years ago. I have code like this below: ``` #include <stdio.h> int main(int argc, char *argv[]) { printf("hello"); while(1){ // whatever here } } ``` and the question is: why the first instruction is skipped? It runs only the loop, hello is never printed. I compiled it with gcc and g++ with the same result.
Itdoesrun, it's just that the output buffer is notflushedbefore yourwhile. Useprintf("hello\n");instead. The newline character will flush the buffer so writing the output immediately to your console.
The strcmp cause the program to crash, Why is that? When removing strcmp it works well, and also with strcpy makes it crash ``` size_t maxLineLen=1024; char *line = (char*)malloc(maxLineLen); while(getline(&line, &maxLineLen,stdin)!= -1){ int h =strlen(line); for (int i = 0; i < h; i++){ if(strcmp(line[0], "a") == 0) { printf("a found %c \n ",line[i]); break; } } } return 0; } ```
Thestrcmpfunction expects achar *for the first argument, but you're passing achar. Similarly withstrcpy. This caused undefined behavior. Your compiler should have given you a warning regarding this. If what you're trying to do is see if a given character in the string isa, you would do it like this: ``` if (line[i] == 'a') ```
I've noticed in C on Windows platformprintf(0);can crash any program, since there is no format specifier mentioned in argument. Usually I've seen it triggers __invoke_watson(). I want to know if there is any security implication associated with this type of scenarios, considering parameter of printf() cannot be controlled attacker.
There are no security implications here. printf(0)is dereferencing a NULL pointer. While this will likely make the program crash, there's no room for an attacker to inject anything.
Here is my code in C Language: ``` #include<stdio.h> int main(){ printf("This line is written before return keyword."); return 0; //terminator printf("This line is written after return keyword."); //does not display } ``` I know that anything written after a return keyword in a function will not be executed. My question is, "Does the code after return keyword be compiled in the first place?" Please clarify. Thanks.
Yes the code is compiled and the compiler can issue an error if the code is invalid. Also it can issue a warning saying that the code after the return statement will not be executed. The compiler is allowed not to generate object code for such unreachable code.
This question already has answers here:printf not printing to screen(3 answers)Why does printf not flush after the call unless a newline is in the format string?(10 answers)Closed7 years ago. I have code like this below: ``` #include <stdio.h> int main(int argc, char *argv[]) { printf("hello"); while(1){ // whatever here } } ``` and the question is: why the first instruction is skipped? It runs only the loop, hello is never printed. I compiled it with gcc and g++ with the same result.
Itdoesrun, it's just that the output buffer is notflushedbefore yourwhile. Useprintf("hello\n");instead. The newline character will flush the buffer so writing the output immediately to your console.
The strcmp cause the program to crash, Why is that? When removing strcmp it works well, and also with strcpy makes it crash ``` size_t maxLineLen=1024; char *line = (char*)malloc(maxLineLen); while(getline(&line, &maxLineLen,stdin)!= -1){ int h =strlen(line); for (int i = 0; i < h; i++){ if(strcmp(line[0], "a") == 0) { printf("a found %c \n ",line[i]); break; } } } return 0; } ```
Thestrcmpfunction expects achar *for the first argument, but you're passing achar. Similarly withstrcpy. This caused undefined behavior. Your compiler should have given you a warning regarding this. If what you're trying to do is see if a given character in the string isa, you would do it like this: ``` if (line[i] == 'a') ```
This question already has answers here:printf not printing to screen(3 answers)Why does printf not flush after the call unless a newline is in the format string?(10 answers)Closed7 years ago. I have code like this below: ``` #include <stdio.h> int main(int argc, char *argv[]) { printf("hello"); while(1){ // whatever here } } ``` and the question is: why the first instruction is skipped? It runs only the loop, hello is never printed. I compiled it with gcc and g++ with the same result.
Itdoesrun, it's just that the output buffer is notflushedbefore yourwhile. Useprintf("hello\n");instead. The newline character will flush the buffer so writing the output immediately to your console.
The strcmp cause the program to crash, Why is that? When removing strcmp it works well, and also with strcpy makes it crash ``` size_t maxLineLen=1024; char *line = (char*)malloc(maxLineLen); while(getline(&line, &maxLineLen,stdin)!= -1){ int h =strlen(line); for (int i = 0; i < h; i++){ if(strcmp(line[0], "a") == 0) { printf("a found %c \n ",line[i]); break; } } } return 0; } ```
Thestrcmpfunction expects achar *for the first argument, but you're passing achar. Similarly withstrcpy. This caused undefined behavior. Your compiler should have given you a warning regarding this. If what you're trying to do is see if a given character in the string isa, you would do it like this: ``` if (line[i] == 'a') ```
I have tried it but i get "sum=6" and it is wrong. Whats is wrong with the code? Here is the code: ``` #include <stdio.h> #define ROW 2 #define COL 3 int sum(int(*array)[3]); int main(void) { int a[ROW][COL] = { {1 , 2, 3} , {4 , 5, 6} }; printf(" sum = %d\n", sum (a)); return 0; } int sum(int(*array)[3]) { int i,j, sum = 0; for (i =0; i < ROW ; i ++) { for (j =0; j < COL ; j ++) { sum = sum + *(*( array +i )+j); } } } ```
You forget to return the value ofsumin your function ``` int sum(int(*array)[3]) { int i,j, sum = 0; for (i =0; i < ROW ; i ++) { for (j =0; j < COL ; j ++) { sum = sum + *(*( array +i )+j); } } return sum; /* HERE */ } ``` And notice that ``` sum = sum + array[i][j]; ``` is more readable than ``` sum = sum + *(*( array +i )+j); ```
I'm usinglldbas a standalone debugger in OSX. I'm trying to debug a C executable, using a text file as input, by way of a redirect. Thelldbdocumentation specifies the following command for changing stdin to a given file: ``` process launch -i <file> ``` Using this command,lldbseems to ignore the specified file, instead waiting for keyboard input. Is this intended behavior? If so; what do I need to do to actually get the process to operate on my wanted input file? tl;dr: How do I getlldbto imitate a standard terminal execution with a redirect like: ``` ./executable < <file> ```
I got it to work as follows: ``` lldb <executable> (lldb) settings set target.input-path <file> (lldb) process launch ``` It solves my problem, but I don't really have an explanation for why the method in my questiondoesn'twork.
This question already has answers here:How is conversion of float/double to int handled in printf?(7 answers)Closed7 years ago. I have the below C code. ``` int main (void) { printf("%d\n",5/(float)4.7); printf("Size of int = %d",sizeof(int)); return(1); } ``` But the result is 1610612736 I was expecting the result to be 1 since we are tying to print an integer. Why this is the case? How float value is getting converted to a large value in printf statement? I am using codeblock + mingw
as you'retrying to print an integeryou have to cast the result toint ``` printf("%d\n",(int)(5/(float)4.7)); ``` otherwise5/(float)4.7is afloat You see1610612736because thefloatvalue is "interpreted" as andintleading to and odd result.
``` #include <stdio.h> int main(void) { char c[] = "Gate2011"; char *p = c; printf("%s", p+p[3]-p[1]); return 0; } ``` Output:2011 Why does it give this output? I tried different combinations and it always gives junk.
becausep[3] = 'e' = 101andp[1] = 'a' = 97 101 - 97 = 4 p + 4= address of "2001" in "Gate2001" interpreted as string ... there you go. I also do not understand the downvotes :(
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 just started programming and would like to implement a file monitoring system from scratch in C. I have used the Watch Service API in java but I would like to learn how to build one from scratch. I would really appreciate some assistance and guidance. Thanks.
You can: either rely on existing system calls that will push you notifications on file system modifications (eg: inotify)implement your own kernel module that will intercept file system modification and notify you (if you really want to reimplement the wheel)use a polling-approach, rebuild the filesystem tree in-memory and compare it every second or so. This will be very cpu/io/memory consuming, but it can be instructive.
I'm dealing with some C source code I'm trying to convert over to Javascript, I've hit a snag at this line ``` char ddata[512]; *(unsigned int*)(ddata+0)=123; *(unsigned int*)(ddata+4)=add-8; memset(ddata+8,0,add-8); ``` I'm not sure exactly what is happening here, I understand they're casting the char to an unsigned int, but what is theddata+0and stuff doing here? Thanks.
You can't say. That's because the behaviour on casting achar*to anunsigned*isundefinedunlessthe pointer started off as anunsigned*, which, in your case it didn't. ddata + 0is equivalent toddata. ddata + 4is equivalent to&ddata[4], i.e. the address of the 5th element of the array. For what it's worth, it looks like the C programmer is attempting to serialise a couple ofunsignedliterals into a byte array. But the code is a mess; aside from what I've already said they appear to be assuming that anunsignedoccupies 4 bytes, which is not necessarily the case.
There is a function tosetthe "valid data length" value:SetFileValidData, but I didn't find a way togetthe "valid data length" value. I want to know about given file if the EOF is different from the VDL, because writing after the VDL in case ofVDL<EOFwill cause a performance penalty as describedhere.
I foundthispage, claims that: there is no mechanism to query the value of the VDL So the answer is "you can't". If you care about performance you can set the VDL to the EOF, but then note that you may allow access old garbage on your disk - the part between those two pointers, that supposed to be zeros if you would access that file without setting the VDL to point the EOF.
I have the following declared globally ``` char a[20] = " "; char b[20] = " "; char c[20] = " "; char d[20] = " "; ``` I need to set these variable to NULL in a method.So i use ``` void mymethod() { a[10]=" "; b[10]=" "; c[10]=" "; d[10]=" "; } ``` But the variables still retain their old value.What im i doing wrong?
``` char a[20] = ""; ``` This is initializing an array during declaration. Whereas ``` a[10] = ""; ``` This is actually setting a value to an element in an array. Try using ``` memset(a,0,sizeof(a)); ``` To initialize your array within a function.
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 just started programming and would like to implement a file monitoring system from scratch in C. I have used the Watch Service API in java but I would like to learn how to build one from scratch. I would really appreciate some assistance and guidance. Thanks.
You can: either rely on existing system calls that will push you notifications on file system modifications (eg: inotify)implement your own kernel module that will intercept file system modification and notify you (if you really want to reimplement the wheel)use a polling-approach, rebuild the filesystem tree in-memory and compare it every second or so. This will be very cpu/io/memory consuming, but it can be instructive.
I'm dealing with some C source code I'm trying to convert over to Javascript, I've hit a snag at this line ``` char ddata[512]; *(unsigned int*)(ddata+0)=123; *(unsigned int*)(ddata+4)=add-8; memset(ddata+8,0,add-8); ``` I'm not sure exactly what is happening here, I understand they're casting the char to an unsigned int, but what is theddata+0and stuff doing here? Thanks.
You can't say. That's because the behaviour on casting achar*to anunsigned*isundefinedunlessthe pointer started off as anunsigned*, which, in your case it didn't. ddata + 0is equivalent toddata. ddata + 4is equivalent to&ddata[4], i.e. the address of the 5th element of the array. For what it's worth, it looks like the C programmer is attempting to serialise a couple ofunsignedliterals into a byte array. But the code is a mess; aside from what I've already said they appear to be assuming that anunsignedoccupies 4 bytes, which is not necessarily the case.
There is a function tosetthe "valid data length" value:SetFileValidData, but I didn't find a way togetthe "valid data length" value. I want to know about given file if the EOF is different from the VDL, because writing after the VDL in case ofVDL<EOFwill cause a performance penalty as describedhere.
I foundthispage, claims that: there is no mechanism to query the value of the VDL So the answer is "you can't". If you care about performance you can set the VDL to the EOF, but then note that you may allow access old garbage on your disk - the part between those two pointers, that supposed to be zeros if you would access that file without setting the VDL to point the EOF.
I have the following declared globally ``` char a[20] = " "; char b[20] = " "; char c[20] = " "; char d[20] = " "; ``` I need to set these variable to NULL in a method.So i use ``` void mymethod() { a[10]=" "; b[10]=" "; c[10]=" "; d[10]=" "; } ``` But the variables still retain their old value.What im i doing wrong?
``` char a[20] = ""; ``` This is initializing an array during declaration. Whereas ``` a[10] = ""; ``` This is actually setting a value to an element in an array. Try using ``` memset(a,0,sizeof(a)); ``` To initialize your array within a function.
Why are they separate from the rest of the scan codes? Is there some reason for it? ``` F9 is 67 F10 is 68 Numlock is 69 F11 is 87 F12 is 88 ```
Yes, there is. Keyboards with function keys used to only go up to F10. The addition of F11 and F12 as standard happened some time in the late 80s or early 90s, from memory. Changing the enumeration for existing scan codes 69 and 70 would have broken compatibility with old keyboards. Remember that prior to USB (or PS/2, for that matter), keyboards had a chunky 5-pin DIN connector, and you couldn't really tell what was on the other end of it.
I had two questions regarding the -DNDEBUG that I didnt quite understand after doing some reading on it. 1) Will it cause problems if both -DNDEBUG and -g flags are used together? 2) Does the -DNDEBUG flag turn off asserts? (This means that asserts wont work)
To expand@kaylum's valid answer. -DNDEBUGconsists of two parts, the flag-Dand the argumentNDEBUG. The flag is used to create preprocessor defines, therefore this will create a new preprocessor#definecalledNDEBUG -gis a compiler switch to generate debugging information. It works completely separate from creating defines with-D. Read more about debugging flagshere.
Is it possible to change the options in Clion so that the variables are aligned like so: This should be applied in structs and methods.
Yes. Settings -> Editor -> Code Style -> C/C++ -> Wrapping and Braces -> Variable groups -> Align in columns You can of course also use a custom formatting tool that does it as well.
After I compile usinggcc -Wall getopt.c -o optionsand run a few examples, it seems to work at first glance. Purposely tripping it up makes it Segfault. ``` //straight from the man page static struct option long_options[] = { {"add", required_argument, 0, 0 }, {"append", no_argument, 0, 0 }, {"delete", required_argument, 0, 0 }, {"verbose", no_argument, 0, 0 }, {"create", required_argument, 0, 'c'}, {"file", required_argument, 0, 0 }, {0, 0, 0, 0 } //<-- if i omit this line, it segfaults }; ``` Why does it cause a Segmentation Fault when I omit that one line? or rather, asked in a different way Why must I initialize the last set ofstruct option arraymembers to null?
Easy. So the code processing the array knows when it's at the end. It's called a sentinel.
I need to write a driver which is capable of reading and writing on the serial and the can bus port. The serial port is realized with asigaction()and an event handler. When I try to realize the same thing for the can bus, just the last event handler will be notified as there can be just on event handle assigned to thesigaction(). Is there any other possibility to solve this problem?
Your signal handler needs to determine why the signal was raised and act appropriately. You're probably going to want to block further signals with sigprocmask() as you could be interrupted in the signal handler, check if any data is available on both the serial port and the can bus, copy it out or set whatever flags you need to, then unblock signals at the end of your signal handler.
My problem is the following: ``` int c; c = getchar(); while (c != EOF) { putchar(c); c = getchar(); } while((c = getchar()) != EOF) { putchar(c); } ``` These two does the same thing. My question is how they both work? And why they both produce the same result? As far as my understanding goes lets take the first one as example here, it reads one character, its not EOF-> go into while putchar(printchar on the screen) then move into get another char. However lets say i input something like "Hello", it will output Hello, how and why? Why does it not just output 5x H -> HHHHH ?
putcharis a function in the C programming language that writes a single character to the standard output stream, stdout. The C library functionint getchar(void)gets a character (an unsigned char) from stdin. This is equivalent togetcwith stdin. Hope this Helps.
I have a method that looks like this: ``` static inline float average(int numbers, ...) { } ``` How do you use for loop to get all the value I've put into numbers. For example: ``` average(1, 3, 5, 7); ```
You can't. If you want to use variadic arguments, you need a mechanism for getting the number of arguments. Most often it is inferred from the first non-variadic argument. That's howprintfand family work for instance. For your example I personally wouldn't bother with variadic arguments. If you want a mathematical function likeaverageapplied to one or more arguments, just use a vector: ``` static inline float average(const int* numbers, int size) ``` If you insist in using variadic functions, these will get you started: GNU introduction and example for variadic functionWikipedia entry on Variadic functioncppreference documentation with example for C variadic functions
I want to show my TopMost window right-bottom of screen (above taskbar) Here is what I have tried: ``` this->SetWindowPos(&this->wndBottom, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); ``` Which shows at center of screen
UseSystemParametersInfo(SPI_GETWORKAREA...)to find the desktop rectangle (area excluding the toolbar) then set window position withSWP_NOSIZEflag: ``` CRect rcDesktop; ::SystemParametersInfo(SPI_GETWORKAREA, NULL, &rcDesktop, NULL); CRect rw; GetWindowRect(&rw); SetWindowPos(0, rcDesktop.right - rw.Width(), rcDesktop.bottom - rw.Height(), 0, 0, SWP_NOSIZE); ```
I'm trying to compile following code using gcc (tdm-1) 4.7.1 with notepad, and command prompt on windows 10. previously add bin folder path to global variables,but when i try to compile i get following error " undefined reference to `WinMain@16'".However same code works fine with codeblocks!. PS: I compile it like this "cd /d path of code then gcc filename.c" ``` #include<stdio.h> int main(){ printf("Hello world"); return 0; } ```
I found What was wrong accidentally.After writing my code through notepad,I forgot to save file ctrl+s so i just trying to compile empty file.
I have the following code and I am trying to assign a value to the structure name but it is returning me segment core error. Why is that? ``` struct group { char *name; struct user *users; struct xct *xcts; struct group *next; }; int add_group(Group **group_list_ptr, const char *group_name) { Group *newGroup = malloc(sizeof(Group)); strcpy(newGroup->name, group_name); } ```
You havemalloc-ed thestruct, but you did notmallocthe string. The pointer inside thestructis uninitialized, so you cannotstrcpyanything into it yet. You have to allocate memory for your string, assign that memory toname, and only then dostrcpy: ``` Group *newGroup = malloc(sizeof(Group)); newGroup->name = malloc(strlen(group_name)+1); // +1 for '\0' terminator strcpy(newGroup->name, group_name); ```
The standard struct for list node is: ``` struct node { int x; struct node *next; }; ``` But, what would happen if we defined a node without a pointer, like this: ``` struct node { int x; struct node next; }; ``` ? I assume that the main problem would be not knowing where the list ends, since there wouldn't be aNULLpointer. But apart from that is there any other effects to be taken into consideration?
What would happen if we defined a node without a pointer, like this:struct node { int x; struct node next; }; This declares a structure with unterminated recursion. Hence the declaration is invalid and is rejected by the compiler.
This question already has answers here:Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?(19 answers)Closed7 years ago. ``` int main(void) { char *temp = "ABCDE"; temp[2] = 'X'; printf("%s", temp); return 0; } ``` In gdb I could see that temp[2] = 'X' is causing the crash. But why? Could some answer please?
String literals arenon-modifiable. It may be stored in read-only section of the memory and any attempt to modify it will lead to undefined behavior. If you want to modify it, declaretempas an array ofchars ``` char temp[] = "ABCDE"; ```
What is the term used (say, by programming language theorists) for the act of casting a void pointer into a pointer to a type? Is it "upcasting"? "type infusion"? "typing"? Notes: It is obviously a cast, and obviously a reinterpreting cast - but I'm looking for a more specific term, expressive of the transition from an untyped to a typed pointee.Please do not argue about whether it's a good idea to avoid this or not, that is really not the question.
If you wanted to make up a new term, you could call ittype unerasure.
I want to assign ' to a character but it keeps giving me error any help? ``` void main() { char c = '''; } ```
Special characters like ' or \ must be escaped with a backslash in these situations. In this particular case you got an error because the compiler thinks you opened and closed a null character with the first two '' and then opened another character without closing it with the third one.
I have the following code and I am trying to assign a value to the structure name but it is returning me segment core error. Why is that? ``` struct group { char *name; struct user *users; struct xct *xcts; struct group *next; }; int add_group(Group **group_list_ptr, const char *group_name) { Group *newGroup = malloc(sizeof(Group)); strcpy(newGroup->name, group_name); } ```
You havemalloc-ed thestruct, but you did notmallocthe string. The pointer inside thestructis uninitialized, so you cannotstrcpyanything into it yet. You have to allocate memory for your string, assign that memory toname, and only then dostrcpy: ``` Group *newGroup = malloc(sizeof(Group)); newGroup->name = malloc(strlen(group_name)+1); // +1 for '\0' terminator strcpy(newGroup->name, group_name); ```
The standard struct for list node is: ``` struct node { int x; struct node *next; }; ``` But, what would happen if we defined a node without a pointer, like this: ``` struct node { int x; struct node next; }; ``` ? I assume that the main problem would be not knowing where the list ends, since there wouldn't be aNULLpointer. But apart from that is there any other effects to be taken into consideration?
What would happen if we defined a node without a pointer, like this:struct node { int x; struct node next; }; This declares a structure with unterminated recursion. Hence the declaration is invalid and is rejected by the compiler.
This question already has answers here:Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?(19 answers)Closed7 years ago. ``` int main(void) { char *temp = "ABCDE"; temp[2] = 'X'; printf("%s", temp); return 0; } ``` In gdb I could see that temp[2] = 'X' is causing the crash. But why? Could some answer please?
String literals arenon-modifiable. It may be stored in read-only section of the memory and any attempt to modify it will lead to undefined behavior. If you want to modify it, declaretempas an array ofchars ``` char temp[] = "ABCDE"; ```
So I created a function with the code: ``` #define ATABLE 20 void func1(){ char array[ATABLE][ATABLE]; int row, col; for(row=0; row<ATABLE; row++) for(col=0; col<ATABLE; col++) { array[row][col]={' '}; } } ``` But there is an error message when I compile it and it says "expected expression before '{' token" I think there is something wrong with my initialization but I can't seem to figure out how to correctly implement it. If I wanted to initialize all the elements of my 2d array with, let's say, a space, how do I write it? All answers would be very much appreciated. TIA
Not sure how you declaredarray, but you could try this: ``` array[row][col] = " "; ```
http://docs.ceph.com/docs/hammer/radosgw/s3/cpp/#creating-and-closing-a-connection I used "LISTING A BUCKET’S CONTENT" section from above link. But I am not able to list all contents of bucket. isTruncated comes to 1 in call back, but nextMarker is null. Any help ? I will try using aws-sdk but that is too large for my simple needs. And it has gcc 4.9 as requirement.
You need to save and use the last returned key from the first request as marker for the second request. The nextMarker is only set in the response if, in your request, you set a delimiter, because when you are using a delimiter, it's not always possible to determine where you should start back up based on the contents of the response. http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html
``` void reverse_String(char a[], int start, int length){ int i; int j = length; for(i = start; i != j ; i++, j--){ a[i] ^= a[j]; a[j] ^= a[i]; a[i] ^= a[j]; } printf("%s", a); } int main(int argc, char *argv[]){ int length; char word[strlen(argv[1])]; strcpy(word,argv[1]); length = strlen(word); reverse_String(word,0,length); return 0; } ``` Why am I getting a Segmentation Fault for some entries, but it works for others? (Argv[1] is any String entered)
If the number of characters is even, i will never be equal to j. You need to change your condition to i < j
I have a makefile, called "Makefile", and some target in it like: ``` file.o: file.c Makefile gcc <some flags & options> file.c ``` What exactly doesfile.o: file.c Makefiledo?
That line describes the dependencies forfile.o. If any file listed after the:(file.candMakefilein this case) has been modified later thanfile.o, thenfile.ois rebuilt according to the command in the following line.
I need some help. I have toconvert and STORE a char * into a double or long doublewithout losing precision. Indeed, i tried to usestrtoldandatofmethods (alsostrtold), but these methods are rounding the value. For example: ``` char * key ="39.7519707"; double ld =strtod((char*)key,NULL); printf("%lf", ld); ``` prints : 39.751971 butprintf("%6.7f",ld)gives me the right value but I couldn't store into a variable.
First of all, you only need%fformat specifier to print adouble. Then, you're not losing precision by making use ofstrtod(), the outputrepresentationis the problem with how you useprintf()with%fformat specifier. As perC11, chapter §7.21.6.1,fprintf() [...] If the precision is missing, it is taken as 6;[...] Next, when you did ``` printf("%6.7f",ld); ``` the precision became 7 and it outputs the value you expect to see.
I need to store a 'large' file (say a little under 2mb) in memory and I want to know if it's OK to just use ``` char buffer[2048000]; ``` Is there a better way to handle it? Any performance issues with using large char arrays?
Yes there could be issues, most C implementations will allocate that buffer on the stack if it's a variable of automatic storage duration, and the amount of "stack memory" available for use can be surprisingly small. Your best bet is to usemallocfor anything larger than a few kilobytes. Just remember to callfreeat an appropriate point. Making itstaticis another possibility or making it globalmighthelp.
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 am searching an example for data loss by a concurrent access from two or more threads. Have anyone an idea, how I could do that? (in C) In the second step I want to fix the problem with mutex or smth like that. But it would help just to have an idea how to do the data loss! greetings
Implement a simple linked list, start two thread : one adding and one deleting. I guarante you a beautiful sigsev after a while. The mutex will help keep your linked list clean.
http://man7.org/linux/man-pages/man3/stdout.3.html What does the statement "but all old streams have become inaccessible" mean? From my current understanding, all inherited handles should still be usable. Is my understanding incorrect?
File descriptors are just integers that are managed by the operating system. They are unaffected byexec. Streams (i.e.,FILE *), on the other hand, are collections of buffers and state information managed by a library. They act as a layer above file descriptors. Whenexecis called, all of the buffers and state information associated with a stream are wiped out when the new image is loaded. They're just gone. Any pending buffered data or state info is lost.
I have a makefile, called "Makefile", and some target in it like: ``` file.o: file.c Makefile gcc <some flags & options> file.c ``` What exactly doesfile.o: file.c Makefiledo?
That line describes the dependencies forfile.o. If any file listed after the:(file.candMakefilein this case) has been modified later thanfile.o, thenfile.ois rebuilt according to the command in the following line.
I need some help. I have toconvert and STORE a char * into a double or long doublewithout losing precision. Indeed, i tried to usestrtoldandatofmethods (alsostrtold), but these methods are rounding the value. For example: ``` char * key ="39.7519707"; double ld =strtod((char*)key,NULL); printf("%lf", ld); ``` prints : 39.751971 butprintf("%6.7f",ld)gives me the right value but I couldn't store into a variable.
First of all, you only need%fformat specifier to print adouble. Then, you're not losing precision by making use ofstrtod(), the outputrepresentationis the problem with how you useprintf()with%fformat specifier. As perC11, chapter §7.21.6.1,fprintf() [...] If the precision is missing, it is taken as 6;[...] Next, when you did ``` printf("%6.7f",ld); ``` the precision became 7 and it outputs the value you expect to see.
I need to store a 'large' file (say a little under 2mb) in memory and I want to know if it's OK to just use ``` char buffer[2048000]; ``` Is there a better way to handle it? Any performance issues with using large char arrays?
Yes there could be issues, most C implementations will allocate that buffer on the stack if it's a variable of automatic storage duration, and the amount of "stack memory" available for use can be surprisingly small. Your best bet is to usemallocfor anything larger than a few kilobytes. Just remember to callfreeat an appropriate point. Making itstaticis another possibility or making it globalmighthelp.
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 am searching an example for data loss by a concurrent access from two or more threads. Have anyone an idea, how I could do that? (in C) In the second step I want to fix the problem with mutex or smth like that. But it would help just to have an idea how to do the data loss! greetings
Implement a simple linked list, start two thread : one adding and one deleting. I guarante you a beautiful sigsev after a while. The mutex will help keep your linked list clean.
http://man7.org/linux/man-pages/man3/stdout.3.html What does the statement "but all old streams have become inaccessible" mean? From my current understanding, all inherited handles should still be usable. Is my understanding incorrect?
File descriptors are just integers that are managed by the operating system. They are unaffected byexec. Streams (i.e.,FILE *), on the other hand, are collections of buffers and state information managed by a library. They act as a layer above file descriptors. Whenexecis called, all of the buffers and state information associated with a stream are wiped out when the new image is loaded. They're just gone. Any pending buffered data or state info is lost.
Is it possible for a function in a linux kernel module calling a function in another module ?
Yes. Of course, the other kernel module must be loaded. For an example, look at the USB code, which is implemented as a mullti-layer driver, with each layer in its own module.Reference linkhere.
I'm pretty new to C programming and I'm wondering why I need to input the same value twice when using the following code? ``` #include <stdio.h> int main(void) { int ascii; printf("Enter an ASCII value: "); scanf(" %d\n", &ascii); printf("The %d ASCII code has the character value %c\n", ascii, ascii); return 0; } ``` You can see that I've had to enter89twice in the image below.
You need to remove the whitespace (the space and\n) in yourscanfpattern, i.e."%d"instead of" %d\n". ``` #include <stdio.h> int main(void) { int ascii; printf("Enter an ASCII value: "); scanf("%d", &ascii); printf("The %d ASCII code has the character value %c\n", ascii, ascii); return 0; } ```
I'm reading an integer from a file usingfscanf(fp, "%d", &n)function. Is there a way to know how many digits that number has without loops?
You can try: ``` int count = 0; fscanf(fp, "%d%n", &n, &count); ``` The%nspecifier puts incountthe number of characters read so far. However, this number can be larger that the number of digits ofnbecause the%dspecifier allows skipping whitespace characters before it reads the number. Check @pmg'sanswerto see how to count those whitespaces.
I am a newbie! I need to pass an array of hex values bit by bit. I am not sure as to how to do it. let's say I have array defined below, ``` const uint_8t a[] = { 0xAA, 0xF8, 0x03, ... }; int size=sizeof(a) / 8; //edited SBIT(port, SFR_P0, 1); void Data(int *a, int size) { int i; for (i = 0; i < size; i++) { port = a[i]; } } ``` How can I pass this array bit by bit to a function pointing to MSB first.
You cannotpassbit addresses. But you can enumerate the bits and pass their values with 2 nested loops: ``` const uint_8t a[] = { 0xAA, 0xF8, 0x03, ... }; size_t size = sizeof(a); for (size_t i = 0; i < size; i++) { for (int shift = 8; shift-- > 0; ) { transmit_bit((a[i] >> shift) & 1); } } ```
I am trying to find what will happen if I have 2 variables in enum and I assign it a value. I want a understanding on when i assign value to c_type which one gets used C1 or C2? I have the following code: ``` typedef enum { C1 = 0, C2, } c_type; typedef struct A_a { c_type store; } A; FuncABC(int val) { A a1; a1.store = val; /here store has C1 and C2, which one gets used here? } ``` Please, let me know. I know the above code works logically in C. But, want clarification on the assignment.
What you are confusing isa1.storewill storeC1orC2. Actually,a1.storecould beC1orC2or2or3or255or whatever is the value ofval. Back to the C standard, anenumvariable can store a value that is out of the range of values of theenumtype. You could also refer thisEnumeration object set to a value not equal to any of its respective enumeration constants
I am a newbie! I need to pass an array of hex values bit by bit. I am not sure as to how to do it. let's say I have array defined below, ``` const uint_8t a[] = { 0xAA, 0xF8, 0x03, ... }; int size=sizeof(a) / 8; //edited SBIT(port, SFR_P0, 1); void Data(int *a, int size) { int i; for (i = 0; i < size; i++) { port = a[i]; } } ``` How can I pass this array bit by bit to a function pointing to MSB first.
You cannotpassbit addresses. But you can enumerate the bits and pass their values with 2 nested loops: ``` const uint_8t a[] = { 0xAA, 0xF8, 0x03, ... }; size_t size = sizeof(a); for (size_t i = 0; i < size; i++) { for (int shift = 8; shift-- > 0; ) { transmit_bit((a[i] >> shift) & 1); } } ```
I am trying to find what will happen if I have 2 variables in enum and I assign it a value. I want a understanding on when i assign value to c_type which one gets used C1 or C2? I have the following code: ``` typedef enum { C1 = 0, C2, } c_type; typedef struct A_a { c_type store; } A; FuncABC(int val) { A a1; a1.store = val; /here store has C1 and C2, which one gets used here? } ``` Please, let me know. I know the above code works logically in C. But, want clarification on the assignment.
What you are confusing isa1.storewill storeC1orC2. Actually,a1.storecould beC1orC2or2or3or255or whatever is the value ofval. Back to the C standard, anenumvariable can store a value that is out of the range of values of theenumtype. You could also refer thisEnumeration object set to a value not equal to any of its respective enumeration constants
please explain why the user and system time output is zero seconds and 0% cpu usage. ``` #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> int main() { char c; int in, out; in = open(“inputfile_name”, O_RDONLY); out = open(“outputfile_name”, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR); while(read(in,&c,1) == 1) write(out,&c,1); exit(0); } ```
If a program runs sufficiently fast, it may terminate before the long-term system clock (as queried withgettimeofdayadvances. On some systems, this clock has a precision of just 10 ms, so it's likely that this happens with a very brief program like yours. In this situation, the operating system reports the runtime of your program as 0 as it didn't take any time to run from the point of view ofgettimeofday.
say, I have some struct like this: ``` typedef struct node { char[32] name; int *contents[10]; } Node; ``` I want to initialize a new Node and store it on heap, do I need also to malloc space for name and integers? However, if I tried to malloc space for them, for example: ``` Node *new_node = malloc{...}; new_node->name = malloc{32 * sizeof(char)}; ... ``` I got error says name is not assignable.
When you allocate space for your struct asNode *new_node = malloc(sizeof(Node));, that includes space for each struct element. In this case, that includes space for 32charand 10int *. So you don't need to allocate space for thenamearray, although depending on your usage, you might allocate space to each element ofcontents.
I'm trying to access the next line using fgets in order to count the number of lines that are similar to the next one, is there anyway to get the nextLine variable? int similar = 0; char line[100]; char nextLine[100]; FILE *f = fopen(file, "r"); while (fgets(line, 100, f)) { if (strcmp(nextLine, line) == '0') { similar++; } }
It's possible - add a new varnext_line. For example, ``` int similar = 0; char line[100] = ""; char next_line[100] = ""; FILE *f = fopen(file, "r"); while (fgets(line, 100, f)) { if (strcmp(next_line, line) == 0) { similar++; } strcpy(next_line, line); } ``` NOTE: You must checkstrcmpwith0, not'0'This only works to compare adjacent lines.
Code: ``` enum {a, b}; int different(void) { if (sizeof (enum {b, a}) != sizeof (int)) return a; // a == 1 return b; // b == 0 in C89, b == 1 in C99 } ``` Howa==1andb==0inc89andb==1inc99? I want to know how value ofain returnais 1 and return value ofbchanges inc89andc99?
The difference between the C89 and C99 behavior is due to whichenumdefinition is in scope. In gcc, for C89 the inner definition is in effect forreturn b, while in C99 the outer definition is in effect forreturn b. You can see this more clearly in the following example: ``` #include <stdio.h> enum {a=5, b=6}; int different(void) { if (sizeof(enum {b=7, a=8}) != sizeof(int)) return a; return b; } int main() { printf("%d\n", different()); } ``` In gcc, C89 mode gives 7 and C99 mode gives 6.
I encountered the following code snippet within a cstartup file for a cortex m0 micro -cstartup_M.c ``` #pragma location = ".intvec" __root const intvec_elem __vector_table[] = { { .__ptr = __sfe( "CSTACK" ) }, __iar_program_start, NonMaskableInt_Handler, HardFault_Handler, ``` Could someone please explain the syntax within the line:{ .__ptr = __sfe( "CSTACK" ) }, Specifically: What is the purpose of the additional code block?What is going on here:.__ptr?
That's the new C99 initialization syntax. An initializer of the form ``` .field = value ``` initializes structure memberfieldtovalueinstead of initializing the next structure member in order.
both have almost same input parameters: ``` int _ftprintf( FILE *stream, const _tchar *format [, argument ]...) int fprintf(FILE *stream, const char *format, ...) ``` What is the difference between the two format agruments? When should I use each?
_tprintfand_ftprintfare to be used withTCHARformat strings.TCHARis just a macro, which unwraps into eithercharorwchar_t, depending on whether is the_UNICODEmacro defined. So, basically, if you don't have_UNICODEdefined,_ftprintfwill be equivalent tofprintf, otherwise it will be equivalent tofwprintf.
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 I would need some clarifications regarding processes and threads. I learned recently that all threads (user-level or kernel-level) are executed by a kernel, i.e. they are mapped to a kernel-thread. I also learned that process can spawn other processes and threads, but can threads spawn other processes ? I had a second question, kernel-threads executes threads, but what executes processes ? is a process also mapped to a kernel thread ?
regarding the question: * but can threads spawn other processes ? * The answer is 'yes'. To do so, in C, call thefork()function or any of theexec*()functions although to be perfectly honest, the exec() functions actually replace the current process rather than starting a new process
I've searched the standard but didn't notice the mentioned part. Is it just "anything but 0" and 1 or it is compiler-dependent?
The result of the logical negation operator!is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has typeint. Appears in C89/C90, C99, and C11.
I wanted to convert two dimensional array to a one dimension (array linearization ) by using a pointer and setting it to a particular character. Here is the code: ``` #define COLS 20 #define ROWS 10 void convert(void) { char record[ROWS][COLS] = { 0 }; char *pRecord = record; int i = 0; for (i = 0; i < (ROWS*COLS); i++) { *(pRecord++) = ' '; } } ``` However, I am getting a compiler error in initializing the pointer tochararray. I 'vd edited the code i.e it will be *pRecord, previously it was only pRecord. Need some help in understanding the error and if possible some suggestions to fix it.
May I suggest you define the pointer as a pointer? This compiles cleanly on my machine: ``` char *pRecord = &record[0][0]; ```