question
stringlengths
25
894
answer
stringlengths
4
863
This question already has answers here:What does a colon in a struct declaration mean, such as :1, :7, :16, or :32?(3 answers)Closed6 years ago. I'm working with a piece of code and I come across with something similar to this: ``` struct { int a : 1; int b : 1; }; ``` I don't know what is the function of: 1here. For your interest, that struct is inside aunionwhich in turn is inside atypedef struct. Thanks,
This is used to assign value to abit. You can read about bitfieldshere.
In the C programming language, a string such as"2147483649"overflows as an int since the largest unsigned int is2147483647. When I want to convert strings of integers toints, how do I go about checking for these overflow cases? I can't just check if it is>=-(2^32-1)and<= (2^32-1)since the process of converting this string to anint(egatoi()) already changes this value. Is there an easy way instead of checking the number of digits of the string before converting and also each digit at a time to make sure it's within the range ofints?
You can convert the resulting integer back to string and compare it to the source string. Although it doesn't look elegant to me. :-)
So i'm trying to extracts bits from a 32=bit binary integer using bit shifting and masking, but i'm sightly off by one. ``` #include <stdio.h> int main (){ int number = 87; //0000 000 0000 0000 0000 0000 0101 0111 int i; int bit; int g = 0; for(i = 32; i > 0; i--){ if(g%4==0 && g!=0){ printf(" "); } g++; bit = (number >> i) & 1; printf("%d", bit); } printf("\n"); return 0; } ```
There is logic missing in your code.. Use ``` for(i **= 31**; i **>=** 0; i--) ``` instead of ``` for(i **= 32**; i **>** 0; i--) ``` Comment if it works for you
My Source Code ``` for(i=0;str[i]!='\0';i++) { if(str[i]!=' '){ str2[j]=str[i]; flag=1; } if(flag==1 && str2[j]!=' ') { printf("\n"); printf("%c",str2[j]); flag=0; } } ``` My Output: ``` I am joe I a m j o e ``` But I want output like this: ``` I am joe ``` I want each of the word prints in new line likeIin one lineamin another line andjoein another line also need to remove extra space beforejoe
I found it easier to just replace the space characters by new lines ``` #include <stdio.h> int main() { char str[] = "I am joe"; for(int i = 0; str[i] != '\0'; i++) { if(str[i] == ' ') str[i] = '\n'; } printf("%s\n", str); return 0; } ``` All you have to figure out is how to trim those extra spaces....
The arrayoptionscontains elements of this form: "-option=value". The argumentneeded_optioncontains for example "option" ``` char *function(char *options[], char *needed_option){ for(//go over all possible options){ if(fnmatch("-???=*", options[i], 0) == 0){ //<--- look here char *ret = extract_value_from_option(); return ret; } } } ``` Question: Is there a way to genericly replace the "???" with the function - argumentneeded_optionlike its done inprintf()where achar *can be included by using the%s?
prepare it withsprintf() ``` char current[256]; sprintf(current, "-%s=*", needed_option); //... if(fnmatch(current, options[i], 0) == 0){ //... ```
When we're defining a 2D array as in: ``` int *a[5]; ``` Which dimension does the "5" define? The first or the second?
It's not a "2D" array. It's a 1-dimensional array of pointers toint. As such the array size designates that it has space for 5 pointers. Each individual pointer can point to the first element of a buffer with different size. A "true 2D array" is the colloquial "array of arrays"int a[M][N]. Here the expressiona[i]evaluates to the array ofNintegers, at positioni.
Everytime I compile and run c file, I have to type: gcc filename.c a.out I don't want to do this in two lines, How to compile and run in one line on linux terminal?
Try ``` gcc filename.c && a.out ``` It only runs the second command if the first was successful. Seehttps://askubuntu.com/questions/334994/which-one-is-better-using-or-to-execute-multiple-commands-in-one-line
I'm just trying to make some kind of pointer to "Nall" struct so I wrote this code ``` Nall **headall; headall = malloc (30000 * sizeof (Nall)); for (i = 0; i < 30000; i++) { *(headall+i) = newNall; } ``` and now I get this error "warning: incompatible pointer types assigning toNall *(akastruct nodeall *) fromNall *(void)(akastruct nodeall *(void)) [-Wincompatible-pointer-types]*(headall+i) = newNall;"
From the compiler warning I'm assuming thatnewNallis actually a function that allocates a newstruct nodealland returns a pointer to it. In that case, your code should look like this: ``` Nall **headall; headall = malloc(30000 * sizeof *headall); for (i = 0; i < 30000; i++) headall[i] = newNall(); ``` Note the argument to thesizeofoperator, and the parentheses afternewNall.
This is my C code: ``` #include <stdio.h> #include <stdlib.h> typedef struct node * ptr; typedef struct node { int data; ptr next; } item; void printList(ptr p); int main() { ptr h = NULL; } void printList(ptr p) { while(p) { printf("%d -> \n", ptr -> data); ptr = ptr -> next; } } ``` I get 2 errors when I compile the code: ``` error: unexpected type name 'ptr': expected expression printf("%d -> \n", ptr -> data); ^ error: expected identifier or '(' ptr = ptr -> next; ``` I tried to play around with all kind of changes but I don't understand why I'm getting these errors.
You're referring to the type of the structure member not the structure member. ``` printf("%d -> \n", ptr -> data); ptr = ptr -> next; ``` should be ``` printf("%d -> \n", p->data); p = p->next; ```
The .txt file will have the matrix we need to input into our program, it may have more than one matrices. I am using VIM editor on Linux. Is there any specific escape sequence to copy the .txt file while compiling?
To redirect standard output to a file, the>character is used like this: ls > file_list.txt And To take input from the file , the<character is used like this: ./a.out < input.txt
I created a file with this content:abcand I would like to read (only with theread()function, please don't suggest another one) it and display it on the console with this program: ``` #include <stdio.h> #include <unistd.h> #include <fcntl.h> int main() { int fd; char buf[3]; int size; fd = open("test",O_RDONLY); for (int i=0;i++;i<3){ size = read(fd,buf,1); // Version 2 used buf+i printf("%c\n", buf[i]); } close(fd); return 0; } ``` I'm asking to the read function to retrieve bytes one by one, and ascharsare one byte size I though it would work. But nothing displays on the console when executing. Any clue?
Each call toreadputs the character at the start ofbuf, but you don't always print that part ofbuf.
In the following code,2is printed. ``` int x = 1; int f(int y) { return x; } int main() { x = 2; printf("%d", f(0)); } ``` How is it happening if we have static scoping in C? Why isn't1printed? Printing2in this case isn't a dynamic scoping, is it? I thought that in static scoping it should take the nearest x to the function definition.
It does take the nearestx, but since you only have onexit doesn't really matter. If you change the code to ``` int x = 1; int f(int y) { return x ; } int main() { int x=2; printf("%d", f(0)); } ``` so you have 2x, the global one and the local one inmainyou will see1getting printed.
I have a similar code. ``` #include <stdio.h> int main() { FILE* file = fopen("file.txt", "w+"); fputc('A', file); fflush(file); char buff; fscanf(file, "%s", &buff); printf("read data: %s", &buff); fclose(file); return 0; } ``` I want without close file read written data. But in buff not exist data. Why? If i close file after writing and then read all worked.
You should userewind(file)to set the position indicator associated with the file stream to the beginning of the file. Your example, working fine: ``` #include <stdio.h> int main() { FILE* file = fopen("file.txt", "w+"); fputc('A', file); fflush(file); rewind (file); char buff [80]; fscanf(file, "%s", buff); printf("read data: %s", buff); fclose(file); return 0; } ```
I am a newbie in Eclipse and STM32. So I would like to ask you for an advice with a problem which I have been solving. I have got a software for STM32. This software is written in C language and has an existing Makefile. The software is now placed on the SVN server. I need to build the project in Eclipse Neon 4.6.2 IDE running on Windows 7. I have installed the whole GNU ARM Toolchain according to tutorialMastering STM32. Please can anybody direct me on any step by step instructions how to do that? Thanks in advance.Sed utility warning message
sedis a unix utility. Maybe executed as a part of your makefile. The error message is hidden by the second widnow. If it suggests, try to install it on your machine. I use GNU/Linux where it is essential part of the distribution. On Windows you can find a binary after some search.
I asked this onTaking an index out of const char* argumentalong with another question, but debate got only to the first question, so I splitted it to a different thread. Question: Is there any reason anyone would ever want to represent a C string asconst char*and not asconst unsigned char*? On one hand, I see the commonly used representation of C str asconst char*all the time.On the other hand, usingconst char*sometimes forces a cast to unsigned, like in the example linked above. Thanks,
Yes, of course a general read-only string should beconst char *, sincechar(with unspecified implementation-specified signedness) is the default type for a character. In other words, a literal like"foo"consists ofchar, notunsigned char, elements. Of course you can interpret the characters as unsigned if you feel like it, but then you might need a cast.
I have to recode these 3 functions in C and the goal is that the recoded functions have to replace the system functions in different programs or system calls. I don't really understand what is the behaviour of these functions since I've read the mans, I just know I'm allowed to usebrk()andsbrk().
mallocbasically pre allocates memory pages (Cfgetpagesize(2)), and returns pointer to usable parts of those pre allocated areas when called.mallocthen have to "remember" which part of those pre allocated memory segments are being used, and which one are free. Reading this article:https://www.cocoawithlove.com/2010/05/look-at-how-malloc-works-on-mac.htmlmight help! (I know it was great help to me when i re-coded malloc on mac Os as an university assignment ;)).
``` int main(){ char s[]="hi "; char t[55]; fgets(t,55,stdin); strcat(s,t); puts(s); } ``` I want to concatenate the stringssand the entered stringt, but I'm not getting any output. I have tried usinggetsto read thestringbut the compiler says "use of gets can be dangerous". What should I do?
strcat(s,t);is overrunning the destination memory buffers, as it is only large enough for 4 characters (and one of those is occupied by the NUL-terminator). The behaviour of your program is thereforeundefined. Make the size ofslarge enough to accommodate its initial contentsplusthe largest string possible int.
So I know that ``` struct bit { unsigned char a : 1; } ``` will still take up a byte because of padding, my question is this: ``` struct bit { unsigned char a : 1; ... unsigned char h : 1; } ``` Will this struct take up the same size as a char? And if so, am I better off just using acharinstead? I'm asking because I want to use bits as a key, but I'd rather avoid bitwise operations if possible.
There is no guarantees of anything when using bit-fields. That struct can have any size and any bit order. In factunsigned chartype for bit-fields is not even supported by the standard! Your code is already relying on non-standard extensions. Forget about bit-fields, forget aboutchar. You should useuint8_tand bitwise operators if you want predictable, portable code.
We are developing a software on Hi3536 processor based board. TheSDKprovided byHiSiliconcomes with samples for developing user interface using frame buffer API - which is too low level. i.e., to design Combo Box, Text box, we have to write code from Scratch. We are now trying to use QT. Not sure what other vendors do use for developing software on Hi3535 or Hi3536. Can somebody suggest whichSDKis most suitable for developing user Interface onHiSiliconprocessor based boards ?
We referred the sample code given in the following link and we would bring up the GUI successfully in Hi3536 using QT 5.6 -http://bbs.ebaina.com/thread-8217-1-1.html. Please note that you need to use Google translator to translate the text in chinese.
I am experiencing a problem with C language while I am trying to adapt a callback written in C to C++. Compiler shows the following error: ``` error C2664: 'fread' : cannot convert parameter 4 from 'void *' to 'FILE*' 1>Conversion from 'void*' to pointer to non-'void' requires an explicit cast ``` I found that thissize_t retcode = fread(ptr, size, nmemb, stream)needs acast. I've tried, but nothing works. Here is the code: ``` static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *stream) { curl_off_t nread; size_t retcode = fread(ptr, size, nmemb, stream); nread = (curl_off_t)retcode; fprintf(stderr, "*** We read %" CURL_FORMAT_CURL_OFF_T " bytes from file\n", nread); return retcode; } ```
``` fread(ptr, size, nmemb, static_cast<FILE*>(stream)) ```
How to print the formatting characters such as:%pout? A backslash doesn't do any good as it does with quotations(""). I tried it in a simple toy program and I suppose the value returned by it was garbage : What I was trying to print was the statement : ``` With the formatting character %p and '&' ```
Using double percentage i.e.%%will print single%for you: ``` printf("With the formatting character %%p and '&'\n"); ```
If I usefork()to spawn a child process, then will the child process automatically terminate once the parent process terminates? Or must this be programmed?
This isn't really a c question, it's an O/S question. In Windows, a process will continue until either it callsExitProcessor when it has performed enough CPU RETs that there's nothing left in the call stack. In Unix, the process will continue and run as a subprocess ofinit. On both O/S's, a user with enough permissions can kill the process. Threads, on the other hand, are a different matter-- they will terminate when the process terminates.
I have a char array composed of hex values that looks similar to this: ``` char str[] = "\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b" "\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd" "\x80\xe8\xdc\xff\xff\xff"; ``` After manipulating this string, I want tofprintfthis string to a file using this statement: fprintf(fp, "%X\n", str); but I'm getting an output similar to this: ``` 65C58A20 ``` Seems like it got condensed to a single hex number. How can Ifprintfthestrin the same form I declared it above, with separate hex values for each individual byte?
What you need is this: ``` for (size_t i = 0; i != sizeof str - 1; ++i) fprintf(fp, "\\x%02x", (unsigned char)str[i]); ```
In the following code,2is printed. ``` int x = 1; int f(int y) { return x; } int main() { x = 2; printf("%d", f(0)); } ``` How is it happening if we have static scoping in C? Why isn't1printed? Printing2in this case isn't a dynamic scoping, is it? I thought that in static scoping it should take the nearest x to the function definition.
It does take the nearestx, but since you only have onexit doesn't really matter. If you change the code to ``` int x = 1; int f(int y) { return x ; } int main() { int x=2; printf("%d", f(0)); } ``` so you have 2x, the global one and the local one inmainyou will see1getting printed.
I have a similar code. ``` #include <stdio.h> int main() { FILE* file = fopen("file.txt", "w+"); fputc('A', file); fflush(file); char buff; fscanf(file, "%s", &buff); printf("read data: %s", &buff); fclose(file); return 0; } ``` I want without close file read written data. But in buff not exist data. Why? If i close file after writing and then read all worked.
You should userewind(file)to set the position indicator associated with the file stream to the beginning of the file. Your example, working fine: ``` #include <stdio.h> int main() { FILE* file = fopen("file.txt", "w+"); fputc('A', file); fflush(file); rewind (file); char buff [80]; fscanf(file, "%s", buff); printf("read data: %s", buff); fclose(file); return 0; } ```
I am a newbie in Eclipse and STM32. So I would like to ask you for an advice with a problem which I have been solving. I have got a software for STM32. This software is written in C language and has an existing Makefile. The software is now placed on the SVN server. I need to build the project in Eclipse Neon 4.6.2 IDE running on Windows 7. I have installed the whole GNU ARM Toolchain according to tutorialMastering STM32. Please can anybody direct me on any step by step instructions how to do that? Thanks in advance.Sed utility warning message
sedis a unix utility. Maybe executed as a part of your makefile. The error message is hidden by the second widnow. If it suggests, try to install it on your machine. I use GNU/Linux where it is essential part of the distribution. On Windows you can find a binary after some search.
I asked this onTaking an index out of const char* argumentalong with another question, but debate got only to the first question, so I splitted it to a different thread. Question: Is there any reason anyone would ever want to represent a C string asconst char*and not asconst unsigned char*? On one hand, I see the commonly used representation of C str asconst char*all the time.On the other hand, usingconst char*sometimes forces a cast to unsigned, like in the example linked above. Thanks,
Yes, of course a general read-only string should beconst char *, sincechar(with unspecified implementation-specified signedness) is the default type for a character. In other words, a literal like"foo"consists ofchar, notunsigned char, elements. Of course you can interpret the characters as unsigned if you feel like it, but then you might need a cast.
I have to recode these 3 functions in C and the goal is that the recoded functions have to replace the system functions in different programs or system calls. I don't really understand what is the behaviour of these functions since I've read the mans, I just know I'm allowed to usebrk()andsbrk().
mallocbasically pre allocates memory pages (Cfgetpagesize(2)), and returns pointer to usable parts of those pre allocated areas when called.mallocthen have to "remember" which part of those pre allocated memory segments are being used, and which one are free. Reading this article:https://www.cocoawithlove.com/2010/05/look-at-how-malloc-works-on-mac.htmlmight help! (I know it was great help to me when i re-coded malloc on mac Os as an university assignment ;)).
``` int main(){ char s[]="hi "; char t[55]; fgets(t,55,stdin); strcat(s,t); puts(s); } ``` I want to concatenate the stringssand the entered stringt, but I'm not getting any output. I have tried usinggetsto read thestringbut the compiler says "use of gets can be dangerous". What should I do?
strcat(s,t);is overrunning the destination memory buffers, as it is only large enough for 4 characters (and one of those is occupied by the NUL-terminator). The behaviour of your program is thereforeundefined. Make the size ofslarge enough to accommodate its initial contentsplusthe largest string possible int.
So I know that ``` struct bit { unsigned char a : 1; } ``` will still take up a byte because of padding, my question is this: ``` struct bit { unsigned char a : 1; ... unsigned char h : 1; } ``` Will this struct take up the same size as a char? And if so, am I better off just using acharinstead? I'm asking because I want to use bits as a key, but I'd rather avoid bitwise operations if possible.
There is no guarantees of anything when using bit-fields. That struct can have any size and any bit order. In factunsigned chartype for bit-fields is not even supported by the standard! Your code is already relying on non-standard extensions. Forget about bit-fields, forget aboutchar. You should useuint8_tand bitwise operators if you want predictable, portable code.
We are developing a software on Hi3536 processor based board. TheSDKprovided byHiSiliconcomes with samples for developing user interface using frame buffer API - which is too low level. i.e., to design Combo Box, Text box, we have to write code from Scratch. We are now trying to use QT. Not sure what other vendors do use for developing software on Hi3535 or Hi3536. Can somebody suggest whichSDKis most suitable for developing user Interface onHiSiliconprocessor based boards ?
We referred the sample code given in the following link and we would bring up the GUI successfully in Hi3536 using QT 5.6 -http://bbs.ebaina.com/thread-8217-1-1.html. Please note that you need to use Google translator to translate the text in chinese.
I am experiencing a problem with C language while I am trying to adapt a callback written in C to C++. Compiler shows the following error: ``` error C2664: 'fread' : cannot convert parameter 4 from 'void *' to 'FILE*' 1>Conversion from 'void*' to pointer to non-'void' requires an explicit cast ``` I found that thissize_t retcode = fread(ptr, size, nmemb, stream)needs acast. I've tried, but nothing works. Here is the code: ``` static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *stream) { curl_off_t nread; size_t retcode = fread(ptr, size, nmemb, stream); nread = (curl_off_t)retcode; fprintf(stderr, "*** We read %" CURL_FORMAT_CURL_OFF_T " bytes from file\n", nread); return retcode; } ```
``` fread(ptr, size, nmemb, static_cast<FILE*>(stream)) ```
How to print the formatting characters such as:%pout? A backslash doesn't do any good as it does with quotations(""). I tried it in a simple toy program and I suppose the value returned by it was garbage : What I was trying to print was the statement : ``` With the formatting character %p and '&' ```
Using double percentage i.e.%%will print single%for you: ``` printf("With the formatting character %%p and '&'\n"); ```
If I usefork()to spawn a child process, then will the child process automatically terminate once the parent process terminates? Or must this be programmed?
This isn't really a c question, it's an O/S question. In Windows, a process will continue until either it callsExitProcessor when it has performed enough CPU RETs that there's nothing left in the call stack. In Unix, the process will continue and run as a subprocess ofinit. On both O/S's, a user with enough permissions can kill the process. Threads, on the other hand, are a different matter-- they will terminate when the process terminates.
I have a char array composed of hex values that looks similar to this: ``` char str[] = "\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b" "\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd" "\x80\xe8\xdc\xff\xff\xff"; ``` After manipulating this string, I want tofprintfthis string to a file using this statement: fprintf(fp, "%X\n", str); but I'm getting an output similar to this: ``` 65C58A20 ``` Seems like it got condensed to a single hex number. How can Ifprintfthestrin the same form I declared it above, with separate hex values for each individual byte?
What you need is this: ``` for (size_t i = 0; i != sizeof str - 1; ++i) fprintf(fp, "\\x%02x", (unsigned char)str[i]); ```
If I have this little C code (that I compile with:gcc -m32 -o code code.c): ``` int main(){ char tab[3]; tab[0]='a'; tab[1]='b'; tab[2]='c'; return 0; } ``` How can I use GDB (or another program) to get a general overview of the stack like: ``` ADRESSES VALUES 0xbffff260 0x61 0xbffff261 0x62 0xbffff262 0x63 ``` Thank you p.s:The values should be 0x61, 0x62, 0x63 for a,b,c respectively.
To show the variables of the local stack try using the gdb command: ``` where ``` If you want the variables of each frame that exists in the program then try using: ``` where full ``` Then if you want to select a specific frame use: ``` frame <frame#> ``` EDIT: Also, try compiling with -g flag. ``` gcc -g code.c -o code ``` So you can debug in gdb.
I'm facing a piece of code that I don't understand: ``` read(fileno(stdin),&i,1); switch(i) { case '\n': printf("\a"); break; .... ``` I know thatfilenoreturn the file descriptor associated with thesdtinhere, thenreadput this value inivariable. So, what should be the value ofstdinto allowito match with the first "case", i.e\n? Thank you
But what should be the value of stdin to match with the first "case", i.e \n ? The case statement doesn't look at the "value" of stdin. ``` read(fileno(stdin),&i,1); ``` reads in a single byte intoi(assumingread()call is successful) and if that byte is\n(newline character) then it'll match the case. You probably need to read the man page ofread(2)to understand what it does.
I am reading a excerpt from -Charles Petzold's book on C++ Windows It states The virtual key codes you use most often have names beginning with VK_ defined in the WINUSER.H header file. I have looked inside the WINUSER.H file, and from what I have seen all Virtual Key codes begin win VK_. If this is not the case, can somebody point out where I have gone wrong?
You misinterpreted the English grammar. The sentence in itself is ambiguous, but in a larger context it becomes clear. The author wanted to say: You usually use the virtual key codes, instead of the scan codes of the keys.The virtual key codes have names starting withVK_.The scan codes have names starting withSC_. By the way, the exact reference is Chapter 6, section Keystroke Messages. The paragraph above your quote talks about scan codes and virtual key codes. The paragraph you quoted concentrates on the virtual key codes.
I'm facing a piece of code that I don't understand: ``` read(fileno(stdin),&i,1); switch(i) { case '\n': printf("\a"); break; .... ``` I know thatfilenoreturn the file descriptor associated with thesdtinhere, thenreadput this value inivariable. So, what should be the value ofstdinto allowito match with the first "case", i.e\n? Thank you
But what should be the value of stdin to match with the first "case", i.e \n ? The case statement doesn't look at the "value" of stdin. ``` read(fileno(stdin),&i,1); ``` reads in a single byte intoi(assumingread()call is successful) and if that byte is\n(newline character) then it'll match the case. You probably need to read the man page ofread(2)to understand what it does.
I am reading a excerpt from -Charles Petzold's book on C++ Windows It states The virtual key codes you use most often have names beginning with VK_ defined in the WINUSER.H header file. I have looked inside the WINUSER.H file, and from what I have seen all Virtual Key codes begin win VK_. If this is not the case, can somebody point out where I have gone wrong?
You misinterpreted the English grammar. The sentence in itself is ambiguous, but in a larger context it becomes clear. The author wanted to say: You usually use the virtual key codes, instead of the scan codes of the keys.The virtual key codes have names starting withVK_.The scan codes have names starting withSC_. By the way, the exact reference is Chapter 6, section Keystroke Messages. The paragraph above your quote talks about scan codes and virtual key codes. The paragraph you quoted concentrates on the virtual key codes.
This question already has answers here:What is the rationale for one past the last element of an array object?(2 answers)Closed6 years ago. The standard states: Unless both pointers point to elements of the same array object or one past the last element of the array object, the behavior is undefined. Why is it valid to reference one past the last element?
It's okay to compute that pointer and compare to it only. The reason being that it can be used to pass and iterate over and array using a pair of pointers. If it was not allowed by the standard, the following loop would have exhibited undefined behavior by the mere existence ofpend ``` int arr[100] = {0}; for (int *pbegin = arr, *pend = arr + 100; pbegin != pend; ++pbegin) { // do stuff } ``` This is especially important in C++, where the idiom of passing a range as "an iterator to the beginning and one-past the end" is used heavily by the standard library.
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed6 years ago. For this code ``` int j=2; int c=(j++)*(j++); printf("%d\n",c); ``` I get the value of c as 6 While for below code ``` int j=2; int c=(++j)*(++j); printf("%d\n",c); ``` I get the value of c as 16 Can someone please explain this case to me ?
You are simultaneously modifying the value of a variable, and using that variable in an expression. As such, your code is exhibitingundefined behavior. Undefined behavior is exactly that; anything can happen. There is no logical way to predict what values will result from the code you have written.
I have this code in C ``` int main(){ int t = 1; while(t != 0) t = t + 1; return 0; } ``` What would be the equivalent in Python? In C, although it appears as such, it's not an infinite loop. Would it be similar in Python?
Python integers are not limited in constant number of bytes, only in your RAM limits. This loop would go forever, until your computer runs out of memory. Usesys.getsizeof(int())andsys.getsizeof(int(2**128))to test this behaviour. Anyway, the equivalent that terminates is ``` t = 1 while t < 2**32: t += 1 ``` (Considering 32-bit integers)
My application starts with different resolutions depending on whether I build it in Debug or Release configuration. This behavior is unwanted and unexpected. Window is created this way: ``` screen->window = SDL_CreateWindow(WINDOW_TITLE, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, screen->width, screen->height, SDL_WINDOW_SHOWN); ``` screen-width and screen-height are defined in a header. ``` #define SCREEN_WIDTH 1024 #define SCREEN_HEIGHT 800 ``` When I run it with DEBUG configuration, it seems to run in the desktop display mode (1080p). In release, it runs as if the desktop was 1024x800. vs
The problem was that the application had "Disable display scaling on high DPI settings" option enabled in application properties. When I disabled it, the issue went away.
My task is going like this: Write a recursive functionint calculate(node *root, int lvl, int defaultlvl)that will calculate the sum of all nodes at the default lvl and all progenys of those nodes. I got in my task this information. ``` typedef struct node { int value; struct node *left, *right; } node; ```
You will not get a answer for homework without showing some effort at trying to solve the problem... Here is a simple function that sums the whole tree. Modify it to handle the level limitation is the assignment: ``` int calculate(node *root) { if (root) { return root->value + calculate(root->left) + calculate(root->right); else return 0; } ```
I want the program to print the wordhelloto the text file by means of strings. ``` #include <stdio.h> void main () { char word[10] = {"hello"}; FILE*fp; fp = fopen("C:\\temp\\Dictionary.txt", "w+"); fprintf(fp, word[0]); } ```
You're printing first char instead of the string. And it might not be a valid format either. Correct call will befprintf(fp, "%s", word). And don't forget to close file too.
I need to create a function that recursively adds up each digit in a large number. For example, if the user inputs the number143, the function should return1+4+3which is8. How can I do this?
The idea is that given a number, you can sum its digits by recursively summing the number without its last digit sum, and add the last digit. Calculating the last digit is simplex%10, and getting the number without the last digit isx/10. The base case when you hit 0 (you removed all digits) - return 0. ``` int sum_digits(int x) { if (x == 0) return 0; return x%10 + sum_digits(x/10); } ```
Could someone explain why I can move through the memory locations for the char * but not for the int * using the following code: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void){ int * a = malloc(48); char * s = malloc(27); for (int i = 0;i<26;i++) s[i] = i+65; int intSize = sizeof(int); printf("%d\n",intSize); for(int i = 0;i<12;i++){ a[i] = i; printf("%d %d %c\n",*(a+i*intSize),a[i],*(s+i)); } return 0; } ```
when you declare a variable e.g. ``` int* a; char* b; ``` all offsets are in the end calculated as byte offsets, the size of the offset depends on the type. soa + 1is in realitya + sizeof(int)andb + 1is in realityb + sizeof(char) the compiler handles this, it makes it easier to read the code otherwise you would always have to calculate how many bytes a type has when looping through an array and such
I have to show an error when I access an item outside of an array (without creating my own function for it). So I just thought it was necessary to access the value out of the array to trigger a segfault but this code does not crash at all: ``` int main(){ int tab[4]; printf("%d", tab[7]); } ``` Why I can't get an error when I'm doing this?
When you invokeundefined behavior, anything can happen. You program may crash, it may display strange results, or it may appear to work properly. Also, making a seemingly unrelated change such as adding an unused local variable or a simple call toprintfcan change the way in which undefined behavior manifests itself. When I ran this program, it completed and printed 63. If I changed the referenced index from 7 to 7000, I get a segfault. In short, just because the programcancrash doesn't mean itwill.
I'm on a linux box and/proc/self/exedoes seem to be supported: ls -l /proc/self/exeshows that it's linked to/usr/bin/lsat the moment I run the commandrealpath /proc/self/exeprints out/usr/bin/realpathas expectedboth commands exit with status0 But: ``` if (NULL == realpath("/proc/self/exe", NULL)) { printf("this prints unexpectedly, %s\n", strerror(errno)); } ``` At this point,errnois22and I seeInvalid argument. Why? Or -- how does one figure out why?
This behavior would occur onglibcversions below 2.3 as stated inman realpath: ERRORS............EINVAL -pathisNULL. (In glibc versions before 2.3, this error is also returned ifresolved_pathisNULL.)
I try to split any number of two digits and get result in two different variables. I had a problem with a specific number:23. ``` int root = 23; float div = (float)root/10.0; // div = 23.0/10.0 = 2.3 int left = (int)div; // left = 2 int right = ((float)div - (float)left) * 10.0; // right = (2.3 - 2) * 10.0 = 0.3 * 10.0 = 3 printf("%d", right); // 2, why ? ``` There is a lot of float-to-int operations and I got some troubles with the final result. Have I miss or didn't catch something ?
Since 0.3 may not be represented exactly in binary, you end up with 2.9999… that became2when converted to anint. Instead: ``` int root = 23; int left = root / 10; int right = root % 10; ```
Is it possible to multiply usingi**in C? For example, I can incrementiusingi++. Why doesn'ti**work in C? ``` #include <stdio.h> int main(void) { int result; for (int i = 2; i < 100; i**){ result = i + 1; printf("%i\n", result); } return 0; } ```
No, it's not possible. There is no operator like**in C unlike unary increment (++) and decrement (--) operators. You should have tryi *= i.
In atom, when I write any code incorrectly I can view the errors immediately because the file is being scanned by a plugin. I have the vs code plugin for c/c++ but I do not see this option to display errors. Is this available and I am just failing with my google skills? Or is this not an option with vs code?
The VSCode plugin for C++ doesnotsupport "intellisense" at the moment. It supports debugging and some basic symbol parsing (with code completion) but it doesn't parse your code using a compiler. For more info:https://code.visualstudio.com/docs/languages/cpp
Why is the following legal: ``` typedef struct a aType; struct a { int x; aType *b; }; ``` and the following illegal: ``` void main() { typedef struct a aType; aType someVariable; struct a { int x; aType *b; }; } ``` I'm just curious as in each case it is forward referencing and as far as I know, at least for functions and variables, forward referencing is not legal. Also, would the answer for this be the same for C++ as well?
You are allowed to create pointers to incomplete types, because the size of the pointer object does not depend on the size of the pointed-to type. Pointers to differentstructtypes have the same size and representation, regardless of the size of thestructtype itself. You are not allowed to createinstancesof incomplete types, since the size of the type isn't known.
Is it possible to multiply usingi**in C? For example, I can incrementiusingi++. Why doesn'ti**work in C? ``` #include <stdio.h> int main(void) { int result; for (int i = 2; i < 100; i**){ result = i + 1; printf("%i\n", result); } return 0; } ```
No, it's not possible. There is no operator like**in C unlike unary increment (++) and decrement (--) operators. You should have tryi *= i.
In atom, when I write any code incorrectly I can view the errors immediately because the file is being scanned by a plugin. I have the vs code plugin for c/c++ but I do not see this option to display errors. Is this available and I am just failing with my google skills? Or is this not an option with vs code?
The VSCode plugin for C++ doesnotsupport "intellisense" at the moment. It supports debugging and some basic symbol parsing (with code completion) but it doesn't parse your code using a compiler. For more info:https://code.visualstudio.com/docs/languages/cpp
Why is the following legal: ``` typedef struct a aType; struct a { int x; aType *b; }; ``` and the following illegal: ``` void main() { typedef struct a aType; aType someVariable; struct a { int x; aType *b; }; } ``` I'm just curious as in each case it is forward referencing and as far as I know, at least for functions and variables, forward referencing is not legal. Also, would the answer for this be the same for C++ as well?
You are allowed to create pointers to incomplete types, because the size of the pointer object does not depend on the size of the pointed-to type. Pointers to differentstructtypes have the same size and representation, regardless of the size of thestructtype itself. You are not allowed to createinstancesof incomplete types, since the size of the type isn't known.
I wrote a small program to check if my number is a prime number or not. I think the code works fine, but I want the code to give me a single output: if it's a prime number or not. I tried to find it on Google, but can't find an answer. ``` #include <stdio.h> #include <stdlib.h> #include <stdbool.h> int main() { int z1,z_eingabe; bool b1=true; while(1){ printf("Zahl : "); scanf("%d",&z_eingabe); for(z1=2;z1<z_eingabe;z1++){ if(z_eingabe%z1==0){ printf("False %d\n",z1); b1=false; break; } if(b1==true){ if(z_eingabe%z1!=0){ printf("True\n"); break; } } } } return 0; } ```
use a boolean value and set it totrue. when you find a number that devides the input, put the value tofalseandbreakthe loop. at the end test your boolean:true -> printf("Ja\n"); false -> printf("Nein\n");
In atom, when I write any code incorrectly I can view the errors immediately because the file is being scanned by a plugin. I have the vs code plugin for c/c++ but I do not see this option to display errors. Is this available and I am just failing with my google skills? Or is this not an option with vs code?
The VSCode plugin for C++ doesnotsupport "intellisense" at the moment. It supports debugging and some basic symbol parsing (with code completion) but it doesn't parse your code using a compiler. For more info:https://code.visualstudio.com/docs/languages/cpp
Why is the following legal: ``` typedef struct a aType; struct a { int x; aType *b; }; ``` and the following illegal: ``` void main() { typedef struct a aType; aType someVariable; struct a { int x; aType *b; }; } ``` I'm just curious as in each case it is forward referencing and as far as I know, at least for functions and variables, forward referencing is not legal. Also, would the answer for this be the same for C++ as well?
You are allowed to create pointers to incomplete types, because the size of the pointer object does not depend on the size of the pointed-to type. Pointers to differentstructtypes have the same size and representation, regardless of the size of thestructtype itself. You are not allowed to createinstancesof incomplete types, since the size of the type isn't known.
I wrote a small program to check if my number is a prime number or not. I think the code works fine, but I want the code to give me a single output: if it's a prime number or not. I tried to find it on Google, but can't find an answer. ``` #include <stdio.h> #include <stdlib.h> #include <stdbool.h> int main() { int z1,z_eingabe; bool b1=true; while(1){ printf("Zahl : "); scanf("%d",&z_eingabe); for(z1=2;z1<z_eingabe;z1++){ if(z_eingabe%z1==0){ printf("False %d\n",z1); b1=false; break; } if(b1==true){ if(z_eingabe%z1!=0){ printf("True\n"); break; } } } } return 0; } ```
use a boolean value and set it totrue. when you find a number that devides the input, put the value tofalseandbreakthe loop. at the end test your boolean:true -> printf("Ja\n"); false -> printf("Nein\n");
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.Closed6 years ago.Improve this question I've got multiple float numbers to print: ``` {3.00, 3.20, 2.23, 5.00, 3.40 } ``` They all have 2 decimal places, however if there are two zero's after a decimal, it needs to be displayed as a whole number. How can I convert3.00into3and5.00into5? it is conversion not printing
There is no way todirectly(i.e. using only the format specifier) print either two decimals or zero for a number ending in e.g.3.20. You need to check if the number ends with.00beforehand; for example: ``` if((int)round(num * 100) % 100 == 0) // if decimals are `.00` printf("%.0f", num); else // not `.00` printf("%.2f", num); ``` If3.2is okay for3.20, then the%gspecifier might also be of some use.
``` for (minus == false ? i = 0 : i = 1; string[i] >= '0' && string[i] <= '9'; ++i) { intValue = string[i] - '0'; minus == false ? result = result * 10 + intValue : result = result * 10 - intValue; } ``` error: expression is not assignable screenshot -http://share.pho.to/AarcJ https://codeshare.io/5Pdd7X
minus == false ? i = 0 : i = 1will be parsed as(minus == false ? i = 0 : i) = 1because of operator precedence rule. After evaluation ofminus == false ? i = 0 : i, left side of operator=will become an rvalue, but assignment operator must have an lvalue as its left operand.Change it tominus == false ? (i = 0) : (i = 1)
Let's say we have the following C code: ``` #include<stdio.h> int main(){ char *a = "askakasd"; return 0; } ``` I tried to find my local variable "a", but I don't know how to recognize it looking in this output, where p is the C code compiled:
It's not there. Since the code can't tell at execution time whether it's there or not, the linker removed it to save space.
How to convert char array to its equivalent ascii decimal array ? I tried in QT using QString and QbyteArray. But it is not working. i/p: "1,9,10,2" o/p: "4944574449484450" (1's ascii decimal value is 49, , ascii decimal value is 44, 9's ascii decimal value is 57, and so on..).
How to convert char array to its equivalent ascii decimal array ? You do not, it is already stored that way. If you want to print your array as decimal numbers for ASCII just output it accordingly (as integers): ``` char str[] = "1,9,10,2"; for( const char *s = str; *s; ++s ) std::cout << static_cast<int>( *s ) << ","; // just output number instead of character ``` charin C++ is a numerical type similar toint, difference isstd::ostreamoutputscharas a symbol andintand other integer types as integer.
Probably really trivial question, but: Recently started working an open-source system -janus-gatewayand i am in a need to run a method every 1 second(checking if all users muted). What are the options to do this in C? Should i spawn a new thread? Answer with an example would much appreciated!
Ended up spawning a new thread and doing stuff that way.
Let's say we have the following C code: ``` #include<stdio.h> int main(){ char *a = "askakasd"; return 0; } ``` I tried to find my local variable "a", but I don't know how to recognize it looking in this output, where p is the C code compiled:
It's not there. Since the code can't tell at execution time whether it's there or not, the linker removed it to save space.
How to convert char array to its equivalent ascii decimal array ? I tried in QT using QString and QbyteArray. But it is not working. i/p: "1,9,10,2" o/p: "4944574449484450" (1's ascii decimal value is 49, , ascii decimal value is 44, 9's ascii decimal value is 57, and so on..).
How to convert char array to its equivalent ascii decimal array ? You do not, it is already stored that way. If you want to print your array as decimal numbers for ASCII just output it accordingly (as integers): ``` char str[] = "1,9,10,2"; for( const char *s = str; *s; ++s ) std::cout << static_cast<int>( *s ) << ","; // just output number instead of character ``` charin C++ is a numerical type similar toint, difference isstd::ostreamoutputscharas a symbol andintand other integer types as integer.
Probably really trivial question, but: Recently started working an open-source system -janus-gatewayand i am in a need to run a method every 1 second(checking if all users muted). What are the options to do this in C? Should i spawn a new thread? Answer with an example would much appreciated!
Ended up spawning a new thread and doing stuff that way.
Probably really trivial question, but: Recently started working an open-source system -janus-gatewayand i am in a need to run a method every 1 second(checking if all users muted). What are the options to do this in C? Should i spawn a new thread? Answer with an example would much appreciated!
Ended up spawning a new thread and doing stuff that way.
What is wrong with this code? I'm trying to compare string and white space. ``` void main() { char d; int i; char* mystring="Vikram Natarajan"; char c=mystring[0]; printf("%c\n",c); for(i=0;i<100; i++) { if(mystring[i]==" ") { d=mystring[i+1]; } } printf("%c\n",d); } ```
Replace if(mystring[i]==" ") With if(mystring[i]==' ') Use a single quote for char comparison.
char[i] stands for declaration of a variable both a char array and a string. I know that C adds a null character to the end of the array if it is a string. However, how does C know when to add the null character, in other words, in what stage?
it doesn't, C "strings" are just an assumption about arrays ( that they have a 0 somewhere indicating the end of the string) There is no type "string" in C, just libraries which deal with char arrays with the above assumption. It is completely up to the library functions to manage the arrays and work out when to terminate them if needed. Quite often these functions don't respect what memory was actually allocated for the array, it will assume there's enough allocated space for whatever it's doing It would be entirely possible to use pascal type strings in C and write a string library using that convention if one wished.
I would like to specify the name of a C include file at compile time as a C flag. e.g. ``` #include MY_INCLUDE_FILE int main(int argc, const char * argv[]) {...} ``` Would be expaned by the pre-processor to ``` #include "some_incfile.h" int main(int argc, const char * argv[]) {...} ``` Doing something like this ``` gcc -DMY_INCLUDE_FILE="some_incfile.h" main.c ``` I have attempted using the stringizing operator # to expand but have only gotten errors such aserror: expected "FILENAME" or <FILENAME> Is this even possible? -D define is not entirely necessary, the important part is that the include filename can be set from the gcc command line
You have to escape the ": ``` gcc -DMY_INCLUDE_FILE=\"some_incfile.h\" main.c ```
In shell sort,3h+1sequence is recommended to h-sort a list using insertion sort //1, 4, 13, 40, ... Optimal formula to compute start value ofhis one-third oflistsize, as shown below, ``` int h = 1; while(h < listSize/3){ // why N/3? h = 3*h + 1 } while(h >= 1){ //h-sort the array // perform insertionSort h = h/3; } ``` Question: To perform shell sort, How to prove mathematically thath(at max) should be less thanlistSize/3?
If we continue to increasehafter condition(h < listSize/3),hbecomes larger thanlistSize, and there is no sense in h-sorting - we cannot compare itemsA[i]andA[i+h]because the second index is beyond list range.
I'm trying to figure out how theAttachedInterruptworks on the NodeMCU. Everything I found tells me that this code is OK?! ``` void setup() { Serial.begin(9600); pinMode(D4, INPUT); attachInterrupt(D4, doSth(), CHANGE); } void loop() { Serial.println(digitalRead(D4)); delay(100); } void doSth() { Serial.println("Check!"); } ``` But I just get this error: I still have no idea after hours of research! Thanks a lot in advance :-)
Problem solved — Thanks again! I just usedattachInterrupt(D4, doSth, CHANGE); instead ofattachInterrupt(D4, doSth(), CHANGE);
Is the behavior of writing a non-printing character undefined or implementation-defined, if the character is written viaprintf/fprintf? I am confused because the words in the C standard N1570/5.2.2 only talks about the display semantics for printing characters and alphabetic escape sequences. In addition, what if the character is written viastd::ostream(C++ only)?
The output of ASCII non-printable (control) characters is implementation defined. Specifically, interpretation is the responsibility of the output device. Edit 1:When the output device is opened as a file, it can be opened asbinary. When opened asbinarythe output is not translated (e.g. line endings).
This question already has answers here:How to find the size of an array (from a pointer pointing to the first element array)?(17 answers)Closed6 years ago. Lets be the following code: ``` int x; int *p = &x; int t[3]; ``` Then sizeof returns: ``` sizeof(x) -> 4 sizeof(p) -> 8 sizeof(t) -> 12 ``` I suppose thatsizeof(t)is the result of3 * sizeof(int). But astis a pointer to his first element, its size should besizeof(p). Whysizeof(t)returns the size of the memory block which represents the array ? Thanks.
tis anint[3]type,nota pointer type. So its size is3 * sizeof(int). In certain instances,tdecaysto a pointer, but this is not one of those instances.
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.Closed6 years ago.Improve this question I want to use DB2 10.5 on Linux for XA transactions. Does DB2 include a XA transaction manager? How can I setup my C application for a XA transaction environment?
DB2 LUW 10.5 supports XA transaction managers, but does not include one. If you want to work with one,programming in C is supported.
I am loging error messages using ``` #define LOG_INFO(...) do{ fprintf(fpLogFile, __VA_ARGS__ ); } while( FALSE ) #else #define LOG_INFO(...) do{ } while ( FALSE ) ``` and thefpLogFileis opened usingfopen.fopencreates0KBfile even if there are no errors. If a0KBfile is created, a job is triggered. Hence I want to create the log only if there are errors. How can I acheive this usingfopenare there any other ways?
SetfpLogFiletoNULL, and before eachfprintf, check if it is stillNULL. If so, open the file.
I'm trying to reverse unsigned int of 32 bit, want to turn zeros to ones, and ones to zeros, but seems there is something wrong. input: 3 output: 4294967292 expected output: 2147483648 ``` int main() { unsigned int n; scanf("%u",&n); n^=4294967295; printf("%u",n); return 0; } ```
Your expectation is wrong. Let's do everything in hexadecimal: ``` 0x00000003 ^ 0xffffffff = 0xfffffffc ``` The correct output in hexadecimal is therefore0xfffffffcwhich is4294967292in (unsigned) decimal. Or in binary: ``` 00000000000000000000000000000011 0x00000003 ^ 11111111111111111111111111111111 0xffffffff ---------------------------------- ---------- 11111111111111111111111111111100 0xfffffffc ```
As far as I know there is no such thing as a layout in ncurses however I am wondering if there isn't a third party extension which allows that. I'm looking for support for the typical layouts such as horizontal, vertical and grid. Of course being able to automatically resize the "children" of a layout is a plus.
no - the space available for characters is usually small enough that no one bothers with more than a few choices in fixed-layouts. Some applications resize, but use simple schemes for layout, e.g., all of the screen, half, etc.
I have to read a binary file in my webserver and send it to client via TCP. I decided to read it by chunks. How can I do it? My code with fgets works only with text files (code, that checks return values is omitted): ``` char buf[2048]; fgets(buf, sizeof(buf), fp); while (!feof(fp)) { Server_TCP_Send(socket, buf, strlen(buf)); fgets(buf, sizeof(buf), fp); } fclose(fp); ```
Usefread()instead offgets(), and pay attention to the return value: ``` char buf[2048]; size_t buflen; while (1) { buflen = fread(buf, 1, sizeof(buf), fp); if (buflen < 1) { if (!feof(fp)) { // a read error occured... } break; } Server_TCP_Send(socket, buf, buflen); } fclose(fp); ``` Alternatively, some platforms have functions for sending files over a socket. For example,sendfile()on Linux, orTransmitFile()on Windows.
I have this: ``` typedef struct{ field_1; field 2; ..... }student; typedef struct{ student record[100]; int counter; }List; ``` Then I want to add the information for each 'student', for example: ``` List *p; gets(p->list[index]->field_1); ``` but when I compiled the code it threw this: ``` [Error] base operand of '->' has non-pointer type 'student' ``` So why can't I point to 'list' and way to access a specific 'record' in 'list'?
Adding code snippet that may help you to read/write the values to the records. Free the pointer to a struct when you're done. ``` typedef struct{ int age; int marks; }student; typedef struct{ student record[100]; int counter; }List; int main() { List *p = (List*)malloc(sizeof(List)); p->record[0].age = 15; p->record[0].marks = 50; p->counter = 1; free(p); return 0; } ```
I want to receive ethernet packets from socket in Linux, but only those, which have one of two custom Ethtype values. As I know, if only 1 ethtype should be received, it's possible to specify this value while creating socket like this ``` int socket = socket(PF_PACKET, SOCK_RAW, htons(ETHERTYPE_CUSTOM_1); ``` But what if I have 2 different ethtypes? Should I use 2 sockets or write some custom filter? Or is there some any simple way?
Create two sockets, one for each ethertype. Then you can useselect()orepoll()to wait for packets on either socket at the same time.
I have this: ``` typedef struct{ field_1; field 2; ..... }student; typedef struct{ student record[100]; int counter; }List; ``` Then I want to add the information for each 'student', for example: ``` List *p; gets(p->list[index]->field_1); ``` but when I compiled the code it threw this: ``` [Error] base operand of '->' has non-pointer type 'student' ``` So why can't I point to 'list' and way to access a specific 'record' in 'list'?
Adding code snippet that may help you to read/write the values to the records. Free the pointer to a struct when you're done. ``` typedef struct{ int age; int marks; }student; typedef struct{ student record[100]; int counter; }List; int main() { List *p = (List*)malloc(sizeof(List)); p->record[0].age = 15; p->record[0].marks = 50; p->counter = 1; free(p); return 0; } ```
I want to receive ethernet packets from socket in Linux, but only those, which have one of two custom Ethtype values. As I know, if only 1 ethtype should be received, it's possible to specify this value while creating socket like this ``` int socket = socket(PF_PACKET, SOCK_RAW, htons(ETHERTYPE_CUSTOM_1); ``` But what if I have 2 different ethtypes? Should I use 2 sockets or write some custom filter? Or is there some any simple way?
Create two sockets, one for each ethertype. Then you can useselect()orepoll()to wait for packets on either socket at the same time.
I'd like to measure the time that each thread spends doing a chunk of code. I'd like to see if my load balancing strategy equally divides chunks among workers. Typically, my code looks like the following: ``` #pragma omp parallel for schedule(dynamic,chunk) private(i) for(i=0;i<n;i++){ //loop code here } ``` UPDATE I am using openmp 3.1 with gcc
You can just print the per-thread time this way (not tested, not even compiled): ``` #pragma omp parallel { double wtime = omp_get_wtime(); #pragma omp for schedule( dynamic, 1 ) nowait for ( int i=0; i<n; i++ ) { // whatever } wtime = omp_get_wtime() - wtime; printf( "Time taken by thread %d is %f\n", omp_get_thread_num(), wtime ); } ``` NB thenowaitthan removes thebarrierat the end of theforloop, otherwise this wouldn't have any interest. And of couse, using a proper profiling tool is a way better approach...
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed6 years ago.Improve this question When I clicked on some of my Windows Program, it gives me this error: What causes this error? And how do I fix it?
Here is your answer :https://msdn.microsoft.com/en-us/library/ms173740.aspx In short, just repair/reinstall it.
I was writing a program and had to handle buffers. But when I employed some loops I realized that the buffer was not being flushed after each iteration and withheld its last input value. I searched on the internet and found this code line. It works but I don't know what this means.fseek(stdin,0,SEEK_END);
It moves the read/write pointer to the end of the file/stream and so it needs to be flushed. seeTutorialspoint ``` int fseek(FILE *stream, long int offset, int whence) ``` Parameters stream− This is the pointer to a FILE object that identifies the stream. offset− This is the number of bytes to offset from whence. whence− This is the position from where offset is added. It is specified by one of the following constants − SEEK_SET: Beginning of fileSEEK_CUR: Current position of the file pointerSEEK_END: End of file
I have encountered this question while I was studying for a test. Given answers were: a)'a'b)'\n'c)'012'd)'\0' I tried to find the general rule but I failed.
Only'\n', of the listed 4, is certainly affected by writing to a file in a text mode instead of binary mode. With atext file, thenew-line character'\n'is commonly translated to/from'\n'(no change),"\r\n", or rarely\r'. '012'is a multi-character constant with an implementation defined value, unlikely to be affected by the mode. The unlisted'\012'is acharacter constantemploying anoctal escape sequence. It behaves like'\n'when ASCII is the source encoding. The unlisted012is anoctal constant. It behaves like'\012'. Sneaky test if you ask me.
I try to free structure pointer using function and then check for NULL. It doesn't work! ``` typedef struct{ int * num; } D; void freeD(D * a){ free(a->num); free(a); a=NULL; } int main(){ D * smth = malloc(sizeof(D)); smth->num = malloc(sizeof(int)*2); freeD(smth); if(smth==NULL){ printf("It's NULL"); } } ```
You have to pass the pointer by reference that is by using pointer to the pointer. For example ``` void freeD(D ** a){ free( ( *a )->num); free(*a); *a=NULL; } //... freeD( &smth ); ```
!I had written this simple program on a different Ubuntu PC using Gedit]1
You do not have execute permissions for your executable. Use ``` chmod +x ./secondo ``` first to correct this. Thisquestion gives more detail.
!I had written this simple program on a different Ubuntu PC using Gedit]1
You do not have execute permissions for your executable. Use ``` chmod +x ./secondo ``` first to correct this. Thisquestion gives more detail.
I am reading data from a serial port (in an Arduino) and framing it (syncing on a few bytes). To do that, I am reading the data into a big buffer. Once I got the frame, I extract data and I want to send it to a different serial port usingserial.write(Serial.write(buf, len)) which accepts a byte array and its size. Since the data size can be random, I need something like a dynamic array (which is not recommended in Arduino). Any ideas?
Since the data size can be random, I need something like a dynamic array In C you rarely need a dynamic array, because arrays passed to functions do not carry their size with them. That is why all functions that take an array also take length. Let's say you have your data insidebigBufferat positionstartPos, and you wish to sendlengthbytes. All you need to do is ``` Serial.write(&bigBuffer[startPos], length); ``` or with pointer arithmetic syntax ``` Serial.write(bigBuffer+startPos, length); ```
How to define a variable using another variable.Actually I want a whole string but that string should contain data from another variable. ``` #include <stdio.h> char *Data1 = "23"; char *Data2 = "267"; char *Data = ("www.mywebsite.com?c=%s&v=%s", Data1, Data2); int main() { printf(Data); return 0; } ```
You can define an array and make use ofsprintf()/snprintf()to generate the final string. Something like ``` char final[128] = {0}; //128 is arbitrary value int data1 = 23; //no need to be string for integer value int data2 = 267; snprintf(final, 128, "www.mywebsite.com?c=%d&v=%d", data1, data2); ``` That said,printf(Data);is very invalid. You either use the proper format specifier, likeprintf("%s", final);useputs(final);
Considering this code: ``` limit = sizeof(str1)-strlen(str1)-1; strncat(str1,str2,limit); ``` Ifstr2length is greater thanlimit, doesstrncatNul terminatesstr1or I have to add this code, like in the case ofstrncpy? ``` str1[sizeof(str1)-1] = '\0' ```
It always null-terminate. QuotingC11, chapter §7.24.3.2, (emphasis mine) Thestrncatfunction appendsnot more thanncharacters(a null character and characters that follow it are not appended) from the array pointed to bys2to the end of the string pointed to bys1. The initial character ofs2overwrites the null character at the end ofs1.A terminating null character is always appended to the result. and, the footnote Thus, the maximum number of characters that can end up in the array pointed to bys1isstrlen(s1)+n+1.
I'm usingtypedefto definesetas aboolarray: ``` typedef struct set{ bool Arr[128]; }set; ``` the problem is that every time I try to assign a t/f value, e.g. ``` temp[itemp]=true; ``` (tempis asetas defined anditempis anint), I get the error: ``` subscripted value is neither array nor pointer nor vector ``` I have no idea how to fix this, please help. PS :I'm using C on ubuntu.
what you've done is an alias calledsetto a struct containing an array of bools with the size of 128. This means, that to access the memberArr, you need to use the member access operator.like so: ``` temp.Arr[itemp] = true; ``` If you don't want to do that, you can typedef the array like so: ``` typedef bool set[128]; ``` So you can access it directly: ``` set s = { false }; s[1] = true; ```
I have a text file that contains Persian text like this: یک (U+06CC, U+06A9). and I want to read this file into a string then store it in an output file. I'm using this code: ``` char *locale = setlocale(LC_ALL, "en_US.UTF-8"); FILE *in = fopen("test.txt", "r"); FILE *out = fopen("out.txt", "w"); wint_t c; while ((c = fgetwc(in)) != WEOF) { putwchar(c); fprintf(out, "%c ", c); } fclose(in); fclose(out); ``` It doesn't work. What I expect: تست (U+062A, U+0633, U+062A).
It's only a minor error; for wide characters you need: ``` fprintf(out, "%lc ", c); - ``` or ``` fwprintf(out, L"%lc ", c); - - - ``` Then, itworks for me. (Also the file gets space-separated characters.)
How can I make a check if there is a space inside the array string? Could you help me? Thanks in advance ;) ``` for ( i = 0; string[i] != '\0'; ++i ) if ( string[i]) != ' ' ) ``` error: expected expression
You can use standard functionstrchr(string, ' ')- return a non-NULL pointer ifstringhas space inside: ``` if(strchr(string, ' ')) { // printf( "string contain space" ); } ``` Refer tostrchrfunction: 7.24.5.2 The strchr function ``` #include <string.h> char *strchr(const char *s, int c); ``` 3 The strchr function returns a pointer to the located character, or a null pointer if the character does not occur in the string.
I want to build a function which gets equation (string) likeax^2+bx+c=0(ex:"3x^2+8=0") and geta,b,cparameters. Here is my code: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #define STR_LEN 25 void getABC(char str[]); int a=0, b=0, c=0; int main(void) { char equation[STR_LEN]={0}; printf("Enter an equation:\n"); fgets(equation, STR_LEN, stdin); equation[strcspn(equation, "\n")]=0; getABC(equation); return 0; } void getABC(char str[]) { // how to get a, b and c? } ```
You can Do this instead ``` int a ; int b ; int c ; printf("Enter Equation : "); scanf("%dx^2+%dx+%d" , &a , &b , &c); printf("%d %d %d" , a ,b , c); ``` For Example If you enter3x^2+4x+10, then3will be stored ina, it will ignorex^2and+and then store4inband then it will ignorexand+and store10inc.