question
stringlengths
25
894
answer
stringlengths
4
863
When I outputed0x0a(\n) to file using putc() and viewed it in a HEX-viewer, there was0x0d(\r) in the previous byte. I used latest MinGW to compile the program. How do I output 0x0a on its own?
You must be working on a DOS/Windows system. This linefeed translation is a MS legacy feature for text files. You can open the file in "binary" mode, then line ends will not be translated: ``` FILE *fp=fopen("file.name","wb");//"b" means binary putc('\n',fp); ```
The manual page "man system" contains the following section: If command is NULL, then a nonzero value if a shell is available, or 0 if no shell is available. which basically indicates that I can check withif(system(NULL) != 0) {foo;}if a shell is currently available or not. When do I have to consider to do so? B...
Also fromman system: [...] even though POSIX.1-2001 requires a conforming implementation to provide a shell, that shell may not be available or executable if the calling program has previously calledchroot(2)[...] So that's a possible case where/bin/shmight not be available. In practice I wouldn't worry too much abo...
The manual page "man system" contains the following section: If command is NULL, then a nonzero value if a shell is available, or 0 if no shell is available. which basically indicates that I can check withif(system(NULL) != 0) {foo;}if a shell is currently available or not. When do I have to consider to do so? B...
Also fromman system: [...] even though POSIX.1-2001 requires a conforming implementation to provide a shell, that shell may not be available or executable if the calling program has previously calledchroot(2)[...] So that's a possible case where/bin/shmight not be available. In practice I wouldn't worry too much abo...
I am trying to get rid of all\characters in a string in C. For example, if a string isco\din\git should convert the string tocoding. So far I have the code ``` for(i = 0; i < strlen(string); ++i){ if(string[i] == '\'){ } } ``` That looks to see if there is a backslash. I don't know how I would do to remo...
like this: ``` #include <stdio.h> int main(){ char st[] = "co\\din\\g"; int k = 0; for (int i = 0; st[i] != '\0'; ++i) if (st[i] != '\\') st[k++] = st[i]; st[k] = '\0'; fputs(st, stdout); return 0; } ```
I am trying to use TPT java api, for some automation of project. And trying to "Add step list" using function "generateTestCasesFromTestData" but couldn't figure out where to get its first argument "ScenarioGroup". Has some one worked on it ??
If you just want to create the test cases in your top level test case group you can get it like this: TPT 13 ``` com.piketec.tpt.api.Project prj = ... prj.getTopLevelTestlet().getToplevelScenarioGroup(); ``` There is a design error in versions prior to TPT 13. You can only get the list of scenarios and scenario...
Having opened a directory withopendir()and usingreaddir()to read out it's entries, I check whether the entry is a symbolic link and if so I'd like to use the name of the target. (Let's say we have a directoryexampledir, in it a file that's a symbolic link calledlinkfilelinking to a directory/path/to/link/target) Her...
Use thereadlink/readlinkat(2)system call.
My program creates a file using ``` HANDLE_ERROR(fd = open(path/to/file,O_WRONLY|O_CREAT,0640))) ``` Mapped it ``` uint8_t *output_file_addr = (uint8_t *)mmap ( NULL, size , PROT_WRITE, MAP_SHARED, fd, 0 ) if(output_dic_addr == MAP_FAILED){ fprintf(stderr,"%s\n",strerror(errno)); exit(EXIT_FAILURE...
The problem is solved by allocating spacefor file usingposix_fallocate(...). I thought the mmap will do the allocation as well (wrong judgment)
I'm pretty sure I have the correct return statement so i don't know why it shows this. /* check table full function */ ``` bool check_table_full (char board[][SIZE]) { int row, col; for (row = 0; row < SIZE; row++) { for (col = 0; col < SIZE; col++) { if (board[row][col] != '_') { return...
You can try this, for example: ``` bool check_table_full (char board[][SIZE]) { int row, col; for (row = 0; row < SIZE; row++) { for (col = 0; col < SIZE; col++) { if (board[row][col] != '_') { return true; } else { return false; } ...
How do I check in C if an array of uint8 contains only ASCII elements? If possible please refer me to the condition that checks if an element is ASCII or not
Your array elements are uint8, so must be in the range 0-255 For standard ASCII character set, bytes 0-127 are used, so you can use a for loop to iterate through the array, checking if each element is <= 127. If you're treating the array as a string, be aware of the 0 byte (null character), which marks the end of th...
I have a question about pointer to pointer. Here's my code ``` #include <stdio.h> void main() { int num=10; int *numPtr1; int **numPtr2; numPtr1 = &num; numPtr2 = &numPtr1; printf("%d\n", num); printf("%d\n", *numPtr1); printf("%d\n", **numPtr2); printf("%p\n", &num); printf...
numPtr1andnumPtr2are two different variables. So where those variables are located will be different, regardless of where they point to.
I am dynamically allocating a double pointer (char **pointer), some methods later the information about the length is no longer known. Is there a clean way to free both the "pointer array" and the "char array"s, without knowing the length of the pointer array?
There's technically a way. If you allocate one extra pointer, and set the last one toNULL, you can free all of the double arrays and then the double array array by freeing until you reachNULL. It's a similar principle to strings. You shouldn't probably need this, though.
This question already has answers here:How do I properly compare strings in C?(11 answers)Closed4 years ago. ``` #include<stdio.h> int main(void) { char name[40]; scanf("%s",name); if(name == "yes") { printf("%s",name); } return 0 } ```
You need to usestrcmpfor string comparison. Replace ``` if(name == "yes") ``` With ``` if(strcmp(name,"yes") == 0) ``` strcmpreturns 0 if both strings are identical (equal)Negative value if the ASCII value of first unmatched character is less than second.Positive value if the ASCII value of first unmatche...
I'm a beginner into Linking, lets say I have two .c files file1.c is ``` #include <stdio.h> #include "file2.c" int main(int argc, char *argv[]) { int a = function2(); printf("%d",a); return 0; } ``` and file2.c is ``` int function2() { return 2018; } ``` when I compiled, there is a linker err...
You should create a header file, "file2.h", with: ``` int function2(void); ``` and a file "file2.c" with the function: "file2.h" with: ``` #include "file2.h" int function2(void) { return 2018; ... } ``` Then in your main you have to include the header with: ``` #include "file2.h" ``` Keep care that al...
Let's say I have: file1.c ``` uint8_t array[] = {1, 2, 3}; ``` main.c ``` extern uint8_t array[]; ``` Does this create a copy of the variable array in main.c?
No, it tells the linker "there's a variable somewhere with this name, please fill in a reference to it whenever it's mentioned".
According to the book:How to C Programming - Eighth Edition (by Deitel brothers)this code reads the word "Hello": ``` #define SIZE 20 int main() { char MyStr[SIZE]; printf("Enter your word: "); scanf("%19s", MyStr); } ``` This picture is from theSixth Edition online: But when I do: ``` int main() { ...
There is a difference between scanf and scanf_s. The latter requires the length to be specified. So your code should be changed to: ``` int main() { char MyStr[20]; printf("Enter your word: "); scanf_s("%19s", MyStr, sizeof(MyStr)); } ``` or ``` int main() { char MyStr[20]; printf("Enter your w...
How do I check in C if an array of uint8 contains only ASCII elements? If possible please refer me to the condition that checks if an element is ASCII or not
Your array elements are uint8, so must be in the range 0-255 For standard ASCII character set, bytes 0-127 are used, so you can use a for loop to iterate through the array, checking if each element is <= 127. If you're treating the array as a string, be aware of the 0 byte (null character), which marks the end of th...
I have a question about pointer to pointer. Here's my code ``` #include <stdio.h> void main() { int num=10; int *numPtr1; int **numPtr2; numPtr1 = &num; numPtr2 = &numPtr1; printf("%d\n", num); printf("%d\n", *numPtr1); printf("%d\n", **numPtr2); printf("%p\n", &num); printf...
numPtr1andnumPtr2are two different variables. So where those variables are located will be different, regardless of where they point to.
``` int main(){ int firstNumber, secondNumber, thirdNumber; char oper; scanf("%d", &firstNumber); printf("%d\n", firstNumber); scanf("%c", &oper); printf("%c\n", oper); scanf("%d", &secondNumber); printf("%d\n", secondNumber); return 0; } ``` Why this code doesn't work as expe...
Usingscanf()is hard. Here, there is a newline character left onstdinfrom you hitting enter after the first number. So, that's the character you read. Some format conversions ignore whitespace, but%cdoes not. To make it ignore leading whitespace, you should instead use ``` scanf(" %c", &oper); ``` The space in the f...
After the following code runs, filetastyhas permission bits set to0700, which is unexpected. ``` #include <fcntl.h> #include <unistd.h> #include <stdio.h> int main() { int fild = creat("tasty", 0722); close(fild); return 0; } ``` How to allow everybody to write into the file?
Your shell probably has a umask of022, which means any new files created will have the specified bits (i.e. group write and other write) cleared. You need to set the umask to 0 before creating the file: ``` #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> int ma...
I'm trying to count the number of characters the user has as an input using a while loop, but for some reason the output counts always one more than the expected value. ( I'm a newbie so please don't hate me for it.) Here's my code: ``` #include <stdio.h> #include <string.h> int main() { int len,i; char sttr...
Thefgetsfunction reads in a line of text and stores that text,including the newlineif there's room for it. So the output is one more because of the newline.
From theuser manualof the CGALSurface_meshclass: the data structure uses integer indices as descriptors for vertices, halfedges, edges and faces I am interested in accessing a certain face/edge/vertex based on it's integer index, but cannot find how this is done. Iterators obviously work, but I don't want to itera...
The following should work:unsigned int i = 33; Surface_mesh::Face_index fi(i);
I have the following struct: ``` typedef struct School { int numOfStudents; } School; ``` For example if I have a struct: ``` School s; ``` I want to check whether the struct is null like this: ``` if(s) { printf("null"); } ``` This will not compile and error message is as follows: error: used struct ty...
In the case of: School s; sis definitely not NULL, because it is not a pointer. It is however, anuninitializedinstance of a struct, and the value ofs.numOfStudentsis undefined.
expected ‘int’ but argument is of type ‘char *’ dont know how to correct, any suggestion ``` #include <stdio.h> int my_strncmp(char const *s1, char const *s2, int n); int main (int ac, char **ag) { char result; if (ac == 4) { result = my_strncmp(ag[1], ag[2], ag[3]); printf("%d\n", result);...
You need to convertag[3](of typechar */ string) to an integer. Have a look atstrtol()and its brethren. Withatoi()exists a simpler function, which however is not as robust and versatile. That is why I would recommend getting into the habit of usingstrtol()et al., always. Sidenote, "n" parameters are usually madesize_...
Is there a better way to write the following code by eliminating the repeated condition in theifstatement in C? ``` while (n < 0) { printf("Enter a positive integer: "); scanf("%d", &n); if (n < 0) { printf("Error: please enter a positive integer\n"); } } ``` Thank you.
Simply rework your loop breaking when correct input is given. This way the check is done only one time: ``` while (1) { printf("Enter a positive integer: "); scanf("%d", &n); if (n >= 0) break; printf("Error: please enter a positive integer\n"); } ``` And, as specified in comments, an optimized ...
I'm trying to understand howpthread_createandpthread_joinworks. I thought that the third argument ofpthread_createonly allows functions with one argument of void*. I compiled the code below with gcc and it worked just fine. But why? ``` void *foo() { return 0; } int main() { pthread_t thread_id; int par ...
void foo() means that the function foo can take any number of arguments of unknown type, while void foo(void *) means that the function foo takes a argument of typevoid *That is why the program compiles, as your function can accept any type of arguments, includingvoid * The argumentvoid *is a void pointer that has...
I use libmodbus and have an array of 16 bit integers, where my modbus registers are saved. I tried with MODBUS_GET_INT64_FROM_INT16(mod_arr, 0), but the value is (of course) an integer. Usage of (double) before the MAKRO is not working. modbus_get_float_dcba(mod_arr) read only 2 registers, not 4 registers. Is there ...
Of course. :-) My solution is: temp[0] = modbus[3]; temp[1] = modbus[2]; temp[2] = modbus[1]; temp[3] = modbus[0]; memcpy(&mb_double, &temp, 8);
Below is the code. When I test it, it keeps returning 0 for some reason. ``` float compute_personal_allowance ( float annualSalary ) { int pa = 0; if (annualSalary <= 100000) pa == 11850; else if (annualSalary > 100000) pa == 11850 - 1 * ((annualSalary - 100000)/2); return pa; } ``` ...
Your problem lies here: ``` pa == 11850 - 1 * ((annualSalary - 100000)/2); ``` ==doesn't do assignment, it does comparison. So this doesn't actually do anything in this case. It evaluates to1or0and then just discards that result. What you need instead is ``` pa = 11850 - 1 * ((annualSalary - 100000)/2); ```
``` #include <stdio.h> int main(void) { int marks[10]; int i; for (i=0; i < 10; i++) { scanf("%d ", &marks[i]); } printf("\n"); for (i=0; i <= 9; i++) { printf("%d\n", marks[i]); } return 0; } ``` Clearly, the first loop condition should run only 10 times ...
In This case space after %d is format specifier so it's take 2 argument with space as separator. ``` scanf("%d %d", &marks[i], &marks[i+1]); => 1 2 scanf("%d ", &marks[i]); => 1 2 scanf("%d", &marks[i]); => 1 ```
I have two functions for getting the user to make a move and the computer to generate moves, so when creating a function for updating the computer and user's moves, the 'x' and 'o' for the moves and '_' for a blank space, would I use pointers for my multidimensional array and if so how would you code that? An example ...
Updating a two-dimensional char array with a function, passing thepointerto the array as a parameter: ``` int main(){ char array[5][5]; updateArray(array, 0, 0, 'a'); } void updateArray(char * arr, int row, int col, char c){ arr[row][col] = c; } ``` Note that when declaring an array in C, the array iden...
i have an input with newlines and i need to read it to buffer. Format is restricted to the structure. Input looks like this: ``` { [ 5.5 ; 1 ] , [ 1; 2 ] ,[3; 4]} ``` And the code I have is like this: ``` char *s2 = NULL; size_t n = 0; int slozZav = 0; int hranZav = 0; getline(&s2, &n, stdin); if(sscanf(s...
getlinereads until it encounters a new line; hence, it will stop when you press enter the first time. To read in the complete structure to be scanned, try: ``` getdelim(&s2, &n, '}', stdin); ``` This way, new lines will be read in as well, and reading will stop after having read the delimiter}.
Right now I am reading Head First C and I have a hard time understanding this piece of code, image taken from the O'Reilly website: could you please explain why only single value check is needed in the comparisonval == 10? The code works but I just do not understand the reason why exactly.
Because in the previous if-else tree,valwould be set to 10 for each card J, Q or K and also for the card with the value 10. So whenever you had a J, Q, K or 10valwould be 10 and so you can just check for this value when checking for these cards.
Why does the following code produce an error? I don't understand why the curly braces are making a difference. ``` #include<stdio.h> int main(void) { { int a=3; } { printf("%d", a); } return 0; } ```
The scope of a local variable is limited to the block between {}. In other words: outside the block containingint a=3;ais not visible. ``` #include<stdio.h> int main() { { int a=3; // a is visible here printf("1: %d", a); } // here a is not visible printf("2: %d", a); { ...
Is it possible to have a POSIX thread remain "alive" after executing the function given as an argument? As in reusing that thread for further work. For example, given a queue of functions to execute, is it possible to have a pthread execute several of them? The alternative would be creating a pthread for every task.
No. What you describe reminds me of athread pool, where a set of threads is waiting for work (your functions in this case) to execute.
I am having a very hard time figuring out how I can use: ``` EEDATA = 0xFF, 0x00, 0xFF, 0x00, 0x01, 0x03 ; ``` and turn that into C code. From what I can understand, it's a way of allocating memory in BASIC, but I really do not know. If anyone out there could help I would much appreciate it. It was programmed using...
I am not really sure what you want to do. But I guess you want to preload your EEPROM with the XC8 compiler. Use the following code: ``` __EEPROM_DATA(0xFF, 0x00, 0xFF, 0x00, 0x01, 0x03, 0x00, 0x00); ``` Be sure to always use a block by 8 values. To write and read the EEPROM you can easily use the library functions...
I tried to print a formattedintarray ``` #include <stdio.h> #define SIZE 3 int arr[SIZE] = {1, 2, 3}; int main(void) { printf("{"); for (int i =0; i < SIZE; i++ ) { printf("%d, ", arr[i]); } printf("}"); printf("\n"); } ``` but found it very hard ``` $ ./a.out {1, 2, 3, } ```...
Given that zero length arrays are not permitted in C (soarr[0]always exists), and you already have explicit code for the opening brace, this solution seems reasonable to me: ``` int main(void) { printf("{%d", arr[0]); for (size_t/*better type for array index*/ i = 1; i < SIZE; ++i) { printf(...
I am creating a program that implements a tic-tac-toe game using a 2-D array with multiple functions. How would I create a function where it clears all 'x' and 'o' characters in each cell and have the cells reset it back to the underscore character '_'? An example along with your explanation would be much appreciated!...
You can usememsetto reset the array to_as below. ``` char array[10][10]; memset(array, '_', sizeof(array)); ```
Normally I would use something like this: ``` double value; if (scanf("%lf", &value) == 1) printf("It's float: %f\n", value); else printf("It's NOT float ... \n"); ``` But this time I need to read two numbers at once ``` scanf("%lf %lf", &x, &y); ``` How do I check that?
As @SRhm mentioned in the comment section, you simply can use: ``` scanf("%lf %lf", &x, &y) == 2 ``` to get two numbers from the user input. A quote fromscanf - C++ Referenceexplain the return value of the function: On success, the function returns the number of items of the argument list successfully filled. sc...
``` #include<stdio.h> #include<string.h> int main() { char test[100] = "おおお\n"; int len = strlen(test); for (int i = 0; i < len; i++) { printf("%c", test[i]); } return 0; } ``` the code doesn't display the kana「おおお」on my computer, but the same code on my friend computer display the kana. ...
It depends on the "encoding" your editor (or browser, or whatever you are using) is set to. Check that it is the same on the two computers (it may be UTF-8, UTF-16, JIS, ...) and remember that from a C point of view the result ofstrlen("お")is NOT 1.
Normally I would use something like this: ``` double value; if (scanf("%lf", &value) == 1) printf("It's float: %f\n", value); else printf("It's NOT float ... \n"); ``` But this time I need to read two numbers at once ``` scanf("%lf %lf", &x, &y); ``` How do I check that?
As @SRhm mentioned in the comment section, you simply can use: ``` scanf("%lf %lf", &x, &y) == 2 ``` to get two numbers from the user input. A quote fromscanf - C++ Referenceexplain the return value of the function: On success, the function returns the number of items of the argument list successfully filled. sc...
``` #include<stdio.h> #include<string.h> int main() { char test[100] = "おおお\n"; int len = strlen(test); for (int i = 0; i < len; i++) { printf("%c", test[i]); } return 0; } ``` the code doesn't display the kana「おおお」on my computer, but the same code on my friend computer display the kana. ...
It depends on the "encoding" your editor (or browser, or whatever you are using) is set to. Check that it is the same on the two computers (it may be UTF-8, UTF-16, JIS, ...) and remember that from a C point of view the result ofstrlen("お")is NOT 1.
This question already has answers here:Shortcircuiting of AND in case of increment / decrement operator(6 answers)Short circuit evaluation with both && || operator(2 answers)Is short-circuiting logical operators mandated? And evaluation order?(7 answers)Closed4 years ago. Why post-decrements operator in the following...
In the expression(a==8) || (a--);since(a==8)is already true hence rest of the OR condition is not evaluated.
I try to call getenv in my C code, this can return correct env string in terminal, while it returns NULL in GDB/DDD. ``` void main() { char * a = getenv("ANCHOR_STEM"); if (strlen(a)>0) printf("%s\n", a); } ``` The GDB/DDD is started from the same terminal. Even I "show environment", this env exists. Anyone...
Even I "show environment", this env exists. When GDB invokes your program, it starts a newshellto run this program in. When the environment changes for the target program, most often this is the result of your shell initialization file (~/.bashrc,~/.kshrc, etc.) changing the environment. It is a really bad idea to ...
I am new to c and I am getting the segmentation dump error after first printf statement. Please help me out with this error. ``` void main() { char string[10]={}; char key,used[10]; int len=0; printf("Enter the string :"); scanf("%s",&string); len = strlen(string); for (int i =0; i<len;++i) { int...
As mentioned in the comment scanf("%s",&string);should bescanf("%s",string); Usecorrect format specifier printf("%s",key);should beprintf("%c",key);//<-----should be %cprintf("%s %d",key,count);should beprintf("%c %d",key,count);//<-----should be %c
This question already has answers here:Shortcircuiting of AND in case of increment / decrement operator(6 answers)Short circuit evaluation with both && || operator(2 answers)Is short-circuiting logical operators mandated? And evaluation order?(7 answers)Closed4 years ago. Why post-decrements operator in the following...
In the expression(a==8) || (a--);since(a==8)is already true hence rest of the OR condition is not evaluated.
I try to call getenv in my C code, this can return correct env string in terminal, while it returns NULL in GDB/DDD. ``` void main() { char * a = getenv("ANCHOR_STEM"); if (strlen(a)>0) printf("%s\n", a); } ``` The GDB/DDD is started from the same terminal. Even I "show environment", this env exists. Anyone...
Even I "show environment", this env exists. When GDB invokes your program, it starts a newshellto run this program in. When the environment changes for the target program, most often this is the result of your shell initialization file (~/.bashrc,~/.kshrc, etc.) changing the environment. It is a really bad idea to ...
I am new to c and I am getting the segmentation dump error after first printf statement. Please help me out with this error. ``` void main() { char string[10]={}; char key,used[10]; int len=0; printf("Enter the string :"); scanf("%s",&string); len = strlen(string); for (int i =0; i<len;++i) { int...
As mentioned in the comment scanf("%s",&string);should bescanf("%s",string); Usecorrect format specifier printf("%s",key);should beprintf("%c",key);//<-----should be %cprintf("%s %d",key,count);should beprintf("%c %d",key,count);//<-----should be %c
I try to call getenv in my C code, this can return correct env string in terminal, while it returns NULL in GDB/DDD. ``` void main() { char * a = getenv("ANCHOR_STEM"); if (strlen(a)>0) printf("%s\n", a); } ``` The GDB/DDD is started from the same terminal. Even I "show environment", this env exists. Anyone...
Even I "show environment", this env exists. When GDB invokes your program, it starts a newshellto run this program in. When the environment changes for the target program, most often this is the result of your shell initialization file (~/.bashrc,~/.kshrc, etc.) changing the environment. It is a really bad idea to ...
I am new to c and I am getting the segmentation dump error after first printf statement. Please help me out with this error. ``` void main() { char string[10]={}; char key,used[10]; int len=0; printf("Enter the string :"); scanf("%s",&string); len = strlen(string); for (int i =0; i<len;++i) { int...
As mentioned in the comment scanf("%s",&string);should bescanf("%s",string); Usecorrect format specifier printf("%s",key);should beprintf("%c",key);//<-----should be %cprintf("%s %d",key,count);should beprintf("%c %d",key,count);//<-----should be %c
I am looking for a functionFILE * join (FILE * a, FILE * b)that is equivalent topopen("cat a b", "r");. That is, callingjoinshould produce a new file pointer that contains all of filea, then all of fileb. Preferablyjoinshould be lazy such that filebis not read until all of fileahas been consumed.
You cannot create a portable function for this. It is possible to do withfopencookiewith Linux/Glibc orfunopenon BSD. See:Is it possible to use functions that acts on FILE* on custom structures?I am unaware of any method for this on Windows though. You'd just need to provide a method for reading that would just try t...
Is there any way to let CLion update the declaration in the .h file if I change the function definition in the .c file ? The copy and pasting is such a repetitive task..
It depends on changes I guess. I always useRefactor->Change Signatureto update function return type, name, arguments in both files (source and header).
I have a small c program which uses the raw mode of the terminal. When I exit the program (and the raw mode), the terminal is cleared. Other programs like vim can handle that situation and restore the terminal output. Is there a secret escape sequence or something to restore the terminal as it was before executing my...
There's no need to do the restoration manually. Many applications likevimorlessare using the concept calledalternate screen, so check that. It exists exactly for such a purpose. Simply switch to the alternate screen when your program starts and switch back right before it exits. You can use for example the following ...
``` #include <stdio.h> int main(int argc, char **argv) { float A,B,C; printf("pls write a 3 numbers\n"); scanf("%f%f%f",&A,&B,&C); if (%f<(%f||%f),A,B,C) {printf("NO A");} else if(%f<(%f||%f),B,C,A) {printf("NO C");} else if (%f<(%f||%f),C,B,A) { printf("NO B");} r...
``` if (%f<(%f||%f),A,B,C) ``` This is not the correct syntax to compare numbers. In fact you can only compare 2 numbers with a single operator. To compare 3 numbers you need ``` if (A>B) { if (A>C) { printf("no A"); } else { printf("no C"); } } else { if (B>C) { ...
So this is my code for appending string2 to string 1. Code works fine when I have added the line:s1[null_index]='\0';but when i omit it adds the word 'road' one more time to the output...why is that? Why do I have to specify that the final value of null_index variabe is'\0'....shouldnt the computer already know this s...
s1is allocated only as much memory asSuccess isrequires and when you try to dos1[null_index]=s2[i];you are inducing an undefined behavior.
Before updating to Mojave I was compiling C programs just fine. I used an older version of gcc, 7.3, that I installed using the instructions foundhere. Then I updated to Mojave and tried compiling the simple program that follows with gcc main.c: ``` #include <stdio.h> int main(){ printf("Hello World\n"); ret...
I figured out how to fix it. I went to ``` /Library/Developer/CommandLineTools/Packages/ ``` then opened and installed macOS_SDK_headers_for_macOS_10.14.pkg.
I have no idea how to pass command like: ``` echo -e \"\E[1;3mHello!" ``` tosystem(), since I have to put it in quotation marks cause it'sconst char, any help?
Double quotes need to be escaped in strings, as do backslashes: ``` system("bash -c 'echo -e \"\\E[1;3mHello!\"'"); ```
Is it dangerous/risky to use#pragma pack(1)on structs that contain byte-arrays only? E.g. this one: ``` #pragma pack(1) struct RpcMessage { uint8_t proto_info[16]; uint8_t message_uuid[16]; uint8_t arg0[16]; uint8_t arg1[16]; uint8_t arg2[16]; uint8_t arg3[16]; uint8_t arg4[16]; uint8...
If the structure only containsuint8_t, then#pragma pack(1)will have no effect at all. It simply won’t do anything, because the structure is already packed as tightly as it can be. Padding will only appear if you have elements which have larger than byte alignment.
During startup my application does some expensive time consuming initialization and then it establishes ssl connections to multiple domains (multiple connections to some of these domains). From looking at wireshak traces it takes at best 150-200ms for the ssl connection to be established. Can I somehow tell curl to e...
Since established connections will be kept in curl'sconnection cachefor a while after transfers, I would suggest you simply do a simpleHEADrequest (usingCURLOPT_NOBODY) or anOPTIONSone, then while starting up the rest of the things so then the "real" request and reuse that connection.
When developing a statically-linked library, how do I secure code accessing shared data against data-races using OpenMP? If I simply use#pragma omp criticalon sections I need to run sequentially, am I going to be fine if the library's client uses a different implementation of threads, such as pthreads? Is a critical ...
Looking at thelatest OpenMP specification, it states thatcriticalensures that only one thread from a "contention group" executes the block at a time. The way I read it, the definition of the contention group only covers OpenMP threads. So, technically, an OpenMP implementation could be written in a way thatcriticaldoe...
I am currently reading an online version of Stephen Kochan's "Programming in C (3rd Edition)." One of the activities involves evaluating an equation, Write a program that evaluates the following expression and displays the results (remember to use exponential format to display the result): (3.31 x 10-8x 2.01 x 10...
You must#include <math.h> Also, change to this: ``` printf ("%e\n", result); ``` You should probably also have ``` double result; ``` becausepow()returns adouble.
I want to create text files sequence like... student1.txtstudent2.txtstudent3.txt... How to do it? I have a sample code, but its not working for my problem. ``` #include<stdio.h> void main() { FILE *fp; int index; for(index=1; index<4; index++) { fp=fopen("student[index].txt","w"); ...
You are using a a fixed string "student[index].txt" rather than making a string with the number you want in it. ``` void main() { FILE *fp; int index; char fname[100]; for(index=1; index<4; index++) { sprintf(fname, "student%d.txt", index); fp=fopen(fname,"w"); fclose(fp); } } ```
This question already has answers here:When C says start up values of global variables are zero, does it mean also struct members? And what is the initial value of a pointer?(2 answers)Closed4 years ago. Can I trust of this one: Section 6.7.8p10 Initialization of C standard And will it always be set to 0? Are there...
Yes, if the compiler is a C compiler, all static variables that are not initialized otherwise will be initialized as if by{ 0 }. This means that floats and pointers will be as if initialized by{ 0 }even if the bit-pattern were different. If the compiler has an option for it to become a not-C compiler then all bets ar...
I am looking at some socket code. It declares "wb" as length: ``` ssize_t wb; wb = sendto(sock, buf, len, 0, (struct sockaddr *) &addr, sizeof(addr)); ``` Does anyone know what "wb" is short for? I thought the variable name should be self-explanatory.
My guess would be "written bytes". As for variable names being self-explanatory, that's true, but it's in the context of the code. If you're not using the variable a until hundred lines later, it should probably not require much context. If you're using it again within a line or two and nobody is going to get confu...
Does thegcc 166 compilerfor theSiemens C167micro controller exist in open source ?, or can I find it?
According to the sitelinkI found thatGCC 166it is a compiler available for sale byRigel corp
I want to store a hex value with leading zeros into a char pointer. What I did before, to test my program, was this: ``` printf("%06x : ", offset); ``` So when I had an offset of e.g. 16, the output was 000010. 32 was 000020. My goal is to store that value into a variable or assign it to a pointer. In the end, I wa...
Usesprintf(): ``` char buffer[7]; sprintf(buffer, "%06x : ", offset); ```
Does thegcc 166 compilerfor theSiemens C167micro controller exist in open source ?, or can I find it?
According to the sitelinkI found thatGCC 166it is a compiler available for sale byRigel corp
I want to store a hex value with leading zeros into a char pointer. What I did before, to test my program, was this: ``` printf("%06x : ", offset); ``` So when I had an offset of e.g. 16, the output was 000010. 32 was 000020. My goal is to store that value into a variable or assign it to a pointer. In the end, I wa...
Usesprintf(): ``` char buffer[7]; sprintf(buffer, "%06x : ", offset); ```
This question already has answers here:struct declaration(2 answers)Closed4 years ago. I read such a snippet code of in5.2.  The indirection: ``` struct contact { int n1; float n2; char st[10]; } d1; ``` What's the meaning of using d1 here? is it a recommended practice to define such a struct?
That simply declare astruct contactvariable namedd1. That is not really readable and is not used generally.
I was given the task of writing a program that determines the maximum number of processes a user can have, just like the bash's "ulimit -u" built-in command butusing system calls and C. Any hint as to how achieve this?
Theulimitbuiltin is just an interface to thegetrlimitandsetrlimitfunctions. See thegetrlimit, setrlimit man page. In particular, you are interested in theRLIMIT_NPROCresource.
C language - I don't understand why this works: ``` #define x 5 int vett[x]; main () {} ``` this works: ``` int vett[5]; main () {} ``` this works: ``` main () { int x=5; int vett[x]; } ``` this works: ``` int x=5; main () { int vett[x]; } ``` this does NOT work: ``` int x=5; int vett[x]; main () {}...
In all other examples the size of the array is initialized with a constant (5) when outside main. In the last example the initialization of the array is outside of main so it is not running code, the compiler does not know what the value of x is.
``` main() { int x, y, userInput; do { { printf("Input a number: \n"); scanf("%i", &userInput); } } while (userInput < 1 || userInput > 50); ``` The while end condition works with||, I want to understand why it doesn't work with&&.||allows me to set-up the range between the 0 - 5...
You want to loop while the input is below one or the input is greater than 50. If you use and, the condition will never be true, as the input cannot be lower than 1 and greater than 50.
I am trying to declare this array of strings(or a 2d character array,i reckon) in c language but the compiler ide is giving me error: "[Error] array type has incomplete element type" ``` char division[][]={"Northeast Division","Northwest Division","Southeast Division","Southwest Division"}; ``` what am I doing wrong...
You have to specify the maximum length of a string. This should solve your problem ``` char division[][25]={"Northeast Division","Northwest Division","Southeast Division","Southwest Division"}; ```
This question already has answers here:Why do these pointers cause a crash?(5 answers)Closed4 years ago. ``` int main() { struct stuff { int num; }*foo; // If I comment the line below, I get core dump error. // Why? foo = (struct stuff *)malloc(sizeof(struct stuff)); (*foo).num = ...
You are only allowed to dereference avalidpointer. In your case,foobeing an automatic local variable, unless initialized explicitly, contains some indeterminate value, i.e, it points to an arbitrary memory location, which is pretty much invalid from the point of your program. In case, you do not assign a valid poin...
I have a confusion in basic concept for C language for loop increment. This is my code: ``` #include <stdio.h> #include <stdlib.h> int main() { int j=0;int a; for(j;j<=3;++j) { printf("hello\n"); a=j; } printf("%d,%d\n",j,a); } ``` My question is: Why is the output of a not equal...
Forj=0a=0 Forj=1a=1 Forj=2a=2 Forj=3a=3 Forj=4loop get terminated asj<=3become false, so j value is 4 and a value is 3.
I'm trying to pass a function of type: int *(*)(int *, int *) to a function accepting as argument a: void *(*)(void *, void *) is there any way to do that ?
You can always cast stuff explicitly in C -- so you can cast(void *(*)(void *, void *))functo pass the function pointer. The problem is that if the callee then tries to call through the function pointer without first casting it back toint *(*)(int *, int *), the result is undefined behavior. Now it may be the case t...
Well, my question is to ask how can i add the lwip library to the tool Xilinx SDK to use it in Embedded linux environment. I tried a lot but always debug problems are there. I added this library for example lwip-2.0.2 from the linkhttp://download.savannah.nongnu.org/releases/lwip/ currently i have a Zybo board based ...
LWIP is generally used for bare metal firmwarerefer this link When Zynq is running petalinux, you can directly use Linux POSIX TCP/IP stack.E.g TCP Server/Client Linux code You can selectLinux OSinOS Platformand develop Linux application in Xilinx SDK.Linux application using SDK
I see that theapr_pool_*interface exposes void apr_pool_tag (apr_pool_t *pool, const char *tag) which lets me tag a pool. That's all well and good, but how do I extract the tag from a pool at a later time? I can't find the "getter" for the above setter. How are these tags used?
Trunk (aka 2.0) has anapr_pool_get_tag(), but in released branches pool tagging is meant as a debugging aid. In other words, post-mortem analysis with a debugger.
I'm trying to pass a function of type: int *(*)(int *, int *) to a function accepting as argument a: void *(*)(void *, void *) is there any way to do that ?
You can always cast stuff explicitly in C -- so you can cast(void *(*)(void *, void *))functo pass the function pointer. The problem is that if the callee then tries to call through the function pointer without first casting it back toint *(*)(int *, int *), the result is undefined behavior. Now it may be the case t...
Well, my question is to ask how can i add the lwip library to the tool Xilinx SDK to use it in Embedded linux environment. I tried a lot but always debug problems are there. I added this library for example lwip-2.0.2 from the linkhttp://download.savannah.nongnu.org/releases/lwip/ currently i have a Zybo board based ...
LWIP is generally used for bare metal firmwarerefer this link When Zynq is running petalinux, you can directly use Linux POSIX TCP/IP stack.E.g TCP Server/Client Linux code You can selectLinux OSinOS Platformand develop Linux application in Xilinx SDK.Linux application using SDK
I see that theapr_pool_*interface exposes void apr_pool_tag (apr_pool_t *pool, const char *tag) which lets me tag a pool. That's all well and good, but how do I extract the tag from a pool at a later time? I can't find the "getter" for the above setter. How are these tags used?
Trunk (aka 2.0) has anapr_pool_get_tag(), but in released branches pool tagging is meant as a debugging aid. In other words, post-mortem analysis with a debugger.
Well, my question is to ask how can i add the lwip library to the tool Xilinx SDK to use it in Embedded linux environment. I tried a lot but always debug problems are there. I added this library for example lwip-2.0.2 from the linkhttp://download.savannah.nongnu.org/releases/lwip/ currently i have a Zybo board based ...
LWIP is generally used for bare metal firmwarerefer this link When Zynq is running petalinux, you can directly use Linux POSIX TCP/IP stack.E.g TCP Server/Client Linux code You can selectLinux OSinOS Platformand develop Linux application in Xilinx SDK.Linux application using SDK
I see that theapr_pool_*interface exposes void apr_pool_tag (apr_pool_t *pool, const char *tag) which lets me tag a pool. That's all well and good, but how do I extract the tag from a pool at a later time? I can't find the "getter" for the above setter. How are these tags used?
Trunk (aka 2.0) has anapr_pool_get_tag(), but in released branches pool tagging is meant as a debugging aid. In other words, post-mortem analysis with a debugger.
Currently I am trying to create .skp files from some external geometry data. I have managed to create all required geometries, but after i save model by using following code: ``` if (SUModelSaveToFileWithVersion(model, model_path, SUModelVersion::SUModelVersion_SU2018) != SU_ERROR_NONE){ return 0; } ...
This would be a bug in the API when saving. I'm afraid there is not workaround for that via the C API. (Btw, you can report issues in the SketchUp API issue tracker:https://github.com/SketchUp/api-issue-tracker/issues)
I have a UnsafeMutablePointer pointing at a C string, I want to convert the bytes at this pointer to a Swift String, the data is a C string, so UTF8. Is it possible to iterate byte by byte until NULL? Or some easier way?
CChar is an alias for Int8, so you can useCChar-based methodshere. ``` let str = String(cString: pointer) ```
I am tasked with finding maximum two's complement integer, or the TMax. I am at a complete loss for how to do this. I know that the correct value is 0x7fffffff, or 2147483647, but I do not know how exactly to get to this result. That's the maximum number for a 32 bit integer. I cannot use functions or conditionals, an...
Assuming you know that your machine uses two's complement representation, this is how you would do so in a standard compliant manner: ``` unsigned int x = ~0u; x >>= 1; printf("max int = %d\n", (int)x); ``` By using anunsigned int, you prevent any implementation defined behavior caused by right shifting a negative v...
I'm trying to understandstructin C. I couldn't get the idea about this definition below. Why do we leaveaCard,deck[ ]and*cardPtrout? What is the difference between including them in and leaving them out? ``` struct card { char *face; char *suit; } aCard, deck[52], *cardPtr; ```
You are mixing things up. Astruct cardhas the membersfaceandsuit. But there are three variables using thestruct cardtype, namelyaCard, deck, cardPtr. Alternatively one could have written: ``` typedef struct { char *face; char *suit; } Card; Card aCard, deck[52], *cardPtr; // or even Card aCard; Card deck[52...
I'm trying to understandstructin C. I couldn't get the idea about this definition below. Why do we leaveaCard,deck[ ]and*cardPtrout? What is the difference between including them in and leaving them out? ``` struct card { char *face; char *suit; } aCard, deck[52], *cardPtr; ```
You are mixing things up. Astruct cardhas the membersfaceandsuit. But there are three variables using thestruct cardtype, namelyaCard, deck, cardPtr. Alternatively one could have written: ``` typedef struct { char *face; char *suit; } Card; Card aCard, deck[52], *cardPtr; // or even Card aCard; Card deck[52...
Let's say I have two variables. ``` int a = -10; int b = 10; ``` How can I return 0 if they have different sign or 1 if they have same signs ? Again without if statements
Like this? ``` return ((a >= 0 && b >= 0) || (a < 0 && b < 0)); ```
I am working with 1D and 2D arrays but my scanf is not iterating for my loop for my 1D array. Here is my current code: ``` #include <stdio.h> int main(void) { int row, col, N, M; printf("This program counts occurrences of digits 0 through 9 in an NxM array.\n"); printf("Enter the size of the array (Row Column): ...
you are missing an ampersand in this line : scanf("%d", digits[row][0]); corrected code : scanf("%d", &digits[row][0]);
For example: ``` void *p1 = someStringPointer; void *p2 = p1; ``` Although these are two unique pointers, given that they both point to the same value, are they still different memory objects?
If you print the address ofp1andp2 ``` printf("%p\n", (void *) &p1); printf("%p\n", (void *) &p2); ``` They have different addresses, so yes they are different memory objects.
How can I create an array such that I could access the elementsa[1000000],a[1]anda[2]and not even using the size of 1000000? If possible please provide the answer inC++.
Usestd::unordered_map<>. ``` enum { N = 9 }; int arr[N] = { 0 }; std::unordered_map<int, int> m; for (int i = 0; i < N; i++) { ++m[arr[i]]; } ```
I have the following array: ``` #include <stdio.h> #include <stdlib.h> #include <stdbool.h> int main () { int openedLockers[5] = {0,1,2,3,4}; return 0; } ``` And would like to output "Opened Lockers: 0,1,2,3,4." It specifically has to end with a period after the last number. I'm not sure how to do this in a for...
``` #include <stdio.h> int main () { int openedLockers[] = {0,1,2,3,4}; printf("Opened Lockers: "); for (size_t i = 0; i < 5; i++) { printf("%d", openedLockers[i]); if (i != 4) printf(","); else printf("."); } return 0; } // Output : Opened Lockers: 0,1,2,3,4. ```
Example input: 12345 As you can see I can store each digit "1" "2" "3" "4" "5" through scanf but how do I store the whole number "12345"? Can it happen within the same scanf line? ``` #include <stdio.h> #include <math.h> int main(){ int wholeNumber = 0; int i1,i2,i3,i4,i5 = 0; printf("\nPlease enter ...
I will try to answer your first question. You can simply multiply the entered numbers by multiples of 10. Lets show it with calculation: 5*1 + 4*10 + 3*100 + 2*1000 + 1*10000 = 12345 So, here is the code for a manual use: ``` ... scanf("%1d%1d%1d%1d%1d",&i,&i2,&i3,&i4,&i5); i*=10000; i2*=1000; i3*=100; i4*=10; i5*=...
fclose()flushes buffered output data. Doesclose()also flush buffered output data?
There are no buffers in a C program associated with an open file descriptor, and so no buffered data to speak about. Your OS may or may not have some buffers associated with an open file descriptor (or with a device on which the corresponding file resides), depending on the nature of the file. These are normally invi...
Can anyone explain the difference in why allocating memory to the structures are different here? Thanks. ``` typedef struct Node{ int data; struct Node *next; }Node; Node *newNodePtr = (Node*)malloc(sizeof(Node)); ``` vs ``` struct Person { char *name; int age; int height; int weight; }; struct Person *who = mal...
struct Node is typedefd to Node so the sizeof(Node) is legal, because there is no typedef for Person you cold not do sizeof(Person). The cast to (Node*) on the malloc is unnecessary, C allows cast from void * to other object type pointers without a cast (and plenty of people recommend against it).
I've got a problem. I am trying to free an array of pointers using a loop, but it does not work. Could somebody help me with that? This is the allocation code: ``` void create1(A*** a, int size) { *a = (A**) malloc(size* sizeof(A*)); for (int i = 0; i < size; i++) { a[0][i] = (A*)malloc(size * si...
You have to do the reverse of what you have done when you have allocated the memory. Free the element pointers in a loop and finally free the pointer to the array: ``` void del(A** a, int size) { for (int i = 0; i < size; i++) { free(a[i]); } free(a); } ```
In this code the person has to enter y if wishes to continue, but why does it ask him the question two times when he enters y. ``` char c = 'y'; while(c!='n'){ printf("Do you wish to continue: (y or n):"); c = getchar(); } ``` Here is the console
why does it ask him the question two times when he enters y The enter key the user hits is taken as another character (a new-line:\n) as well.
I tried to read 2 variables from the keyboard and to write them on the screen and I have a problem, the program display me only one.. ``` #include <stdio.h> #include <stdlib.h> int main() { short int n,x; scanf("%d",&n); scanf("%d",&x); printf("%d %d",n,x); return 0; } ``` I introduced 14 and 15...
Use %hd format specifier for short int Use %hu format specifier for unsigned int Use %d format specifier for int Use %ld format specifier for long int ``` #include <stdio.h> #include <stdlib.h> int main() { short int n, x; scanf("%hd", &n); // Notice %hd instead of %d for short int scanf("%hd", &x); // Notice ...
I am having a question for myself while taking operating system course. If I type in any C code to my text editor or though IDE and execute it with the compiler it translates the code into machine code. Then I would guess if I run the program, the OS will allocate a memory address to the code which is done by kernel...
In the ordinary course of events, any code you write is 'user mode code'. Kernel mode code is executed only when you execute a system call and the control jumps from your user code to the operating system. Obviously, if you're writing kernel code, or loadable kernel modules, then things are different — that code wil...
In C, I can bind a client socket to a specific local address and a system-selected port. What would happen if any of the following happened? The local address of the machine is changedThe program is moved to a host with a different local address And what would happen if I attempt to bind after calling connect()?
Well, in general, a TCP socket connection is really identified by the source IP, source port, destination ip, destination port tuple. If say the source IP is not valid any more then neither end can recover from it and the destination host will not probably notice until after a timeout. If on the other hand you're try...
In this code the person has to enter y if wishes to continue, but why does it ask him the question two times when he enters y. ``` char c = 'y'; while(c!='n'){ printf("Do you wish to continue: (y or n):"); c = getchar(); } ``` Here is the console
why does it ask him the question two times when he enters y The enter key the user hits is taken as another character (a new-line:\n) as well.