question
stringlengths
25
894
answer
stringlengths
4
863
I have a typedef struct representing a circle with 3 integers; x y and radius ive been told to create an array of five circles C5, such that circle Ci has x=i,y=i,r=i How do i store this in the array?
You need to create an array like this: ``` type_name circles[5]; ``` where "type_name" is the name of your typedef struct. Then you can assign values to the slots in the array like this: ``` // set the circle in slot 2 to have the values of x, y, and r circles[2].x = x; circles[2].y = y; circles[2].r = r; ``` wher...
This question already has answers here:Strings without a '\0' char?(6 answers)Closed3 years ago. What happens all, if a string would have no NUL-character (\0) and the compiler would let it pass, f.e. just with warnings? How does it affect the computer and the program exactly?
A compiler will let it pass as its completly legit. A C-String is nothing else than an array of char and functions just need the\0to determine the end of the array, as this is unknown in most cases. Having no terminator in your c-string will result in functions not beeing able to determine the end of the string and e...
I've used Code::Blocks to find the result, and it gives me2at the end, wherei + j = 1 + 1. ``` #include <stdio.h> int main(void) { int i = -1, j = 1; for(i++; i++; i++) j++; printf("%d",i + j); return 0; } ``` How doesiget to be1, and why wasjnot incremented?
You start withi == -1, j == 1. Then you run the firsti++, which will makei == 0. The result (which is theoriginalvalue ofi) is unused. Then you test for the first time ini++. Sinceiis already0, the test isfalse, so theforloop will quit. Now the post-increment runs, which makes iti == 1, and the loop exits. Note how...
This question already has answers here:What is time(NULL) in C?(8 answers)Closed3 years ago. Why do we use 'NULL' in code below. Why can't we multiply the seed by an integer? Sorry I am new to C++. CODE ``` srand(time(NULL)); ```
Thetimefunction can write the time to a location provided by a pointer to the function call. This pointer argument can be a null pointer, and thentimeonly returns the current time. On most systems thetimefunction returns the number of seconds since an epoch, and as such is a pretty unique integer value to use forseed...
How is a static variable "retained" from one call to another? Does it use something likemallocto put it in the program memory, or is there other way that it's stored for all the program to view that variable, for example: ``` static int counter = 4; [similar to:] int counter = malloc(sizeof(int)); counter = 4 ```
Static scalar variables (float, int, byte) are stored in the data segment of the memory. the compiler assigns an address in this memory area that is allocated to the program when it is loaded into memory. other areas : stack (for pushing parameters to function, methods) heap : dynamic memory used by malloc, new. htt...
Is there any different between the two: ``` for (int i=0; *(strings+i) != NULL ;i++) len_strings += strlen(*(strings+i)); ``` And: ``` for (int i=0; strings[i] != NULL ;i++) len_strings += strlen(strings[i]); ``` Or is it more of a stylistic difference and there's no actual difference between the two in ho...
The C standard definesE1[E2]to be the same as(*((E1)+(E2)))for any expressionsE1andE2, so there is no semantic difference. For most uses, the subscript notation is preferred and more readable, but the pointer notation may be useful when one wants to emphasize some particular aspect for readers.
Let's say I have the following piece of code: ``` void foo(){ static int bar = 0; bar++; } ``` Does two successive calls to this function reset the value of the variable?
Initialization occurs when an object is created. For static objects, their lifetimes start when program execution starts. They are not reinitialized or reassigned when execution reaches the statements that define them.
I've used Code::Blocks to find the result, and it gives me2at the end, wherei + j = 1 + 1. ``` #include <stdio.h> int main(void) { int i = -1, j = 1; for(i++; i++; i++) j++; printf("%d",i + j); return 0; } ``` How doesiget to be1, and why wasjnot incremented?
You start withi == -1, j == 1. Then you run the firsti++, which will makei == 0. The result (which is theoriginalvalue ofi) is unused. Then you test for the first time ini++. Sinceiis already0, the test isfalse, so theforloop will quit. Now the post-increment runs, which makes iti == 1, and the loop exits. Note how...
This question already has answers here:What is time(NULL) in C?(8 answers)Closed3 years ago. Why do we use 'NULL' in code below. Why can't we multiply the seed by an integer? Sorry I am new to C++. CODE ``` srand(time(NULL)); ```
Thetimefunction can write the time to a location provided by a pointer to the function call. This pointer argument can be a null pointer, and thentimeonly returns the current time. On most systems thetimefunction returns the number of seconds since an epoch, and as such is a pretty unique integer value to use forseed...
Is there any way, whether union, struct, or something else, to have a group of functions? ``` typedef struct { //ERROR int sqr(int i) { return i * i; } //ERROR int cube (int i) { return i * i * i; } } test; ```
Fields in structs can be function pointers: ``` struct Interface { int (*eval)(int i); }; ``` You cannot define the functions in the struct body, but you can assign functions with the same signature to the struct fields: ``` int my_sqr(int i) { return i * i; } int my_cube(int i) { return i * i * i; } ...
Is there any way, whether union, struct, or something else, to have a group of functions? ``` typedef struct { //ERROR int sqr(int i) { return i * i; } //ERROR int cube (int i) { return i * i * i; } } test; ```
Fields in structs can be function pointers: ``` struct Interface { int (*eval)(int i); }; ``` You cannot define the functions in the struct body, but you can assign functions with the same signature to the struct fields: ``` int my_sqr(int i) { return i * i; } int my_cube(int i) { return i * i * i; } ...
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.Closed3 years ago.Improve this question I am trying to build a game in C language usingrayliblibrary and I wanted to deploy thesl...
Let's say that you have two headers, header1.h and header2.h, both containing a function named foo. Then you can define a new header/source pair: mynewheader.h: ``` int header2_foo(int n); ``` mynewheader.c: ``` #include <header2.h> int header2_foo(int n) { return foo(n); } ``` Of course, you can choose any p...
How should I read each of these definitions ? const char *arguments[]char *const arguments[] I saw examples ofexecl()code using the first form but could not make it work under Linux and had to use the second form ?
const char *arguments[] argumentsis an array of unknown size of pointers toconstqualifiedchar. char *const arguments[] argumentsis an array of unknown size ofconstqualified pointers tochar.
I am compiling a project with multiple libraries without issue. I am using stdlib content. However,math.hfunctions are failing to link. My command line compilation is as follows: ``` gcc -o exe/split main/split.c -I/usr/include/gsl -Isrc -Llib -L/usr/lib/x86_64-linux-gnu -ltools -lgsl ``` I am compiling this si...
Most functions declared in<math.h>actually aren't in libc. They're in libm, for hysterical raisins - I mean, historical reasons. Add "-lm" to your command line. It's probably best to put it at the very end.
The code is supposed to transform every letter of every word to uppercase. But running the code results in a bus error. What causes the bus error? ``` #include <stdio.h> char *ft_strupcase(char *str) { int index; index = 0; while (str[index] != '\0') { if (str[index] >= 97 && str[index] <= 1...
The string "sEbas" is aconst char[], so you shouldn't use it to initializechar* name. If you compile this code on Visual Studio 2019, it won't compile and will tell you the error: cannot convert from 'const char [6]' to 'char *' You can replace it with: char name[] = "sEbas";
I am compiling a project with multiple libraries without issue. I am using stdlib content. However,math.hfunctions are failing to link. My command line compilation is as follows: ``` gcc -o exe/split main/split.c -I/usr/include/gsl -Isrc -Llib -L/usr/lib/x86_64-linux-gnu -ltools -lgsl ``` I am compiling this si...
Most functions declared in<math.h>actually aren't in libc. They're in libm, for hysterical raisins - I mean, historical reasons. Add "-lm" to your command line. It's probably best to put it at the very end.
The code is supposed to transform every letter of every word to uppercase. But running the code results in a bus error. What causes the bus error? ``` #include <stdio.h> char *ft_strupcase(char *str) { int index; index = 0; while (str[index] != '\0') { if (str[index] >= 97 && str[index] <= 1...
The string "sEbas" is aconst char[], so you shouldn't use it to initializechar* name. If you compile this code on Visual Studio 2019, it won't compile and will tell you the error: cannot convert from 'const char [6]' to 'char *' You can replace it with: char name[] = "sEbas";
``` #include<stdio.h> int main() { int x = 5; int length = 5+x; int arrayw[length]; return 0; } ``` This code builds fine in gcc and Keil but not in IAR. ``` I get this error : Error[Pe028]: expression must have a constant value ``` How can it be made to compile fine in IAR toolchain
Follow this:https://netstorage.iar.com/SuppDB/Public/UPDINFO/013556/ew/doc/infocenter/GettingStarted/CreatingAnApplicationProject/CreatingAnApplProj.ENU.html On the step where it saysSetting project optionsmake sure to select C99. Here is the window you're looking for: P.S. There is also an option to explicitly a...
Is it possible to write a C program that functions differently according toargv[0]? In fact, I am working on an exercise from a C textbook. The exercise is to write a program that converts uppercase to lower or lowercase to upper, depending on the name it is invoked with, as found inargv[0]. [Edit] FYI, the exercise...
Is it possible to write a C program that functions differently according to argv[0]? Yes, it is possible, very simply. For example: ``` if (0 == strcmp(argv[0], "say_hello")) { printf("hello\n"); } else if (0 == strcmp(argv[0], "say_bye")) { printf("bye\n"); } ```
Here is my code: the line pipeArr[i] = commands leads to a seg fault core dumped. ``` char ***pipeArr; for (int i = 0; i < numPipes; i++) { char** commands = /* a function that returns char** */ pipeArr[i] = commands; } ``` Why does assigning a char** array to the index of an unassigned char*** array lead to...
You never assigned any value topipeArr, so it's a pointer to nothing in particular. So when you dopipeArr[i] = ...you are modifying thei'th element of nothing of particular.
I am trying to useappendStringInfoin PostgreSQL server code. In this case it should add a column name, but it appears empty. When printing ``` elog (INFO, "value:%s", idxcd->varattnames[i]); ``` the corresponding value appears to me. ``` for (i = 0; i < idxcd->ncols; ++i) { appendStringInfo( &cols, "attname=%s...
That is a trivial error: Your format string"attname=%s"has only a single placeholder (%s), but you supply two arguments. Only the first one will get used. Perhaps you mean something like: ``` appendStringInfo(&cols, "%s attname=%s", (i>0 ? "OR" : ""), idxcd->varatt...
I have built a C program (I downloaded the source code from the web) using the Microsoft Visual Stdio compiler. I am using the 2017 version of the Visual Studio . The code was compiled using make and running the compiler on the command line. Among the compiler flags used were: /Od /Zi I now want to use the Microsoft...
I added these two flags to my link line:/Od /ZiNow the command:devenv /debugexeis working.
What is the difference between declaring a thread-local variable using the dedicated keyword: ``` _Thread_local int var; ``` And using the specifictss_set of functions: ``` tss_t key; tss_create(&key, free); tss_set(key, malloc(sizeof(int))); int* pVar = tss_get(key); ``` From what I understand, the_Thread_localke...
Functionally, the important difference is the establishment of a destructor. In your example this isfree, but in fact it could be any function with the right signature. So this gives the possibility for a callback at the end of any thread for doing any kind of cleanup.
``` if(printf("Hello world")){} ``` The output for above code is ``` Hello world ``` My friend told me that the function printf returns the length of characters which is non zero here, so the condition is true. But I can't understand why it executes that printf statement. Shouldn't printf be executed only when it ...
Theexpressionwithinif(expression)isalwaysevaluated, and in your case that's a call toprintf. The value of this expression is used to determine if the body (blank in your case) of theifis run.
I've been looking for quite a while and cannot find the answer to my question. I'm trying to reproduce a shell in C, with full redirections. In order to do this, I wanted to open the file before executing my command. For example, inls > file1 > file2, I usedup2(file1_fd, 1)anddup2(file2_fd, 1)and then I executelsto ...
Is there a way to redirect standard output to multiple files? Many file descriptors cannot be made one file descriptor. You need to write into each file descriptor separately. This is whatteeutility does for you.
I see this in a code challenge before and was wondering if this was the same as passing a parameter to a program? Echo “string”| program.c
The shown code will probably not work at all, becauseprogram.c, if named according to the habits of practically any programmer, will be the pure C-code file, the "human readable" form of a program.To use this in any way as an executable, you first need to build it (compile and link). The result it usually an executabl...
This question already has answers here:Difference between fprintf, printf and sprintf?(9 answers)Closed3 years ago. Is there a difference between the following two statements: ``` fprintf(stderr, "Hello this is something\n"); printf("Hello this is something\n"); ``` If there is, what's the difference, and when woul...
For your specific 2 Ines of code, no they're not the same. printf only writes to stdout (not stderr) You would use fprintf when you want to write to a different stream then stdout.
The address space on my device is 8 bit. I have a 16 bit unsigned integer. I'd like to be able to use pointers to individually extract the data at the two registers which make up the 16 bit int. ``` uint16_t num = 12345; uint8_t *ptr1; uint8_t *ptr2; ``` Thanks for the help, pointers have been confusing for me.
You can take the address of the 16 bit variable and cast it to a pointer touint8_t, then add the necessary offset. ``` uint16_t num = 12345; uint8_t *ptr1 = ((uint8_t *)&num); uint8_t *ptr2 = ((uint8_t *)&num) + 1; ```
Is it acceptable to use the C standard library'srand()function for random numbers that donothave to be cryptographically secure? If so, are there still better choices? If not, what should be used? Of course, I assume theusual caveats about skewapply.
rand()suffers from some serious drawbacks. There is no guarantee on the quality of the random number. This will vary from implementation to implementation.The shared state used by different calls to rand, is not guaranteed to be thread safe. As for POSIX C alternatives, there israndomandrandom_r. OpenSSL provides mo...
I'm trying to make a program (just for fun) that requires something like this: ``` #define TEST "HELLO #define TEST2 WORLD\n" ... printf(TEST TEST2); ... ``` and I want the output to be HELLO WORLD however that code does not work. Is there any way to include newlines and double quotes like this in C?
Arranging the macros using\"toescapethe quotation gives you ``` #include <stdio.h> #define TEST "\"HELLO " #define TEST2 "WORLD\"\n" int main(void) { printf(TEST TEST2); } ``` and yields the output"HELLO WORLD"
As you all know, ANSI C does not require implementations to use ASCII code points for thechartype. However it does define a basic character set with alphanumeric characters, whitespace characters and other printable characters. Are there library functions to portably convert acharto its ASCII code and back?
Here are some functions to do the job, which return 0 if the character is not found; hopefully they are self-explanatory: ``` char const ascii_table[] = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; int char_to_ascii(int ch) { char const *p = strchr(ascii_tab...
This question already has answers here:Difference between fprintf, printf and sprintf?(9 answers)Closed3 years ago. Is there a difference between the following two statements: ``` fprintf(stderr, "Hello this is something\n"); printf("Hello this is something\n"); ``` If there is, what's the difference, and when woul...
For your specific 2 Ines of code, no they're not the same. printf only writes to stdout (not stderr) You would use fprintf when you want to write to a different stream then stdout.
The address space on my device is 8 bit. I have a 16 bit unsigned integer. I'd like to be able to use pointers to individually extract the data at the two registers which make up the 16 bit int. ``` uint16_t num = 12345; uint8_t *ptr1; uint8_t *ptr2; ``` Thanks for the help, pointers have been confusing for me.
You can take the address of the 16 bit variable and cast it to a pointer touint8_t, then add the necessary offset. ``` uint16_t num = 12345; uint8_t *ptr1 = ((uint8_t *)&num); uint8_t *ptr2 = ((uint8_t *)&num) + 1; ```
Is it acceptable to use the C standard library'srand()function for random numbers that donothave to be cryptographically secure? If so, are there still better choices? If not, what should be used? Of course, I assume theusual caveats about skewapply.
rand()suffers from some serious drawbacks. There is no guarantee on the quality of the random number. This will vary from implementation to implementation.The shared state used by different calls to rand, is not guaranteed to be thread safe. As for POSIX C alternatives, there israndomandrandom_r. OpenSSL provides mo...
I'm trying to make a program (just for fun) that requires something like this: ``` #define TEST "HELLO #define TEST2 WORLD\n" ... printf(TEST TEST2); ... ``` and I want the output to be HELLO WORLD however that code does not work. Is there any way to include newlines and double quotes like this in C?
Arranging the macros using\"toescapethe quotation gives you ``` #include <stdio.h> #define TEST "\"HELLO " #define TEST2 "WORLD\"\n" int main(void) { printf(TEST TEST2); } ``` and yields the output"HELLO WORLD"
As you all know, ANSI C does not require implementations to use ASCII code points for thechartype. However it does define a basic character set with alphanumeric characters, whitespace characters and other printable characters. Are there library functions to portably convert acharto its ASCII code and back?
Here are some functions to do the job, which return 0 if the character is not found; hopefully they are self-explanatory: ``` char const ascii_table[] = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; int char_to_ascii(int ch) { char const *p = strchr(ascii_tab...
Is it acceptable to use the C standard library'srand()function for random numbers that donothave to be cryptographically secure? If so, are there still better choices? If not, what should be used? Of course, I assume theusual caveats about skewapply.
rand()suffers from some serious drawbacks. There is no guarantee on the quality of the random number. This will vary from implementation to implementation.The shared state used by different calls to rand, is not guaranteed to be thread safe. As for POSIX C alternatives, there israndomandrandom_r. OpenSSL provides mo...
I'm trying to make a program (just for fun) that requires something like this: ``` #define TEST "HELLO #define TEST2 WORLD\n" ... printf(TEST TEST2); ... ``` and I want the output to be HELLO WORLD however that code does not work. Is there any way to include newlines and double quotes like this in C?
Arranging the macros using\"toescapethe quotation gives you ``` #include <stdio.h> #define TEST "\"HELLO " #define TEST2 "WORLD\"\n" int main(void) { printf(TEST TEST2); } ``` and yields the output"HELLO WORLD"
As you all know, ANSI C does not require implementations to use ASCII code points for thechartype. However it does define a basic character set with alphanumeric characters, whitespace characters and other printable characters. Are there library functions to portably convert acharto its ASCII code and back?
Here are some functions to do the job, which return 0 if the character is not found; hopefully they are self-explanatory: ``` char const ascii_table[] = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; int char_to_ascii(int ch) { char const *p = strchr(ascii_tab...
For example, in the code: ``` bool foo = bar || baz(); ``` the functionbaz()may not be called. I've found that this is a common source of bugs for me and I'm wondering if there's a way for GCC to print a warning.
There is not a warning flag for this, it would generate a warning for too many common conditions (if(condition) bar();,if(foo && foo->bar) baz();, etc). Instead, do something similar to this: ``` bool foo = baz() || bar; ``` or this: ``` bool foo = bar | baz(); ``` These unconditionally callbaz().
I have to print pointer parameters in ascending order and I was trying to use bubble sort algorithm, but the compiler doesn't sort in the right order. I'm only allowed to use one function. ``` void sort3(int *a, int *b, int *c){ int array[3]= {*a, *b, *c}; int temp, i,j; for(i=0;i<3;i++){ ...
You sort the local arrayarray, but you don't "return" the values back to the calling function. Without knowing the full context it seems like you should assign back to what the pointers are pointing to: ``` *a = array[0]; *b = array[1]; *c = array[2]; ```
``` #include <stdio.h> char *prg = "char *prg = %c%s%c;main(){printf(prg,34,prg,34);} " ; void main (){ printf(prg,34,prg,34); } ``` Reason behind the following output char *prg = "char *prg = %c%s%c;main(){printf(prg,34,prg,34);} ";main(){printf(prg,34,prg,34);}
the content in *prg Is printed but in place of "%c%s%c" the content is replaced, why is it embedded That's the wayprintf()works - in theformat(the firstprgargument), eachconversion specification(%c,%s) converts a subsequent argument (34,prg) according to the conversion specifier (c,s) and writes the result to the sta...
I have to print pointer parameters in ascending order and I was trying to use bubble sort algorithm, but the compiler doesn't sort in the right order. I'm only allowed to use one function. ``` void sort3(int *a, int *b, int *c){ int array[3]= {*a, *b, *c}; int temp, i,j; for(i=0;i<3;i++){ ...
You sort the local arrayarray, but you don't "return" the values back to the calling function. Without knowing the full context it seems like you should assign back to what the pointers are pointing to: ``` *a = array[0]; *b = array[1]; *c = array[2]; ```
``` #include <stdio.h> char *prg = "char *prg = %c%s%c;main(){printf(prg,34,prg,34);} " ; void main (){ printf(prg,34,prg,34); } ``` Reason behind the following output char *prg = "char *prg = %c%s%c;main(){printf(prg,34,prg,34);} ";main(){printf(prg,34,prg,34);}
the content in *prg Is printed but in place of "%c%s%c" the content is replaced, why is it embedded That's the wayprintf()works - in theformat(the firstprgargument), eachconversion specification(%c,%s) converts a subsequent argument (34,prg) according to the conversion specifier (c,s) and writes the result to the sta...
To re-name the args in main, I do the following: ``` int main(int argc, char *argv[]) { char * strings[argc]; for(int i=0; i<argc; i++) strings[i]=argv[i]; } ``` Out of curiosity, why wouldn't something like the following work instead: ``` int main(int argc, char *argv[]) { char * strings[argc] = argv; ...
That's simply because in C, an array cannot be initialized with another array. This has nothing to do withargvormain. Here's a simpler example of the same problem: ``` int a[] = {1, 2, 3}; int b[] = a; // error ```
Assume I have a structure like this in a C program: ``` if (res == NULL) { int i = 1; ... } else { int i = 2; ... } ``` Will I save some amount of memory if I instead write ``` int i; if (res == NULL) { i = 1; ... } else { i = 2; ... } ``` ? The variableiis not needed outside the ...
No compiler of even modest quality will generate better code for either case than the other unless, possibly, its optimization features are disabled.
I wrote this code to print a UTF-8 multibyte string. But it does not print properly. Note: I am doing it in a Linux system. ``` #include <stdio.h> #include <locale.h> int main() { char *locale = setlocale(LC_ALL, ""); printf("\n locale =%s\n", locale); printf("test\n \x263a\x263b Hello from C\n", locale)...
Use\uinstead of\x: ``` #include <stdio.h> #include <locale.h> int main() { char *locale = setlocale(LC_ALL, ""); printf("\n locale =%s\n", locale); printf("test\n \u263a\u263b Hello from C\n"); return 0; } ``` This runs and produces the following output: ``` $ gcc foo.c $ ./a.out locale =C test...
I've looked at multiple questions with the same issue, but unfortunately they have different kinds of problems with their loops. I would like the code to output "This is long enough" when a user has inputted text longer than one char. Every time I input something, I get prompted again for an answer. I'm new to c an...
Your while condition is wrong. Your loop will run until the user inputs text less than one char (ie no text). Remember the loop will run as long as the condition is true. Instead do: ``` while(length <= 1); ``` This will run as long as your string is one char or less and stop when you have more than one char.
``` # if RTC /* some code */ # endif ``` Should the macroRTCbe defined with a value? My compiler is not throwing an error. Do all compilers do the same? Isn't defining the macro safer?
In a preprocessing directive such as this, if the macro is not defined, it is treated as0. That is guaranteed by the language. You can rely on there not being a compilation failure. Here's the C++ wording: [cpp.cond]/11: After all replacements due to macro expansion and evaluations ofdefined-macro-expressions,has-...
Are there any significant differences between the following two methods of printing text using subscripts? Are there any pros/cons of using one method over the other? ``` #include <stdio.h> int main(void) { int i; char *text; /* method 1 */ text = "abc"; for (i = 0; i < 3; ++i) { printf...
Both methods are basically the same. The 2nd method could be slightly faster since your print function calls a static value ("abc") instead of a reference to "abc". I wouldn't be surprised if the compiler would make those 2 methods similar in the end. This being said, the first method should be better in most situat...
``` /*Linked list insertin deletion display ``` I have declared a global variable of struct node *head=NULL; linkedlistlinkedlistlinkedlisr=tlinkedlistlinkedlistlinkedlist linkedlistlinkedlistlinkedlisr=tlinkedlistlinkedlistlinkedlist ``` void insert(int x)//i guess the problem might be that temp is pointing to he...
temp->next=newis most likely your problem. At the top of the function you set temp to NULL and by using the->operator, you will be dereferencing a null pointer.
Are there any significant differences between the following two methods of printing text using subscripts? Are there any pros/cons of using one method over the other? ``` #include <stdio.h> int main(void) { int i; char *text; /* method 1 */ text = "abc"; for (i = 0; i < 3; ++i) { printf...
Both methods are basically the same. The 2nd method could be slightly faster since your print function calls a static value ("abc") instead of a reference to "abc". I wouldn't be surprised if the compiler would make those 2 methods similar in the end. This being said, the first method should be better in most situat...
``` /*Linked list insertin deletion display ``` I have declared a global variable of struct node *head=NULL; linkedlistlinkedlistlinkedlisr=tlinkedlistlinkedlistlinkedlist linkedlistlinkedlistlinkedlisr=tlinkedlistlinkedlistlinkedlist ``` void insert(int x)//i guess the problem might be that temp is pointing to he...
temp->next=newis most likely your problem. At the top of the function you set temp to NULL and by using the->operator, you will be dereferencing a null pointer.
Why is this allowed in C??? And what does it do? Full program can be seen here even though it is not necessaryhttp://www.learntosolveit.com/cprogramming/Ex_1.18_remtrailbt.html ``` for (i > 0; ((s[i] == ' ') || (s[i] == '\t')); --i) ```
Why is this allowed in C? Why should it not be allowed? The initialiser part of aforloop can contain an expression, or a declaration, or just be empty.i > 0is an expression like any other. Trying to somehow limit what goes there to just expressions with side effects would complicate the language for little benefit. ...
We have a production Socket code and often I find below code in it: ``` struct sockaddr_in* sin = (struct sockaddr_in*)to; (void)sin; ``` The variable sin is nowherfe further used? Since it is production code I am not sure if these statements has any importance at all? What is the code trying ti achieve here - from ...
It has a benign effect. It's primarily used to suppress compiler warnings about unused variables,sinin this case. Ifsinindeed is not used outside these two lines, then they can be safely removed. (I ban its use as it can lead to undefined behaviour and catastrophic optimisation on that branch ifsinis not initialised...
How can I know which version of C is supported by the VS2019 compiler? I looked in the project C/C++ and Linker command lines and found no -std=Cxx flag. The following code compiles: ``` for (int i = index; i < nb_users - 1; i++) { users[i] = users[i + 1]; } ``` So Iguessit's C99 according tothis, but is there a...
VS2019 supports ANSI C90 plus a few other features from a few later standards that are required in C++. For example, you can tell that C99 is not fully supported in MSVC with this code, which will fail to compile: ``` int foo(int n, char *s) { char s2[n]; strcpy(s2, s); return !strcmp(s, s2); } ``` This...
Has this patch been merged or rejected? Or the discussion has just ended without evolving? Maybe the fact that seccomp filters can be rewritten as binary trees is enough to don't add hash maps support for seccomp? https://groups.google.com/forum/#!msg/libseccomp/pX6QkVF0F74/ZUJlwI5qAwAJ Yes, I struggle to follow ker...
That patch has not been merged.seccomp-bpf still doesn't support eBPF bytecode or even just maps.Itseems unlikelythat seccomp-bpf will ever rely on eBPF instead of cBPF. Binary trees were indeed considered a good enough solution for anyone who needs very high seccomp-bpf performance. AlthoughI don't think libseccomp ...
In this code for linear search, after line 8 is executed it jumps to line 13 without executing the for loop. Output: Enter the size of array 5 Enter the elements Enter the element to be searched Here is the code: ``` #include<stdio.h> int main() { int array[100],search,c,n; printf("Enter the size of array\n...
You're not entering the for loop because of the conditionc > n, try change it toc < n. ``` for(c=0; c < n; c++) ```
I am trying to write a complex program in C, but I get absurd results. I tracked the error in the definition of a constant. With this MWE I can reproduce the problem of my program: ``` #include <stdio.h> #include <stdlib.h> #include <math.h> int main(){ double Md=pow(10.,-9.); /*double Md= 0.000000001;*/...
The default for%fis six decimal places, hence 0 is output. Be assured,Mdwill be non-zero in your debugger. printf("%.*lf\n", DBL_DIG, Md);is one way round this:DBL_DIGis introduced via<float.h>, although you'd be advised to get used toscientific notation ``` printf("%e\n", Md); ``` which will permit printing of ar...
they used to ship sources for the C runtime in previous versions of VS. Would someone perhaps know what would be the default location in VS2017? Do they still ship the code with it?
Ah.. found it in Visual Studio\2017\Community\VC\Tools\MSVC\14.12.25827\crt I hope the refactored code is as beautiful as the path is long.
I'm trying to add a user space program in xv6, but when I try to compile it gives error:"/usr/include/bits/stdio2.h:104: undefined reference to __printf_chk". Any help? My user program: ``` #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <sys/types.h> #includ...
You've compiled the program with yourhostheaders, which are from glibc, but you're trying to link it with the xv6targetlibraries. That's not going to work. You need to be using a proper cross compiler and taking care not to pollute it with-Ioptions that would bring in host headers or-Loptions that would bring in host ...
This question already has answers here:Comma operator in c [duplicate](3 answers)What does the comma operator , do?(8 answers)What does i = (i, ++i, 1) + 1; do?(7 answers)Closed4 years ago. With reference toComma-Separated return arguments in C function [duplicate], ``` x=x+2,x+1; ``` will be evaluated as ``` x=x+...
The statementreturn (x = x + 2, x + 1);is equivalent to: ``` x = x + 2; // x == 7 return x + 1; // returns 8 ```
I have a program that uses the <stdio.h> function dprintf. If I complie this without -std=c99 I have no problems, however if I try to compile wih this flag I'll get the "implicit function declaration" warning Does this mean that dprintf is not declared in <stdio.h> for c99? If so, where is the function declaration?
dprintfis not in C99. It's only in recent versions of POSIX. You can compile with-std=gnu99to include both C99 and POSIX functions (plus some extensions).
What does mean by these expression which I found somewhere and I can't find any effective search results to learn about them via examples or anything: ``` (*)[15] //how is this defined/used ``` And ``` int (*fun)(int)[1] ``` The second one is a function pointer but what is meant by[1]at the end?
``` fun // fun is... *fun // a pointer to... (*fun) (*fun)(int) // a function with an `int` parameter, returning... (*fun)(int)[1] // an array of size 1 of ... int (*fun)(int)[1] // int ``` Functions can't return arrays, so this type is invalid and can't be used in a C program.
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed4 years ago.Improve...
Change this statement ``` a=max; ``` to ``` max = a; ```
I'm trying to add a user space program in xv6, but when I try to compile it gives error:"/usr/include/bits/stdio2.h:104: undefined reference to __printf_chk". Any help? My user program: ``` #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <sys/types.h> #includ...
You've compiled the program with yourhostheaders, which are from glibc, but you're trying to link it with the xv6targetlibraries. That's not going to work. You need to be using a proper cross compiler and taking care not to pollute it with-Ioptions that would bring in host headers or-Loptions that would bring in host ...
This question already has answers here:Comma operator in c [duplicate](3 answers)What does the comma operator , do?(8 answers)What does i = (i, ++i, 1) + 1; do?(7 answers)Closed4 years ago. With reference toComma-Separated return arguments in C function [duplicate], ``` x=x+2,x+1; ``` will be evaluated as ``` x=x+...
The statementreturn (x = x + 2, x + 1);is equivalent to: ``` x = x + 2; // x == 7 return x + 1; // returns 8 ```
I have a program that uses the <stdio.h> function dprintf. If I complie this without -std=c99 I have no problems, however if I try to compile wih this flag I'll get the "implicit function declaration" warning Does this mean that dprintf is not declared in <stdio.h> for c99? If so, where is the function declaration?
dprintfis not in C99. It's only in recent versions of POSIX. You can compile with-std=gnu99to include both C99 and POSIX functions (plus some extensions).
What does mean by these expression which I found somewhere and I can't find any effective search results to learn about them via examples or anything: ``` (*)[15] //how is this defined/used ``` And ``` int (*fun)(int)[1] ``` The second one is a function pointer but what is meant by[1]at the end?
``` fun // fun is... *fun // a pointer to... (*fun) (*fun)(int) // a function with an `int` parameter, returning... (*fun)(int)[1] // an array of size 1 of ... int (*fun)(int)[1] // int ``` Functions can't return arrays, so this type is invalid and can't be used in a C program.
#define TITLES "* %10s * %10s %10s %11s *\n" is a bit of pre-code that I have in a buggy C program, and I have no idea what the numbers after the percent symbol do. I know that the percent symbolis the string format specifier symbol in C. However, I've only seen the percent symbol followed directly by a letter, rath...
Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger. http://www.cplusplus.com/reference/cstdio/printf/ ``` #include <cstdio> int main() { printf(">%10s<", "foo"); } ```...
It's in the build.gradle file. I'm following an online course and I don't really understand what these lines of codes are doing. Probably related to "defining the path of produced so file" ``` sourceSets { main.jniLibs { source { srcDirs = ['../libs'] } } }...
Here is the expected setup ``` android { sourceSets { main { jniLibs { srcDirs = ['../libs'] } } } } ```
Parts of the c code is as below: ``` char c[] = {'J', 'K', 'W'}; printf("%s\n", c); ``` And I don't know why it prints "JKWJKW" instead of "JKW".Isn'tchar c[] = {'J', 'K', 'W'}equal tochar c[] = "JKW"?
It's not equal: you forgot the terminating zero. It's present in "JKW", but not in the array initializer. As for why it prints "JKW" twice? By not zero-terminating the string, you've stumbled on undefined behavior. Your code can do pretty much anything at that point.
I ran across the following function declaration while looking at some generated C code from MPLabX's Code Configurator. ``` void __interrupt() INTERRUPT_InterruptManager(void) { ... } ``` What is the__interrupt()part of that declaration? I don't think it's a second return type, so what is it? In response to a coupl...
The compiler extends the C/C++ language by adding the __interrupt keyword, which specifies that a function is treated as an interrupt function. This keyword is an IRQ interrupt. The alternate keyword, "interrupt", may also be used except in strict ANSI C or C++ modes. For more information:__interrupt
I've never met...in a macro. What is this macro supposed to do? It computes the offset of member from the beginning of type, and then it computes the offset to the end of member field from the beginning of type. But how are these two values combined? ``` #define bpf_ctx_range(TYPE, MEMBER) \ offse...
It doesn'tcalculateanything. It is for use in thecase-rangeextension of GCC, so that you can write: ``` switch (byte_offset) { case bpf_ctx_range(foo_struct, bar_member): // do something... break; } ``` to find out which member the byte atoffsetwould belong to.
I ran across the following function declaration while looking at some generated C code from MPLabX's Code Configurator. ``` void __interrupt() INTERRUPT_InterruptManager(void) { ... } ``` What is the__interrupt()part of that declaration? I don't think it's a second return type, so what is it? In response to a coupl...
The compiler extends the C/C++ language by adding the __interrupt keyword, which specifies that a function is treated as an interrupt function. This keyword is an IRQ interrupt. The alternate keyword, "interrupt", may also be used except in strict ANSI C or C++ modes. For more information:__interrupt
I've never met...in a macro. What is this macro supposed to do? It computes the offset of member from the beginning of type, and then it computes the offset to the end of member field from the beginning of type. But how are these two values combined? ``` #define bpf_ctx_range(TYPE, MEMBER) \ offse...
It doesn'tcalculateanything. It is for use in thecase-rangeextension of GCC, so that you can write: ``` switch (byte_offset) { case bpf_ctx_range(foo_struct, bar_member): // do something... break; } ``` to find out which member the byte atoffsetwould belong to.
I've installed (OSX Mojave 10.14.6.) Eclipse CDT andGNU MCU Eclipse pluginand finalyGNU Tools for ARM. My goal is to build and debug ARM code using GDB (arm-none-eabi-gdb). I've created a Hello World project for Arm, which builds ok - but, debugging seems not to work with GDB (that comes with the Arm package). GDB ge...
Probably what is going on here is that you built to a given target (ARM based) and you're trying to run it (with gdb) on your mac (x86). You'll need an emulator or QEMU to properly run on your mac or maybe a real board.
This question already has answers here:How does the compare function in qsort work?(6 answers)Closed4 years ago. Is there a 'built-in'sort, in which theint (*compar)(const void *, const void*)does not need to be specified? For example, I find that about 99% of the time I'll do either a basic ascending or descending s...
I believe that qsort() is the only "build-in" sorting function in C. But if you write C++, std::sort() is also available.
My book says for programming using while-loop, we must first initialize with a number, provide the condition mentioning 'while', and then it's to be followed by the statement to partake in the loop until the condition is met as well as to increment value in the loop. Example : ``` i = 1; while(i<=10) { s = s + i; p =...
This line is the incrementing value: ``` i = i + 2; ``` The first loop increments by 1 withi++. But since you only want the odd numbers, you need to increment by 2. You can simplify this to: ``` i += 2; ```
This question already has answers here:Initialisation and assignment(6 answers)Closed3 years ago. In the below code a variable is initialized multiple times. Why is this code not throwing an error? ``` int main() { int x; x=5; x=10; printf("\nx=%d",x) ; } ``` Program Output x = 10
You're not doing any initializationat all. An initialization would be ``` int x = 0; ``` where you initialize the variable in the definition. With e.g. ``` x = 5; ``` you onlyassigna new value to the variablex. Non-constant variables are not immutable. You can assign a value to a variable as many times as you l...
I have created a 4B file with contentsasdf. However, when I do the following: ``` fseek(fptr, 0, SEEK_END); printf("%c", fgetc(fptr)); ``` The last character printed is?. I need to to do: ``` fseek(fptr, -1, SEEK_END); printf("%c", fgetc(fptr)); ``` for it to print the letterf. Why is this so? What is considered ...
Use this code snippet to see weird behavior reason. Code ``` int c = fgetc(fp); if (c == EOF && ferror(fp)) { fprintf(stderr, "%s\n", "ddd"); exit(EXIT_FAILURE); }else if(c == EOF){ fprintf(stderr, "%s\n", "EOF"); } ``` I think you reach to end of file andEOFwill be print. asEOFas a predefined constant ...
Is it possible to get thestructinfo (that is, the keys) of any struct? Or is required that you go to the manual page to read up what the actual structure is for that object. Take the following example: ``` struct stat stats; stat(filepath, &stats); printf("Size: %lld\n", stats.st_size); ``` Is it possible to do some...
You can read the man page, or you can read the header; there are no built-in introspection facilities in the C language that will inspectstructs for their attributes in any convenient way. In theory, if you compile the executable with debugging symbols a debugger might be able to tell you some of this (after loading ...
I currently want to make a program, called with system(), accept an input, in the case where the input is not an argument. As it may be a bit unclear, I am going to illustrate my question with a simple example. Let's assume we have 2 programs, askname.c and call.c askname.c ``` #include <stdio.h> #include <stdlib.h...
You don't. You use something else. Perhapspopen ``` FILE *fp = popen("./askname", "w"); fprintf(fp, "%s\n", foo); ```
I make program which exec 2 times this code. 2 process enter to semaphore and stuck(HERE comment). Why it happen and how to fix it? ``` sem_t *sem = sem_open(SEM_NAME, O_RDWR); if (sem == SEM_FAILED) { perror("sem_open(3) failed"); exit(EXIT_FAILURE); } int j = atoi(argv[1]); int i; for (i = 0; i < 2; i++) ...
You should create the semaphore using this ``` sem_open(SEM_NAME, O_RDWR,0777, 1); ``` to set the starting value of the semaphore to 1.
``` #include <stdio.h> int main(){ int a[1] = {1}; int b = 6; printf("%d\n", a[-1]); printf("%d\n", b); //printf("%d\n", (a-1 == &b)); return 0; } ``` I wrote the above code and found out it didn't work properly when using gcc or mingw to compile it, but when I uncommented 8th line, everythin...
Thea[-1]is undefined memory space.
I currently want to make a program, called with system(), accept an input, in the case where the input is not an argument. As it may be a bit unclear, I am going to illustrate my question with a simple example. Let's assume we have 2 programs, askname.c and call.c askname.c ``` #include <stdio.h> #include <stdlib.h...
You don't. You use something else. Perhapspopen ``` FILE *fp = popen("./askname", "w"); fprintf(fp, "%s\n", foo); ```
I make program which exec 2 times this code. 2 process enter to semaphore and stuck(HERE comment). Why it happen and how to fix it? ``` sem_t *sem = sem_open(SEM_NAME, O_RDWR); if (sem == SEM_FAILED) { perror("sem_open(3) failed"); exit(EXIT_FAILURE); } int j = atoi(argv[1]); int i; for (i = 0; i < 2; i++) ...
You should create the semaphore using this ``` sem_open(SEM_NAME, O_RDWR,0777, 1); ``` to set the starting value of the semaphore to 1.
Using the JDBC thin client, it is possible for the client to configure what is displayed in thePROGRAMcolumn of theV$SESSIONview (this is done by setting theCONNECTION_PROPERTY_THIN_VSESSION_PROGRAMconnection property). Is there a similar capability for a C program using OCI? There are ways to setCLIENT_INFO,MODULEa...
I haven't tried it, buthere's an archived blog post(with example C code) on the topic. The author says you can do it by overwritingargv[0]early in your program, and OCI will send that program name to the server, e.g. ``` prglen = strlen(argv[0]); strncpy(argv[0], "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", prglen...
I was commenting onWhy should I always enable compiler warnings?and pointed out In the embedded world, the warnings that worry me most are "possible loss of precision" and "comparison between signed and unsigned" warnings.I find it difficult to grasp how many "programmers" ignore these (in fact, I am not really sure ...
The message says "possible". Only the programmer can know if this is a true issue or not; the compiler cannot guess. "Surely it's just a disaster waiting to happen?" is an overstatement. Some loss of precision can just be harmless. I would rather fear over/underflow. Usually you know what you are doing with your data...
This question already has answers here:How does the Comma Operator work(9 answers)Closed4 years ago. I came across a#definestatement with the following expression. I do not understand what do the whole statement or the comma do that separate the 2 expressions within the parentheses. It seem like a function, I guess i...
Comma in C is just a sequential operator for expressions and construction an expression. That means that: ``` e1, e2, ..., en ``` is an expression whose value is the expression of en and evaluatese1, thene2, ... thenen
ERROR: type should be string, got "\nhttps://github.com/torvalds/linux/blob/33920f1ec5bf47c5c0a1d2113989bdd9dfb3fae9/include/linux/filter.h#L556-L571is this the implementation of the ebpf fallback interpreter?\n"
To complete pchaigno's answer: The selection forprog->bpf_funcis done bybpf_prog_select_runtime()defined inkernel/bpf/core.c, and called inkernel/bpf/syscall.cinbpf_prog_load(), i.e. when thebpf()system call is used with theBPF_PROG_LOADcommand. Selected runtime can be the in-kernel interpreter, a JIT-compiled functi...
This question already has answers here:Multiplication and division: weird output in c(3 answers)Closed4 years ago. I am using c preprocessor directive. I want to know how does this program work? ``` #define PRODUCT(x) (x*x) main() { int i=3,j; j=PRODUCT(i+1); printf("\n%d",j); } ``` The output is ...
Why do I get 7 withPRODUCT(i+1)? because3+1*3+1==3+3+1 Try#define PRODUCT(x) ((x) * (x))
I would like to convert acharacter arrayto adecimal array. For example, in the extended ASCII Table, lowercase q is 113. I would ask a prompt to get a text from the user and then the user might input "qqq", then input[] would be ['q','q','q'] and intinput[] would be ['113','113','113']. Is there a way to do this? Tha...
In the for loop try ``` for(l =0; input[l]!= '\0'; l++) { intinput[l] = (int)input[l]; } ```
This works: ``` int x = 4; function(&x); ``` These don't ``` function(&4); function(& (4)); ``` Why is that so? Is there a way to do it on "one-line" here?
The reason that this line does not work is because the number 4 is not a variable allocated on the memory. What I mean by that is, when you declared the variable X, the computer has allocated some space for it on the memory in some address. When you use the & you basically say - refer to the address in memory of that...
I am sort of self-learning the C language. ``` for(i=1;i<=k;i++) kfact = kfact * i; ``` Using the mathematical formula to calculate the factorial was tried. n! = n*(n-1)*(n-2)*(n-3)....*1, but I do not get how it correlates with the above mentioned code. ``` int k, kfact, i; kfact = 1; for(i=1;i<=k;i++) k...
The code you're looking at is not computing the factorial using yourn! = n*(n-1)*(n-2)*(n-3)....*1formula but rather on the equivalentn! = (n-1)! * nformula. It starts off with the factorial of 0, which is 1 and then, in each iteration, computes the factorial ofias the previous factorial(i-1)!timesi. So,kfactis firs...
I have a simple question that I couldn't find the answer for by googling -- is it possible to escape the C language's string null terminator '\0', so that we can include it in a string?
Note that a "string" with an embedded NUL is no longer astring. You cannot safely use it as an argument to functions declared in<string.h>, for example ``` char embeddednul[] = "zero\0one\0two\0"; // embeddednul[12] = embeddednul[13] = 0 printf("len: %d\n", strlen(embeddednul)); // 4?? char tmp[1000] = {0}; strcpy(tm...
Since bounded loop are now allowed in ebpf programshttps://git.kernel.org/pub/scm/linux/kernel/git/davem/net-next.git/commit/?id=2589726d12a1b12eaaa93c7f1ea64287e383c7a5does the verifier still check in the first pass if the program control flow is a Direct Acyclic Graph?
Yes,it still does, and rejects programs with back-edges in two cases: If the program is loaded by anunprivileged user. Theenv->allow_ptr_leaksboolean indicates a privileged user.If the back-edge isperformed using a call.Only normal jumps can make bounded loops(which doesn't mean you can't do a bpf-to-bpf callinsidea ...
I have a variable length MACRO from which i need to perform an operation based on the argument that is passed. Is there a way to get the argument with index directly using__VA_ARGS__? ``` #define OPERATION5(_1) (_1) #define _GET_1ST_ARG( N, ...) (N) #define TOP_MACRO(...){\ OPERATION##(_GET_1ST_ARG(1));\ } ``...
You need first expand then concatenate the identifiers with another macro passYou need to remove the braces when getting the first argument. The(can't be concatenated. ``` // CONCATenate #define CONCAT(a, b) a ## b // eXpand then CONCATenate #define XCONCAT(a, b) CONCAT(a, b) #define OPERATION5(_1) (_1) // remov...
I came from python and it was easy to get the middle digit of an integer, for example, from 897 I want the 9: ``` >>> num = 897 >>> num2 = int(str(num)[1]) >>> num2 9 ``` But how i can do this on C? It's so difficult to convert into string...
Getting a single digit as anintcan be done mathematically: ``` int num = 897; int dig1 = (num / 1 ) % 10; int dig2 = (num / 10 ) % 10; int dig3 = (num / 100 ) % 10; ``` Division by one on the first line is only for illustration of the concept: you divide by n-th power of ten, starting with 100= 1.
I am sort of self-learning the C language. ``` for(i=1;i<=k;i++) kfact = kfact * i; ``` Using the mathematical formula to calculate the factorial was tried. n! = n*(n-1)*(n-2)*(n-3)....*1, but I do not get how it correlates with the above mentioned code. ``` int k, kfact, i; kfact = 1; for(i=1;i<=k;i++) k...
The code you're looking at is not computing the factorial using yourn! = n*(n-1)*(n-2)*(n-3)....*1formula but rather on the equivalentn! = (n-1)! * nformula. It starts off with the factorial of 0, which is 1 and then, in each iteration, computes the factorial ofias the previous factorial(i-1)!timesi. So,kfactis firs...