question
stringlengths
25
894
answer
stringlengths
4
863
This is the solution ofProgramming Pearlsin column 1.6_1: ``` > #include <stdio.h> int intcomp(int *x, int *y) { return *x-*y; } int a[1000000]; int main(void) { // insert code here... int i,n=0; while (scanf("%d",&a[n])!=EOF) { n++; } qsort(a,n,sizeof(a[0]),intcomp); for(i=0;i<n;i++) { printf("%d\n",a[i]); } return 0; } ``` Error message: conflicting types for "qsort" Can you tell me why could that happen? Isn't it defined by default? My compiler isXcode(MacOS).
Comment (which turned out to be a correct guess) promoted to answer: It's unclear if the source code above was from typed in from the book, or found online. The code above has a few differences fromthis github copy of p1c1quicksort, i.e. the code above is missing: ``` #include <stdlib.h>. ```
I know that Guile has ascm_assert_smob_typefunction, but I do not believe that it returns a boolean. I want to be able to do something like: ``` if (type(smob) == int_smob) { int_foo(smob); } else if (type(smob) == string_smob) { string_foo(smob); } ```
You can checkscm_assert_smob_type'sdefinitionfor hints: ``` void scm_assert_smob_type (scm_t_bits tag, SCM val) { if (!SCM_SMOB_PREDICATE (tag, val)) scm_wrong_type_arg_msg (NULL, 0, val, scm_smobs[SCM_TC2SMOBNUM(tag)].name); } ``` As you can see, it utilizesSCM_SMOB_PREDICATEwhich does return a boolean. The macro is for public use and is defined in<smob.h>.
Novice in c programming. Could someone help me understand what the while loop is doing in this code snippet? I've never seen a while loop of this type. However, I do understand that it is performing pointer arithmetic, but what is it actually saying broken down in terms of pseudocode or plain English? :) ``` char* cpy (char* s) { char *dest, *d; d = dest = malloc(strlen(s) * sizeof(char) + 1); if (d) while ((*d++ = *s++)); return dest; } ```
In C a value of 0 means false and any other means true. Strings end in a null character with a value of 0. This while loop copies all the characters from s to d until the null (end of string) is reached. The assignment*d++ = *s++returns the same value as*s++is assigned to*d After the loop bothsanddwill be pointing after the null character. Note that the null is also copied.
I'm trying to dynamically link a Rust .so library with a C program in Linux with gcc. Using onlydlopenanddlcloseresults in no errors, but I get a segmentation fault with the following code: ``` char * (*my_function)(char *); char *my_input_string = "foo"; //...abbreviated code... my_function = dlsym(handle, "my_function"); char *my_output_string = (*my_function)(my_input_string); ``` I'm usinggcc -g foo.c -ldl -o footo compile, if that matters. I know that it's finding the symbol because I used#[no_mangle]in the rust library and themy_functionpointer is not null
I ran it throughgdband it turns out the library was trying to call a function in the calling program that didn't exist.
This is the solution ofProgramming Pearlsin column 1.6_1: ``` > #include <stdio.h> int intcomp(int *x, int *y) { return *x-*y; } int a[1000000]; int main(void) { // insert code here... int i,n=0; while (scanf("%d",&a[n])!=EOF) { n++; } qsort(a,n,sizeof(a[0]),intcomp); for(i=0;i<n;i++) { printf("%d\n",a[i]); } return 0; } ``` Error message: conflicting types for "qsort" Can you tell me why could that happen? Isn't it defined by default? My compiler isXcode(MacOS).
Comment (which turned out to be a correct guess) promoted to answer: It's unclear if the source code above was from typed in from the book, or found online. The code above has a few differences fromthis github copy of p1c1quicksort, i.e. the code above is missing: ``` #include <stdlib.h>. ```
I know that Guile has ascm_assert_smob_typefunction, but I do not believe that it returns a boolean. I want to be able to do something like: ``` if (type(smob) == int_smob) { int_foo(smob); } else if (type(smob) == string_smob) { string_foo(smob); } ```
You can checkscm_assert_smob_type'sdefinitionfor hints: ``` void scm_assert_smob_type (scm_t_bits tag, SCM val) { if (!SCM_SMOB_PREDICATE (tag, val)) scm_wrong_type_arg_msg (NULL, 0, val, scm_smobs[SCM_TC2SMOBNUM(tag)].name); } ``` As you can see, it utilizesSCM_SMOB_PREDICATEwhich does return a boolean. The macro is for public use and is defined in<smob.h>.
Novice in c programming. Could someone help me understand what the while loop is doing in this code snippet? I've never seen a while loop of this type. However, I do understand that it is performing pointer arithmetic, but what is it actually saying broken down in terms of pseudocode or plain English? :) ``` char* cpy (char* s) { char *dest, *d; d = dest = malloc(strlen(s) * sizeof(char) + 1); if (d) while ((*d++ = *s++)); return dest; } ```
In C a value of 0 means false and any other means true. Strings end in a null character with a value of 0. This while loop copies all the characters from s to d until the null (end of string) is reached. The assignment*d++ = *s++returns the same value as*s++is assigned to*d After the loop bothsanddwill be pointing after the null character. Note that the null is also copied.
I'm trying to dynamically link a Rust .so library with a C program in Linux with gcc. Using onlydlopenanddlcloseresults in no errors, but I get a segmentation fault with the following code: ``` char * (*my_function)(char *); char *my_input_string = "foo"; //...abbreviated code... my_function = dlsym(handle, "my_function"); char *my_output_string = (*my_function)(my_input_string); ``` I'm usinggcc -g foo.c -ldl -o footo compile, if that matters. I know that it's finding the symbol because I used#[no_mangle]in the rust library and themy_functionpointer is not null
I ran it throughgdband it turns out the library was trying to call a function in the calling program that didn't exist.
I am using Kinetis Design Studio v 3.0 and am trying to launch a C application on my FRDM-K64 board. The project builds just fine; however, when I try to debug, I get this error: ``` Error in final launch sequence Failed to execute MI command: -exec-run Error message from debugger back end: Don't know how to run. Try "help target". Don't know how to run. Try "help target". ``` I haven't a clue why this is happening. Other projects (such as the "bubble" example) launch just fine, and I am using basically the same launch configuration. I'm using Segger J-Link, although I tried using OpenOCD as well and got the same message. Any ideas of how to fix this?
I solved the problem--apparently my software needed to be updated. So if anyone is getting the same error, be sure you have tried checking for updates.
I have a program that only generates the output when it returns normally or when it calls theexit()function (I'm trying to usegcovon a C program). On a special input my program hangs in an infinite loop so I have to terminate it by sending termination signal. In this situation it won't produce the output I need since it wouldn't callexit(). Is there any way that I can force a running program to callexit()and terminate without touching the source code and writing a signal handler?
As suggested in the comments, I executed my program withingdband after receiving signal I manually callexit()and it worked like charm.
This question already has answers here:Why both clang and gcc only give a warning when there is a space after backslash if C standard says that whitespace is forbidden?(4 answers)Closed3 years ago. When using\to continue a line, are spaces allowedafterthe backslash (on the same line)?
A new-line character should go immediately after a backslash. The C++ standard (N4140) states: 2.2 Phases of translation....Each instance of a backslash character (\) immediately followed by a new-line character is deleted, splicing physical source lines to form logical source lines. Only the last backslash on any physical source line shall be eligible for being part of such a splice. (The C standard has the same rules in5.1.1.2 Translation phases.)
my code is given below ``` #include <stdio.h> #include <ctype.h> #define size 5 void main(){ int i; char letter[size]; for(i=0;i<size;i++) letter[i]=getchar(); for(i=0;i<size;i++) putchar(toupper(letter[i])); } ``` and the output is : ``` bitto@HP-ProBook-4430s:~$ gcc test.c bitto@HP-ProBook-4430s:~$ ./a.out a s d A S D ``` why is this happening? it was to read 5 characters and convert them to upper case.
As EOF said, any input you have will be taking two chars as input because you are typing inAthenEnterwhichCreads asaand\nso that is two chars, not one.
I'm rooting around some really old C code and have come across the following: ``` GLOBAL void Input_Channels() { // removed } ``` There are also plenty of similar, but LOCAL. What is this? I can't see any information anywhere about the LOCAL / GLOBAL function.
My best guess is that somewhere there are macros defined for this, to help you see whether the functions should be considered public or private (to use object-oriented lingo) - or whether the function is exported or not. GLOBAL could do nothing where LOCAL could mark the functions static. I haven't seen that before, so maybe it is an obscure addition to the syntax used by the compiler vendor. Which compiler are you using ?
This question already has answers here:Conditional execution based on short-circuit logical operation(2 answers)Closed7 years ago. So, let's say, I have this piece of code: ``` int value = 256; if( check_value_1(value) && check_value_2(value) ) { // .. do stuff .. } ``` If functioncheck_value_1()returnsFALSEwillcheck_value_2()be called?
Ifcheck_value_1(value)returnsFALSE, the second portion of the if-statement will be skipped and will not execute. This is known asshort circuit evaluation.
I'm making a program in C that has the option (for the user) to launch automatically at Linux startup. I'm looking for a code snippet or something helpful. The way I want to do it, is programmaticallyif the user selected auto-startup, then (code I am looking for) I saw many thing about cron jobs and/etc/rd.somethings, but it doesn't seems to be what I'm looking for.
if the user selected auto-startup, then (code I am looking for) One way is to add a cron job to that user's crontab with special time specification@reboot.
I am trying to print a SHA256 hash in C but when I use the for loop shown below, the only way the hash is printed is when I add the newline to printf. Ideally I want to print it all on one line. ``` void enclave_main() { char string[] = "Hello World"; int x; unsigned char digest[SHA256_DIGEST_LENGTH]; SHA256_CTX sha256; SHA256_Init(&sha256); SHA256_Update(&sha256, string, strlen(string)); SHA256_Final(digest, &sha256); for(x = 0; x < SHA256_DIGEST_LENGTH; x++) printf("%02x\n", digest[x]); sgx_exit(NULL); } ```
Standard output is (typically) line-buffered, which means output won't be flushed to the terminal until the buffer is fulloryou send a newlineoryou flush the stream manually withfflush(). The easiest thing to do is print the newline after the loop: ``` for(x = 0; x < SHA256_DIGEST_LENGTH; x++) printf("%02x", digest[x]); putchar( '\n' ); ```
I am trying to write a recursive Fibonacci generator that prints each term in C. The number of terms is user-specified; I have developed the algorithm. When I try to print, it only prints ones. Can anyone point me in the direction of where I am going wrong? ``` #include <stdio.h> #include <stdlib.h> int Fibonacci (int n) { if (n = 0) return 0; if (n = 1) return 1; else return (Fibonacci(n-1) + Fibonacci(n-2)); } int main() { int terms; printf("Enter the number of terms: "); scanf("%d", &terms); printf("\nThe Fibonacci sequence containing %d terms is:\n", terms); int i = 0; for (i; i < terms; i++) { printf("%d ", Fibonacci(i)); } return 0; } ```
``` if (n == 0) ``` not ``` if (n=0) ``` check your syntax careful.
The way to call execlp is shown in the following: ``` int execlp(const char *file, const char *arg, ... /* (char *) NULL */); ``` For example, ``` execlp("/bin/Binary","Binary","0x00","0x01","0x02",(char *)0); ``` In this case, since my argument"0x00","0x01"and"0x02"are always fixed. Can I create a char array instead of doing it this way ? ``` char *myArgv[]={0x00, 0x01, 0x02}; ``` And then execlp("/bin/Binary","Binary",myArgv,(char *)0); This one doesn't work because it will read only the first element in the array. Please advise.
I think you are looking forexecvp: ``` int execvp(const char *file, char *const argv[]); ``` But mindEOF's comment:0x00and"0x00"are most definitely not interchangeable. EDIT As pointed out in the comments, the array passed in this case toexecvpmust contain aNULLpointer as the last member (unlike your example that is).
I am trying to write a recursive Fibonacci generator that prints each term in C. The number of terms is user-specified; I have developed the algorithm. When I try to print, it only prints ones. Can anyone point me in the direction of where I am going wrong? ``` #include <stdio.h> #include <stdlib.h> int Fibonacci (int n) { if (n = 0) return 0; if (n = 1) return 1; else return (Fibonacci(n-1) + Fibonacci(n-2)); } int main() { int terms; printf("Enter the number of terms: "); scanf("%d", &terms); printf("\nThe Fibonacci sequence containing %d terms is:\n", terms); int i = 0; for (i; i < terms; i++) { printf("%d ", Fibonacci(i)); } return 0; } ```
``` if (n == 0) ``` not ``` if (n=0) ``` check your syntax careful.
The way to call execlp is shown in the following: ``` int execlp(const char *file, const char *arg, ... /* (char *) NULL */); ``` For example, ``` execlp("/bin/Binary","Binary","0x00","0x01","0x02",(char *)0); ``` In this case, since my argument"0x00","0x01"and"0x02"are always fixed. Can I create a char array instead of doing it this way ? ``` char *myArgv[]={0x00, 0x01, 0x02}; ``` And then execlp("/bin/Binary","Binary",myArgv,(char *)0); This one doesn't work because it will read only the first element in the array. Please advise.
I think you are looking forexecvp: ``` int execvp(const char *file, char *const argv[]); ``` But mindEOF's comment:0x00and"0x00"are most definitely not interchangeable. EDIT As pointed out in the comments, the array passed in this case toexecvpmust contain aNULLpointer as the last member (unlike your example that is).
This question already has answers here:when to use while loop rather than for loop(15 answers)Closed7 years ago. What is the need for using thewhileloop when we can iterate without usingwhile? Is there something that cannot be done withoutwhile?
There is nothing thatwhilecan do that you wouldn't be able to do withfor. In fact, ``` while (xxxxxxx) { } ``` can be replaced mechanically with ``` for (; xxxxxxx ;) { } ``` and the code would work exactly the same. The only reason for having thewhileloop as well is better readability of your code.
I have a problem with my two dimensional array in C. Say 2D array isboard[d][d](d=7) and i want to assign value ofboard[d-1][d-2]to anint. When i do this i get error, if i printfboard[d-1][d-2]i get32766. The highest value in the array isd*d-1=48. What am i doing wrong? ``` int main(void) { int d=7; int nr=(d*d)-1; int board[d][d]; int u=board[d-1][d-2]; bool even=false; if ((d/2)*2!=d) { even=true; } printf("%d\n", even); printf("%i\n", board[d-1][d-2]); //result here is 32764? for(int i=0;i<d;i++) { for(int j=0;j<d;j++) { board[i][j]=nr; nr--; printf(" %2d", board[i][j]); } printf("\n"); } return 0; } ```
It's because you didn't initialize it with any value, so it simply stores whatever garbage happened to be there in memory atm. You need to run on board and set initial values to it.
I have been going through the documentation and I'm still lost on how to filter out_idresults from mongodb using the C driver.I essentially want this functionality but I'm not sure ``` db.collection.find({"test":"pass"},{_id: false}); ``` How would I include that projection in C? ``` cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL); ```
After a bit of trial and error I was able to finally add flags to a search query. For anyone else here is the format for appending the No id flag to a MongoC search. bson_t *field = bson_new();BSON_APPEND_INT32(field,"_id", 0); to a search pattern like cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, query, field, NULL);
I created a library for my C programs and this includes threads. I usually work with Code::Blocks and I never had problems, but now I need to compile programs directly from terminal. I saw that I need to write-lpthreadbut also my library name (its name is my_lib.h). I tried to compile first the library withgcc my_lib.c -cand this works; after, I tried thisgcc main.c my_lib.h -o main -lpthread, but this doesn't work. So what is the correctly sintax to compile this program that uses my_lib.h?
I assumemy_lib.cis just a module (object file) rather than shared library. The compiling consists of two parts - compiling into object files and then linking: ``` # compiling (note the -c) gcc -c my_lib.c gcc -c main.c # linking (no -c, just specify target with -o) gcc -o main main.o my_lib.o -lpthread ``` Header files are never compiled (explicitly), they are just included from the.cfiles and therefore never produce.ofile.
I have a problem with my two dimensional array in C. Say 2D array isboard[d][d](d=7) and i want to assign value ofboard[d-1][d-2]to anint. When i do this i get error, if i printfboard[d-1][d-2]i get32766. The highest value in the array isd*d-1=48. What am i doing wrong? ``` int main(void) { int d=7; int nr=(d*d)-1; int board[d][d]; int u=board[d-1][d-2]; bool even=false; if ((d/2)*2!=d) { even=true; } printf("%d\n", even); printf("%i\n", board[d-1][d-2]); //result here is 32764? for(int i=0;i<d;i++) { for(int j=0;j<d;j++) { board[i][j]=nr; nr--; printf(" %2d", board[i][j]); } printf("\n"); } return 0; } ```
It's because you didn't initialize it with any value, so it simply stores whatever garbage happened to be there in memory atm. You need to run on board and set initial values to it.
I have been going through the documentation and I'm still lost on how to filter out_idresults from mongodb using the C driver.I essentially want this functionality but I'm not sure ``` db.collection.find({"test":"pass"},{_id: false}); ``` How would I include that projection in C? ``` cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL); ```
After a bit of trial and error I was able to finally add flags to a search query. For anyone else here is the format for appending the No id flag to a MongoC search. bson_t *field = bson_new();BSON_APPEND_INT32(field,"_id", 0); to a search pattern like cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, query, field, NULL);
I created a library for my C programs and this includes threads. I usually work with Code::Blocks and I never had problems, but now I need to compile programs directly from terminal. I saw that I need to write-lpthreadbut also my library name (its name is my_lib.h). I tried to compile first the library withgcc my_lib.c -cand this works; after, I tried thisgcc main.c my_lib.h -o main -lpthread, but this doesn't work. So what is the correctly sintax to compile this program that uses my_lib.h?
I assumemy_lib.cis just a module (object file) rather than shared library. The compiling consists of two parts - compiling into object files and then linking: ``` # compiling (note the -c) gcc -c my_lib.c gcc -c main.c # linking (no -c, just specify target with -o) gcc -o main main.o my_lib.o -lpthread ``` Header files are never compiled (explicitly), they are just included from the.cfiles and therefore never produce.ofile.
This question already has answers here:Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer(5 answers)Closed7 years ago. I'm trying out the following code: ``` int main() { char *yo = "yo"; char *whaddup = NULL; strcpy(whaddup,yo); } ``` and I get a segfault. Complete C noob here - other places say I should initializewhaddupas an array. Why can't I pass in a pointer to null?
Just anystrcpydocumentation will tell you that the destination string should be achararray large enough to hold the string and theNULterminator. So what you need is something like ``` char* yo = "yo"; char* whaddup = malloc(strlen(yo)+1); strcpy(whaddup, yo); ``` Or alternatively you could usestrdupfunction which does this for you, but it's not standard as it's POSIX only.
I'm using an Arduino Mini Pro and I'm using it to sample the data line of a C218D 433Mhz rf receiver. When using timer interrupts, the Arduino seems to miss most of the samples. However when using delays instead, it seems to work perfectly fine! Problem is, is that I cannot use delays for my project and need to use the timer interrupts. Is there some problem with Arduino interrupts? The problem persists even when I'm using delays but have interrupts enabled, even if they aren't doing anything!
Think i solved it, Serial port was open and messing with my interupts
I'm reading a file on linux and windows, on linux all work pretty well, but on windows, thefread(r_hash, 1, 64 , f);will put 64 char in r_hash then 32 char of junk, and I don't understand why. Here is my code Thanks! ``` int status; FILE *f; char *path; char ln[64]; char *r_hash = calloc(64, 1); path = malloc(1024); path = strcpy(path, "some path"); status = -1; f = fopen(path, "rb"); if (!f) return -1; while (fscanf(f, "%s ", ln)!=EOF) { fread(r_hash, 1, 64 , f); if(strcmp(w_hash, r_hash) == 0 && strcmp(hostname, ln) == 0) { status = 0; break; } } fclose(f); ```
r_hash = calloc(68, 1); // anything more than 64
I'm usingstat.st_mtimeto get my last modification time of a directory and then store it into afile.txt(stored string is something like that :1467035651) Later when I retrieved data from myfile.txt, I tried to convert my string from myfile.txttointtype since the string contains just seconds but I don't know if it's a good idea to do that. Is there any way to convert directly totime_t?
According to thereference documentationtime_tis just an unspecified numeric format. Just directly read back the numeric value from the file, there's no need for special conversions: ``` time_t t; std::ifstream input("File.txt"); // ... input >> t; ```
I've created a background worker. I want to manually delete it and relaunch a new one. At this point, I am doing the following: ``` select * from pg_stat_activity; select pg_terminate_backend(pid); ``` It certainly stops the current worker. But I think it does not delete the metadata about the bgworker. In the config file, the default number of bgworkers that can execute simultaneously is set to 8 and I am only able to repeat the above process for first eight times. After this point, I am not able to register the bgworker again. I suspect the metadata is not being deleted. Is there any other way to kill the bgworker completely?
Please refer the below URL for an answer: ``` https://www.postgresql.org/message-id/CALF3U-4To6FfrBcMWH2uR7yubcm03L9G0pJYMcyv0fNA6A%3DZ3Q%40mail.gmail.com ```
What are some use cases of do nothing function (in C) like: ``` dummy() {} ``` I am reading "The C programming Language" by K&R and in chapter 4 (Functions & Program Structures) , it mentions that A do-nothing function like this (shown above) sometimes useful as a place holder during program development. Can anyone explain what author means by that and uses of these types of functions?
A function that does nothing (yet) is an indicator that something should be done, but hasn't been implemented yet.
I have a struct inside a struct and on initialization of the outer struct I want to initialize the inner struct as const. ``` typedef struct A { uint16_t id; }A; typedef struct B { A a; uint16_t data; } ``` I know I can initialize the inner struct when initializing the outer struct by this code: ``` B test = { { .id = 0x100 }, .data = 0 }; ``` I know I can do it this way: ``` const A aTest = { .id = 0x100 }; B test = { .a = aTest, .data = 0 ``` But is there a way to make the inner initialization directly constant?
You need to define the inner member asconst: ``` typedef struct B { const A a; uint16_t data; } B; ``` Then you can initialize like this: ``` B test = { { .id = 0x100 }, .data = 0 }; ``` While this generates a compiler error: ``` test.a.id=1; ```
I was wondering ifcurrent->link->datadata andcurrent->dataprovides the same result. Also another concept what exactly the difference betweencurrentandcurrent->linkin singly linked list?
I was wondering if current->link->data data and current->data provides the same result. May be they provide same data if same data is stored, but these are different locations i.e. ifcurrent->dataisdataatcurrent nodethencurrent->link->datawould bedataofnext node. as shown in figure. ``` struct node { struct node *link; int data; }; ``` Consider a typicalnodeof singly linked list, as mentioned above. The memberlinkpoints toNULLinitially but later on it points to some othernode. Consider a linked list with some preinsertednode. And also another concept what exactly the difference between current and current->link in singly linked list? currentis pointer to currentnodewhilecurrent->linkis pointer to nextnodeto currentnode.
Below is the code in C language: function call: ``` insert(&head,value); void insert(struct node** headref,int value) { struct node* head = (*headref); while( head!=NULL ) { head= head->link; } struct node* new_node=(struct node*)malloc( sizeof(struct node) ); new_node->data=value; new_node->link=NULL; head=new_node; } ```
You need to link the last element of the list tonew_nodeotherwise you will loose the linked-ness(if there is such a word :) ) of your list. You need to store 2 pointers in the cycle -head, that you already have and a pointer to the previous element(the element before head). Take special care for the case where you have empty list!
I am programming STM32F373RCT and I have been trying to make a USB virtual comport device. if I send data up to about 960 bits per second (I used a timer (50Hz) and I transmit 14 bytes in every cycle), communication is working correctly but if I try to send data more than this, some data lost. I have to increase data transmission speed. How do I increase?
USB has built-in flow control so you should be able to send data as fast as possible without losing any data. There is either a bug in the USB stack you are using or in the code that you are using to send data to the USB stack. If you can identify and fix that bug, then you should be able to send data a lot faster without losing anything.
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.Closed7 years ago.Improve this question I have#included <xcb/xcb.h>and<xcb/xcb_util.h>and linked with-lxcbbut I still get an undefined reference to 'xcb_event_get_label' I can see the function exists in the header file, and the error indicates a linker error, but what other libraries do I need to link against?
Linking with-lxcb-utildid the trick as mentioned byMarcus Müller
according to the C Standard (and K&R) the syntax of the Comma-Operator is as follows: ``` expression: assignment-expression expression, assignment-expression ``` But why does this statement work? ``` 5+5, 1+1; ``` 5+5 and 1+1 are not assignment-expressions, but the C Standard requires assignment-expressions as operands for the Comma-Operator.
assignment-expression⊃conditional-expression⊃logical-OR-expression⊃logical-AND-expression⊃inclusive-OR-expression⊃exclusive-OR-expression⊃AND-expression⊃equality-expression⊃relational-expression⊃shift-expression⊃additive-expressionwhich finally are ⊃additive-expression + multiplicative-expression. So no, 5+5 is indeed ∈assignment-expression. ⊃ is the "contains" relation.
I have been able to use the digit-separator'in my C projects thus far. They have all been compiled with the MSVC compiler with no problems. I have just changed to using the GCC compiler instead, which does not allow these digit-separators and throws an error, when I use them. I assume the reason is because, Visual Studio uses the same compiler for C and C++, and in C++14 (I believe),'digit separators are allowed. If this is the case, is there then a digit separator usable in GCC? Those separators really help out a lot, when working with 64 bit register values in binary...
It's defined inn2626, thus, you can use this feature straightly with--std=c2x(for gcc/clang) currently.
``` #define HELPER(param) Wazz ##param HELPER(hek) ``` Doing agcc -E filenameshows me ``` Wazzhek ``` How do I getWazz hek? How do I insert a space between the 2 tokens? ``` #define HELPER(param) Wazz ## ## ##param ``` Doesnt work either. Any suggestions?
Just do not use token concatenation operator when you don't want to do token concatenation. ``` #define HELPER(param) Wazz param HELPER(hek) ```
My question is that in the below program,how does the code ``` while (scanf("%d %d", &a, &b), (a || b)) ``` is being evaluated? The program get two number and print the sum: ``` int a, b; while (scanf("%d %d", &a, &b), (a || b)) printf("%d\n", a + b); ```
Read more documentation aboutCand itsstandard library. Start by readingcarefullythe documentation ofscanf. Then read about thecomma operator,and thelogical operators(e.g.||and&&) Also, compile your code with all warnings & debug info (gcc -Wall -g) and run it step by step in the debugger (gdb). That would give you some (partial) intuition about how your computer is running your code. Don't forget to read aboutundefined behavior, notably C.Lattner's blog:What every C programmer should know about undefined behavior. A better code might be: ``` int a, b; while ((a=b=0), (scanf("%d %d", &a, &b)==2) && (a || b)) printf("%d\n", a + b); ```
I just know about the %i format specifier from this link Difference between format specifiers %i and %d in printf and I tried to implement it with this program. ``` #include <stdio.h> int main(){ long long a,b; printf("Input: "); scanf("%i %lld",&b,&a); printf("Output: %i %lld",b,a); } ``` %i worked properly but %lld stores a garbage value in variable a. This is the output of this program. Input : 033 033Output : 27 141733920846Process returned 0 (0x0) execution time : 4.443 s Press any key to continue. Can anyone explain, why I am getting the garbage value in variable a?
scanf%itakes anint *, but you're passing&b, which is along long int *. This has undefined behavior. You should be using%lli. The same problem occurs inprintf: Use%llito printb, not%i. You should also checkscanf's return value to make sure two values were successfully read.
I have a line of code like this: ``` for (ivalue=list[i];i>0 && list[i-1]>ivalue;i--) ... ``` which runs fine. But if I change the position of first condition i>0 it exits with Segmentation fault: 11 while running: ``` for (ivalue=list[i];list[i-1]>ivalue && i>0;i--) exits with Segmentation fault: 11 ``` Why the results depends on position of conditions in && operator?
The order of Associativity of&&operator is left to right So it first checks forlist[i-1]>ivaluebefore checkingi>0 Thus wheni=0thelist[i-1]becomeslist[-1]that is out of bound and hence givessegmentation error NOTE:i>0is never checked
Which way is the best for line up all the output on the right ? Example: for powers of 2: ``` 2 4 8 16 32 64 128 256 512 1024 2048 ... 134217728 ``` If my last number has N digits, how print the first one (which in this case has just one digit) with (N - 1) spaces on left ?
You can supply a computed field width toprintf()using*. So after you calculate the maximum number of digits, you can do: ``` printf("%*d\n", max_digits, value); ```
I know that in C both of these works: ``` char* string = "foo"; printf("string value: %s", string); ``` and more simply: ``` printf("string value: %s", "foo"); ``` But I was asking myself why. I know that%sidentifier expects the argument to be a char*, andstringactually is (and it will be the same with an array of characters, because this two datatypes are pretty the same in C) but when I pass directly a string to printf shouldn't it be different? I mean"foo"is not a pointer anymore... Right?.
The string constant"foo"has typechar []. When passed to a function, the array decays to a pointer, i.e.char *. So you can pass it to a function that expects the same. For the same reason, you can also pass a variable of this type: ``` char string[4] = "foo"; printf("string value: %s", string); ```
``` #include<stdio.h> int main() { FILE *opening; opening = fopen("hello.usr","w"); fprintf(opening,"Hello world!"); fclose(opening); printf("Writing to the file was successful.\n"); printf("Closing the program"); return 0; } ``` I have tried this code to create a file in c programming and write the text "Hello world!" in it. What's wrong with this code?
If you want to know what is wrong check the result offopen ``` opening = fopen("hello.usr","w"); if (opening == NULL) { perror("fopen"); } ```
I am working on an exercise where this is a piece of the code: ``` typedef struct node { size_t size; struct node *next; } node_t; byte heap[SIZE]; node_t *node_list; void heap_init() { node_list = (node_t*) heap; node_list->size = SIZE; node_list->next = NULL; } ``` But i have some trouble under standing the line: ``` node_list = (node_t*) heap; ```
heapis an array of bytes of sizeSIZE. node_listis a pointer of typenode_t. This pointer is assigned to the first byte of the arrayheap. What this does is thatnode_listis assigned to an allocated location of memory. I am guessing that the next pointer for the list will be assigned to a location further along this array. This is most probably simulating a heap in the global variables, and avoids the use ofmallocwhich cannot be used some embedded systems.
I know that in C both of these works: ``` char* string = "foo"; printf("string value: %s", string); ``` and more simply: ``` printf("string value: %s", "foo"); ``` But I was asking myself why. I know that%sidentifier expects the argument to be a char*, andstringactually is (and it will be the same with an array of characters, because this two datatypes are pretty the same in C) but when I pass directly a string to printf shouldn't it be different? I mean"foo"is not a pointer anymore... Right?.
The string constant"foo"has typechar []. When passed to a function, the array decays to a pointer, i.e.char *. So you can pass it to a function that expects the same. For the same reason, you can also pass a variable of this type: ``` char string[4] = "foo"; printf("string value: %s", string); ```
``` #include<stdio.h> int main() { FILE *opening; opening = fopen("hello.usr","w"); fprintf(opening,"Hello world!"); fclose(opening); printf("Writing to the file was successful.\n"); printf("Closing the program"); return 0; } ``` I have tried this code to create a file in c programming and write the text "Hello world!" in it. What's wrong with this code?
If you want to know what is wrong check the result offopen ``` opening = fopen("hello.usr","w"); if (opening == NULL) { perror("fopen"); } ```
I am working on an exercise where this is a piece of the code: ``` typedef struct node { size_t size; struct node *next; } node_t; byte heap[SIZE]; node_t *node_list; void heap_init() { node_list = (node_t*) heap; node_list->size = SIZE; node_list->next = NULL; } ``` But i have some trouble under standing the line: ``` node_list = (node_t*) heap; ```
heapis an array of bytes of sizeSIZE. node_listis a pointer of typenode_t. This pointer is assigned to the first byte of the arrayheap. What this does is thatnode_listis assigned to an allocated location of memory. I am guessing that the next pointer for the list will be assigned to a location further along this array. This is most probably simulating a heap in the global variables, and avoids the use ofmallocwhich cannot be used some embedded systems.
I'm current working in a C project with visual studio (community 2015). I'm attempted to remove warnings from my project. Currently I'm getting the following warning: C4100: 'argc': unreferenced formal parameter Searching on why I get this warning I found this stack overflow question:Why the unnamed parameter warning discrepency between C and C++? From what I understand, this is a C++ warning, not a C warning, even though my file ends with a.cextension. Is there any setting in visual studio that restricts building warnings to just C?
this is a C warning. It is saying that you have a parameter to a function that is not actually used within the function. Note: if the function ismain(), then never assume anything about the parameters, especially the number of command line parameters. This means do not reference anything beyondargv[0]without first checkingargcto assure that parameter actually exists.
I'm practicing structures in C, and I come up with this doubt. Sometimes I see something like: ``` struct myStruct{ //some data } *p; ``` What does that pointerpmeans? How is that different from: ``` struct myStruct{ //some data }; ```
In your code ``` struct myStruct{ //some data }; ``` is the definition of thestruct. There is novariablecreated with that data type. On the other hand, ``` struct myStruct{ //some data } *p; ``` is the definition of thestructas well as creating a variablepof type pointer-to-struct. After allocating memory top, you can access the member variables using that pointer.
How can I embed a small Python script into a Windows shell command to provide arguments to a program? Example: ``` C:\> hello Bob Welcome Bob! ``` What I need is something like this: ``` C:\> hello 'python -c print('Bob')' Welcome Bob! ``` Thanks!
Powershell supports the same format as bash, so you can do: ``` PS C:\> hello $(python -c "print('Bob')") ``` Forcmd.exe, there is no such equivalent, but you can try this (untested): ``` C:\>FOR /F "usebackq" %x in (`python -c "print('Bob')"`) DO hello %x ```
I'm trying to compile aCproject usinggcc. All source files and the .a library file arein the same folder. How can I successfully compile the project? I've tried: ``` gcc -o test main.c IPT.c logitem_list.c -L -./ -libpt ``` But I receieve error: ``` /usr/bin/ld: cannot find -libpt collect2: error: ld returned 1 exit status ```
You specify the directory to-Land the 'core' name to-l: ``` gcc -o test main.c IPT.c logitem_list.c -L . -lpt ``` When given-lpt, the linker looks forlibpt.aorlibpt.soor equivalents (extensions like.dylibor.slor.dllor.libon other platforms). The-L -./is suggesting that the linker look in a directory called 'dash dot', which is unlikely to exist and isn't wherelibpt.ais found anyway.
Here is my code. My question is, why does it keep printing only 5 numbers? Why won't it print 10 like it's supposed to? ``` #include<stdio.h> #include<stdlib.h> #include<time.h> int main(){ int r, col; srand((unsigned)time(NULL)); for (col=1; col<=10; col++){ r = rand() % 11; printf("%d\n", r); col++; } return 0; } ```
Because, you are doingcol++twice, once in the loop body, and once in the post-loop statement. ``` for (col=1; col<=10; col++) //...................(i) ^^^^^^^ ``` and ``` r = rand() % 11; printf("%d\n", r); col++; //.....................(ii) ^^^^^ ``` So, for a single iteration,colgets incrementedtwice, iteration count gets halved. Remove either of the statements.
I am familiar with the Arduino programming tools but have relatively small experience with embedded programming. When using decimal numbers in the Arduino I never had any issues, so when I recently started playing around with TI's Launchpad F28069M(TMS320F28069M Chip), I was surprised that my math was not yielding my expected results. While doing research, I realized that the TI chip has a fixed point processor which may explain why my decimals are being truncated to 0. (See brief code example) My questions are the following: How should I declare decimal numbers in my code?Should I use TI's IQ math?Why was I able to declare and perform math functions with decimal numbers in the Arduino without any issue? My Code ``` Uint16 A; main() { A = .25; } ``` Result from Expression Window in TI's CCS:Expression Window CCS
Try with this code instead: ``` float A; main() { A = .25; } ```
Can we access the mtharray element, if it has m elements? I mean that, if the array has 7 elements, was it ever possible to store any value in array[7]? But the array indexes start from 0 and end with 6, when length is is 7.
No, accessing the element beyond the array bound is undefined behaviour. Taking address of the element 1 beyond last array element is well defined. To understand the implications, consider readingHow dangerous is it to access an array out of bounds?
The value contained in the pointer 'p' from the structure below is wrong printed and i can not find the way to print it right. What's the right code for it? The code: ``` #include <stdio.h> struct my_struct{ //structure definition int a,*p; }; int main(){ my_struct var; var.a = 5; //variable definition var.p = &(var.a); //pointer gets address from variable printf("%d\n",var.p); // the number 2686744 is printed instead of the number '5' return 0; } ```
The%dformat specifier toprintfexpects anint, but you're passing it anint *. You need to dereference the pointer to obtain anint: ``` printf("%d\n",*(var.p)); ```
I want to iterate through any array starting at an index that's close to the middle, go to the end then go to the beginning.As an example: ``` #include <stdio.h> int main(){ int a[]= {1, 2, 3, 4, 5, 6, 7,}; int i = 0; for (i = 2; i < 6; i++){ if (i == 6){ i = 0; } printf("%d\n", a[i]); } return 0; } ``` How can I "reassign" the index to be zero when it reaches the end (index 6)
Here is a simple write-up. Not tested so adjust as needed. The idea is have the counter start at 0 and add the value of start each time using modulus to make it relative. ``` int a[]= {1, 2, 3, 4, 5, 6, 7}; int length = sizeof(a)/sizeof(a[0]); int start = length/2; for (int i = 0; i < length; i++) { printf("%d\n", a[(i+start)%length]); } ``` And props to @SouravGhosh for pointing out modulus in the comments before I got this answer up.
I am using tcp to transfer data. The server code is written by C, and client code is written by nodejs. When I send one buffer, sometimes the client will receive two parts of this buffer, the console.log function will trigger twice, but sometimes it works well. following are nodejs code and C code. nodejs code: ``` var client = new net.Socket(); client.on('data', function(data) { console.log('data:', data) }); ``` C code: ``` send(socket_file, buffer, strlen(buffer),0) ```
This is typical for TCP, which is a stream-oriented (as opposed to packet-oriented like UDP) protocol after all. There's no guarantee that one write to the network equals one read at the other end, multiple writes may be delivered together and single writes may be split. You must add an applicaton-level message protocol.
What is the quickest bit-hack to achieve the following result? Let x be a 4 byte int, in a C program. If x is0x00000000, then x should be0xFFFFFFFF, else x should be untouched.
x |= -(x == 0);x |= -!x;x = x ? x : 0xFFFFFFFF;if (x == 0) x = 0xFFFFFFFF;... Benchmark and choose what's appropriate for you
I want to print the decimal value of 1010 ingdb, but it prints the result as it is what I gave last. ``` (gdb) (gdb) p/d 1010 $1 = 1010 (gdb) ```
GDB'sp[rint] command prints the value of the expression you provide, which is interpreted in the source language of the program being debugged. In C, your1010is a decimal literal, not a binary literal, so your basic problem is that you are giving GDB bad input. Standard C has no support for binary literals, but GNU C supports them as an extension. The format is a binary digit string preceded by0bor0B, which you'll probably recognize as analogous to the standard format for hexadecimal literals. GDB recognizes this form. Sinceprint's default output radix for numbers is decimal, you don't need to specify an output format. Just use the command ``` p 0b1010 ```
The value contained in the pointer 'p' from the structure below is wrong printed and i can not find the way to print it right. What's the right code for it? The code: ``` #include <stdio.h> struct my_struct{ //structure definition int a,*p; }; int main(){ my_struct var; var.a = 5; //variable definition var.p = &(var.a); //pointer gets address from variable printf("%d\n",var.p); // the number 2686744 is printed instead of the number '5' return 0; } ```
The%dformat specifier toprintfexpects anint, but you're passing it anint *. You need to dereference the pointer to obtain anint: ``` printf("%d\n",*(var.p)); ```
I want to iterate through any array starting at an index that's close to the middle, go to the end then go to the beginning.As an example: ``` #include <stdio.h> int main(){ int a[]= {1, 2, 3, 4, 5, 6, 7,}; int i = 0; for (i = 2; i < 6; i++){ if (i == 6){ i = 0; } printf("%d\n", a[i]); } return 0; } ``` How can I "reassign" the index to be zero when it reaches the end (index 6)
Here is a simple write-up. Not tested so adjust as needed. The idea is have the counter start at 0 and add the value of start each time using modulus to make it relative. ``` int a[]= {1, 2, 3, 4, 5, 6, 7}; int length = sizeof(a)/sizeof(a[0]); int start = length/2; for (int i = 0; i < length; i++) { printf("%d\n", a[(i+start)%length]); } ``` And props to @SouravGhosh for pointing out modulus in the comments before I got this answer up.
I know I can do this: ``` //With A = tax(x); return tan(arctan(A)/2); ``` but I wanted something more efficient.
Whenxis between -π/2 and π/2 you can use this formula: ``` t / (1 + sqrt(1 + t*t)) ``` This is hardly an improvement on the original formula, but it uses one function call instead of two. Note:I found this formulahere. The wikipedia page is in Russian, and the equivalent English page does not include the same formula.
I just got a error from connect API in linux. I knew 'connect' will return zero if connection is successful, I got return value "3" is it error code? or is there something else what don't know? ``` connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); ``` I got value 3 from sock.
To get the return value ofconnect(), it is most straight forward to use a variable that is used as the left hand side of an assignment. ``` int result = connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); printf("connect returned: %d\n", result); ``` sockmust be a socket, and was assigned a file descriptor number as a result of a call tosocket(). Most UNIX APIs that return a new file descriptor will return the lowest available one. A program usually starts off with descriptors0,1, and2already in use (for STDIN, STDOUT, and STDERR). So, it is not unexpected thatsocket()returned3.
Is the same ``` char* s1[size]; ``` To ``` char** s2 = malloc(size * sizeof(char*)); ``` They have any difference?
Theoretically,*arr[]and**arrare different. For example : ``` char *arr[size]; //case 1 ``` Herearris a an array of sizesizewhose elements are of the typechar* Whereas, ``` char **arr; //case2 ``` Herearris itself a pointer to the typechar* Note:Incase 1arrayarrdegrades to a pointer to become the typechar**but it's not possible the other way around i.e, pointer incase 2cannot become an array.
I am reading lines from a file, the lines look like this: ``` 89f81a03eb30a03c8708dde38cf:000391716 ``` The thing is: I want to remove everything after the:(including the:). I tried everything I could find online but they seem to useconst charand the lines arecharpointers.
You can usestrchr: ``` char str[] = "89f81a03eb30a03c8708dde38cf:000391716"; char *ptr; ptr = strchr(str, ':'); if (ptr != NULL) { *ptr = '\0'; } ```
So, it has been some time since I last programmed in C, and now I am trying to get back into C again, but I am having trouble with my program. The program is very simple, I use getchar to store chars in a char array, but for some reason the program stops running after my while loop. ``` #include <stdio.h> #define MAXLINE 1000 int main(){ char c; char input[MAXLINE]; int i = 0; while((c = getchar()) != EOF){ input[i] = c; ++i; } printf("Still running"); } ``` So, my program doesn't print "Still running".
Send EOF (Ctrl+D for *nix Ctrl+Z for Win), it will show the Still running. ``` root@Linux-VirtualBox:~/program/progEdit# ./stktest.o sdf fdf sdf Still runningroot@Linux-VirtualBox:~/program/progEdit# ```
Can anyone tell me why my MATLAB code reads doubles correctly, but not floats? This works as expected: Linux c server code: ``` double x = 25.2575; write(sd, &x, sizeof(x)); ``` MATLAB client code ``` t = tcpip('10.5.5.7', 50505, 'NetworkRole', 'client'); t.InputBufferSize = 8; fopen(t); data = swapbytes(fread(t, 1, 'double')); ``` MATLAB correctly reads in 25.2575 This does not Linuc c server code ``` float x = 25.2575; write(sd, &x, sizeof(x)); ``` MATLAB client code ``` t = tcpip('10.5.5.7', 50505, 'NetworkRole', 'client'); t.InputBufferSize = 4; fopen(t); data = swapbytes(fread(t, 1, 'float')); ``` MATLAB incorrectly reads in 6.850875536870000e-313
The problem was solved by removing the swapbytes call and instead using: ``` t.ByteOrder = 'littleEndian'; ``` I do not know why however.
This question already has an answer here:__PTRDIFF_TYPE__ vs. ptrdiff_t(1 answer)Closed7 years ago. I see it is legal to use the variable__PTRDIFF_TYPE__with no header inclusion. I tried to look for this variable name inISO/IEC 9899but it does not appear. I expected to see its definition in the 7th part, C library. Why is it legal ? I am using the gcc under Linux/GNU.
This is a predefined macro in gcc (a GNU C extension); seehttps://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html. As for why this is legal: The standard reserves all names starting with two underscores (and all names starting with an underscore followed by an uppercase letter) for use by the implementation, so gcc could predefine__whateverand still follow the standard.
I want to initialize a couple of arrays which are members of a struct which is passed to a function by reference. Appreciate any help. ``` typedef struct Snake_pos { char field[10][10]; int Y[10]; int X[10]; }snake_pos; int main() { snake_pos pos1; pos_init(&pos1); return 0; } void pos_init(snake_pos *pos1) { pos1->X={}; pos1->Y={}; pos1->field={}; } ```
You can only use the syntax= {}when defining the variable. So to zero every member you can either define it as ``` snake_pos pos1 = { 0 }; ``` Or if it is passed to a function, like this ``` void pos_init(snake_pos *pos1) { memset(pos1, 0, sizeof *pos1); } ```
``` #include <stdio.h> int main(void) { double numbersEntered, sum = 0; do { printf("Enter a number: "); scanf("%lf", &numbersEntered); sum += numbersEntered; } while (/* ??? */); printf("Sum = %.2lf", sum); return 0; } ``` What should I do in thewhilestatement to stop the loop after the user enters4integers?
You need to introduce a counter: ``` double numbersEntered, sum = 0; int count = 0; do { printf("Enter a number: "); scanf("%lf", &numbersEntered); sum += numbersEntered; count++; } while (count < 4); ``` Make sure you increment it otherwise your loop will never end. Changing the 4 to a constant (or even a configurable) variable will make the program more flexible, but whether you actually need to do that depends on what your application needs to do.
According to the given Elf32_Ehdr structure (page9) in the linkelf-formatelf header size should be 52 bytes and fixed. But there is also field e_ehsize and can be greater than 52 bytes. In where defined those extra bytes until first section header starts ?
As it says, also on page 9: Some object file control structures can grow, because the ELF header contains their actual sizes.If the object file format changes, a program may encounter control structures that are larger or smaller than expected. Programs might therefore ignore ‘‘extra’’ information. The treatment of ‘‘missing’’ information depends on context and will be specifiedwhen and if extensions are defined. (emphasis added). Nothing defines the semantics of any extra bytes, currently; they would comprise an extension. Furthermore the text implies that if you find a file with anElf32_Ehdrsection longer than 52 bytes, you can safely ignore the extra bytes.
This question already has answers here:Is floating point math broken?(33 answers)Closed7 years ago. I am using Code::Block 16.01, the current version, that come with compiler. The problem is when I changexMaxto1.2, the result does not change. It produce the same result asxMax=1.1. Did I do something wrong with my C code? Or is this a compiler problem? Here is my MWE: ``` #include<stdio.h> int main() { double xMin=1.0; double xMax=1.1; double x=xMin; double h=0.1; while(x <= xMax) { printf("x=%f\n",x); x=x+h; } return 0; } ```
You have a float point precision problem. Since1.2cannot be represented exactly in the binary form, there is a precision loss. Your code should work if you change1.2to something bigger, let's say,1.201 In general, please try to avoid=in float point comparisons.
I am writing a GPIO-driver for my RPI2 OS. And I was surfing really long time about it, but I found only linux data. How should I do such functions as ``` void gpio_set(int pin); void gpio_clr(int pin); ``` in C for the driver. Or, maybe it can be done due inline assembly?
As explainedhere The underlying architecture in BCM2836 is identical to BCM2835. The only significant difference is the removal of the ARM1176JZF-S processor and replacement with a quad-core Cortex-A7 cluster. The available documentation for the BCM2836 does not detail the peripheral hardare, only the A7. Instead you need the documentation for theBCM2835. Theperipheral specificationsection 6 deals with the GPIO. The registers are memory mapped so you can write directly to them in C.
``` #include <stdio.h> int main(void) { double numbersEntered, sum = 0; do { printf("Enter a number: "); scanf("%lf", &numbersEntered); sum += numbersEntered; } while (/* ??? */); printf("Sum = %.2lf", sum); return 0; } ``` What should I do in thewhilestatement to stop the loop after the user enters4integers?
You need to introduce a counter: ``` double numbersEntered, sum = 0; int count = 0; do { printf("Enter a number: "); scanf("%lf", &numbersEntered); sum += numbersEntered; count++; } while (count < 4); ``` Make sure you increment it otherwise your loop will never end. Changing the 4 to a constant (or even a configurable) variable will make the program more flexible, but whether you actually need to do that depends on what your application needs to do.
According to the given Elf32_Ehdr structure (page9) in the linkelf-formatelf header size should be 52 bytes and fixed. But there is also field e_ehsize and can be greater than 52 bytes. In where defined those extra bytes until first section header starts ?
As it says, also on page 9: Some object file control structures can grow, because the ELF header contains their actual sizes.If the object file format changes, a program may encounter control structures that are larger or smaller than expected. Programs might therefore ignore ‘‘extra’’ information. The treatment of ‘‘missing’’ information depends on context and will be specifiedwhen and if extensions are defined. (emphasis added). Nothing defines the semantics of any extra bytes, currently; they would comprise an extension. Furthermore the text implies that if you find a file with anElf32_Ehdrsection longer than 52 bytes, you can safely ignore the extra bytes.
This question already has answers here:Is floating point math broken?(33 answers)Closed7 years ago. I am using Code::Block 16.01, the current version, that come with compiler. The problem is when I changexMaxto1.2, the result does not change. It produce the same result asxMax=1.1. Did I do something wrong with my C code? Or is this a compiler problem? Here is my MWE: ``` #include<stdio.h> int main() { double xMin=1.0; double xMax=1.1; double x=xMin; double h=0.1; while(x <= xMax) { printf("x=%f\n",x); x=x+h; } return 0; } ```
You have a float point precision problem. Since1.2cannot be represented exactly in the binary form, there is a precision loss. Your code should work if you change1.2to something bigger, let's say,1.201 In general, please try to avoid=in float point comparisons.
I am writing a GPIO-driver for my RPI2 OS. And I was surfing really long time about it, but I found only linux data. How should I do such functions as ``` void gpio_set(int pin); void gpio_clr(int pin); ``` in C for the driver. Or, maybe it can be done due inline assembly?
As explainedhere The underlying architecture in BCM2836 is identical to BCM2835. The only significant difference is the removal of the ARM1176JZF-S processor and replacement with a quad-core Cortex-A7 cluster. The available documentation for the BCM2836 does not detail the peripheral hardare, only the A7. Instead you need the documentation for theBCM2835. Theperipheral specificationsection 6 deals with the GPIO. The registers are memory mapped so you can write directly to them in C.
Linking C with Assembly in Visual StudioI've seen that already but that doesn't contain any helpful informations. I have a C program, in which I'm using function written in assembly. I include fun.h header in C file with declaration, and have fun.asm with implementation. It was firstly written using NASM, and there is aglobalkeyword. How can I achieve the same proper linking effect in MASM? Minimal example: main.c: ``` int main() { f(); return 0; } ``` f.h: ``` void f(); ``` f.asm: ``` .DATA _05 DQ 0.5 _PI DQ 3.14159265358979323846264338327 .CODE public _f _f PROC _f ENDP END ```
According to what Michael Petch wrote in comment: Searched keyword is PUBLIC, and in x86_64 there is NO need for underscore on PROC functions.
fwrite()is a library call that firstly buffers the data into a user space buffer, and then calls thewrite()system call later to actually carry out the write operations. If a program invokesfwrite()to write some data to a file but then exists abnormally, will the buffer offwrite()beclearedflushed, or the buffered data will be left over in memory? The OS I am considering is Linux.
If your program exited abnormally, any buffered data will not be flushed. The OS just says "oh dear me, you left a file descriptor open, I better close that for you" when the process terminates; it has no idea there's some random data lying somewhere in memory that the program intended to write to disk but did not.
Consider thedocumentationofuv_tcp_connect.Here is the declaration of the function: ``` int uv_tcp_connect(uv_connect_t* req, uv_tcp_t* handle, const struct sockaddr* addr, uv_connect_cb cb); ``` It accepts a callback and returns an integer.Usually, the other functions inlibuvreturns an error code (0 in case of no errors).I guess also this one works the same way. What is unclear to me (and undocumented as well) is: in case of a return value not equal to 0, will the callback be invoked anyway?In other terms, does a return value different from 0 mean that the operation won't be performed at all or it is guaranteed that the callback is invoked? Unfortunately, it seems that it is not documented what the return value actually is.
See theerror handling sectionin the documentation. An error (return < 0) means no operation will be performed and no callback will be called.
Could you help me understand what the following piece of code means? Specifically, I do not understand what the effect ofname_fnis. ``` #define name_fn void name_fn Function(void); ```
The macroname_fnexpands to nothing during pre-processing. So the next line is same as ``` void Function(void); ``` Empty#defineis useful for compatibility, self documentation and/or mechanical checking. For example, in socket programming, you may encounter : ``` SOCKET WSAAPI accept (IN SOCKET s,OUT struct sockaddr FAR* addr, OUT int FAR* addrlen ); ``` HereINandOUTare empty macros. They Can be used to mechanically[ check ]the code.Serve as a strong reminder on how the author intended use the parameters associated with them.
I'm on my IOT project with raspberry pi, And I want to raise event in certain time like 06:00:00 and 12:00:00 But I can't do this with jiffies because jiffies only counts the time since the os started. I have an Idea : I may raise interrupt every second and check local time, compare it with certain time. But I think it is very bad way Do you have any good idea for this problem? Thanks in advance.
Run a cron at 06:00:00 and 12:00:00. Trigger your event through cron.How to create a cronjob
fwrite()is a library call that firstly buffers the data into a user space buffer, and then calls thewrite()system call later to actually carry out the write operations. If a program invokesfwrite()to write some data to a file but then exists abnormally, will the buffer offwrite()beclearedflushed, or the buffered data will be left over in memory? The OS I am considering is Linux.
If your program exited abnormally, any buffered data will not be flushed. The OS just says "oh dear me, you left a file descriptor open, I better close that for you" when the process terminates; it has no idea there's some random data lying somewhere in memory that the program intended to write to disk but did not.
Consider thedocumentationofuv_tcp_connect.Here is the declaration of the function: ``` int uv_tcp_connect(uv_connect_t* req, uv_tcp_t* handle, const struct sockaddr* addr, uv_connect_cb cb); ``` It accepts a callback and returns an integer.Usually, the other functions inlibuvreturns an error code (0 in case of no errors).I guess also this one works the same way. What is unclear to me (and undocumented as well) is: in case of a return value not equal to 0, will the callback be invoked anyway?In other terms, does a return value different from 0 mean that the operation won't be performed at all or it is guaranteed that the callback is invoked? Unfortunately, it seems that it is not documented what the return value actually is.
See theerror handling sectionin the documentation. An error (return < 0) means no operation will be performed and no callback will be called.
I am trying to make this for-loop parallelized by using Openmp, i recognized that there reduction in this loop so i added "#pragma omp parallel for reduction(+,ftab)",but it did not work and it gave me this error : error: user defined reduction not found for ‘ftab’. ``` #pragma omp parallel for reduction(+:ftab) for (i = 1; i <= 65536; i++) ftab[i] += ftab[i-1]; ```
The operation you want to do isprefix sum. It can be done in parallel. A simple way is to usethrust::inclusive_scanwith OpenMP or TBB backend. ``` thrust::inclusive_scan(thrust::omp::par, ftab, ftab + 65536, fab); ``` or ``` thrust::inclusive_scan(thrust::tbb::par, ftab, ftab + 65536, fab); ``` You could also implement it by yourself as referenced inthe Wikipedia page.
This question already has answers here:Is short-circuiting logical operators mandated? And evaluation order?(7 answers)Closed7 years ago. Let's take this C-code example: ``` int ID = 0; if( (Check(&ID) == ERROR) ||(ID == -1) ){ return ERROR; } ``` Do you have any guarantee that(Check(&ID) == ERROR)ischeckedbefore(ID == -1)? (ID = -1would be an error-state, set by the functionCheck)
Yes you do. For an expression of the formx || y,yis only evaluated ifxevaluates to 0. This is calledshort-circutting, and also applies to&&. Your parentheses are also superfluous: the same applies to the equivalent (and, in my opinion, clearer) if (Check(&ID) == ERROR || ID == -1)
Given the filealfa.c: ``` #include <stdio.h> int main() { // this is a comment puts("hello world"); } ``` I can format it with GNU Indent like so: ``` $ indent -st alfa.c #include <stdio.h> int main () { // this is a comment puts ("hello world"); } ``` However the comment is now way off to the right. I did try adding an option: ``` $ indent -st -c0 alfa.c #include <stdio.h> int main () { // this is a comment puts ("hello world"); } ``` but this is still not quite right. Can Indent be invoked such a way that the comment starts after only 1 or 2 spaces?
indent -c0 -nut -ts2 This will change all your tabs to spaces. the -c0 removes indentation for comments after code (so this will affect all comments). edit: reduced the spaces in a tab
This question already has answers here:What does a colon in a struct declaration mean, such as :1, :7, :16, or :32?(3 answers)Closed7 years ago. I have been trying to improve my understanding of C/C++ but looking at includes for functions, such asprintf, which I use a lot. However I am running across a syntax which I am not familiar with, nor am I able to find. What does the ':' mean? For example: ``` unsigned int is_long_double:1; ``` It seems that it would be some type of precursor to the boolean expression.
It defines the variable as a bitfield of length 1 bit. It's only valid in a struct, and only makes sense if you have multiple bitfields together. Don't use it as a generic boolean because it doesn't save memory - a single bitfield on its own will still take up a full word of memory.
Another company gives me three files(demo.c,api.h,libapi.so). they told me that't enough for develop. I'm confuse how to build these thing together. I use gcc demo.c -o demo -l libapi.so . But's it's said "ld: library not found". I use Mac OS system. Some websites said i should use Linux to use .so file. what should I do?
*.so is "shared object" it works only on Linux. The Windows counterpart of *.so is DLL.These are combiled object code. What you have to do is 1] "compile" your .c to .o [object file] 2] "Link" the new .o file with the .so
I have a socket server which should receive a message and write an answer. For some messages I want to send a special answer. If the message is for example"Hello"I want to answer"Hi!". Here is a part of my code: ``` ... char in[2000]; char out[2000]; ... while((read_size = recv(fd, in, 2000, 0)) > 0){ if(strcmp(in, "Hello") == 0){ strcpy(out, "Hi!\n"); } else{ strcpy(out, in); } write(fd, out, strlen(out)); } ... ``` But thestrcmp()doesn't work fine here. Because when I type in"Hello"there is not only the"Hello"in theinvariable, because the length is 2000. But how can I check now, if the received message is"Hello"?
Usestrncmpfunction, which compares the firstnbytes of the string: ``` if (strncmp(in, "Hello", strlen("Hello")) == 0) ... ```
I am trying to make this for-loop parallelized by using Openmp, i recognized that there reduction in this loop so i added "#pragma omp parallel for reduction(+,ftab)",but it did not work and it gave me this error : error: user defined reduction not found for ‘ftab’. ``` #pragma omp parallel for reduction(+:ftab) for (i = 1; i <= 65536; i++) ftab[i] += ftab[i-1]; ```
The operation you want to do isprefix sum. It can be done in parallel. A simple way is to usethrust::inclusive_scanwith OpenMP or TBB backend. ``` thrust::inclusive_scan(thrust::omp::par, ftab, ftab + 65536, fab); ``` or ``` thrust::inclusive_scan(thrust::tbb::par, ftab, ftab + 65536, fab); ``` You could also implement it by yourself as referenced inthe Wikipedia page.
This question already has answers here:Is short-circuiting logical operators mandated? And evaluation order?(7 answers)Closed7 years ago. Let's take this C-code example: ``` int ID = 0; if( (Check(&ID) == ERROR) ||(ID == -1) ){ return ERROR; } ``` Do you have any guarantee that(Check(&ID) == ERROR)ischeckedbefore(ID == -1)? (ID = -1would be an error-state, set by the functionCheck)
Yes you do. For an expression of the formx || y,yis only evaluated ifxevaluates to 0. This is calledshort-circutting, and also applies to&&. Your parentheses are also superfluous: the same applies to the equivalent (and, in my opinion, clearer) if (Check(&ID) == ERROR || ID == -1)
Given the filealfa.c: ``` #include <stdio.h> int main() { // this is a comment puts("hello world"); } ``` I can format it with GNU Indent like so: ``` $ indent -st alfa.c #include <stdio.h> int main () { // this is a comment puts ("hello world"); } ``` However the comment is now way off to the right. I did try adding an option: ``` $ indent -st -c0 alfa.c #include <stdio.h> int main () { // this is a comment puts ("hello world"); } ``` but this is still not quite right. Can Indent be invoked such a way that the comment starts after only 1 or 2 spaces?
indent -c0 -nut -ts2 This will change all your tabs to spaces. the -c0 removes indentation for comments after code (so this will affect all comments). edit: reduced the spaces in a tab
This question already has answers here:What does a colon in a struct declaration mean, such as :1, :7, :16, or :32?(3 answers)Closed7 years ago. I have been trying to improve my understanding of C/C++ but looking at includes for functions, such asprintf, which I use a lot. However I am running across a syntax which I am not familiar with, nor am I able to find. What does the ':' mean? For example: ``` unsigned int is_long_double:1; ``` It seems that it would be some type of precursor to the boolean expression.
It defines the variable as a bitfield of length 1 bit. It's only valid in a struct, and only makes sense if you have multiple bitfields together. Don't use it as a generic boolean because it doesn't save memory - a single bitfield on its own will still take up a full word of memory.
Another company gives me three files(demo.c,api.h,libapi.so). they told me that't enough for develop. I'm confuse how to build these thing together. I use gcc demo.c -o demo -l libapi.so . But's it's said "ld: library not found". I use Mac OS system. Some websites said i should use Linux to use .so file. what should I do?
*.so is "shared object" it works only on Linux. The Windows counterpart of *.so is DLL.These are combiled object code. What you have to do is 1] "compile" your .c to .o [object file] 2] "Link" the new .o file with the .so
This question already has an answer here:Why can't I pass constant arrays as arguments?(1 answer)Closed7 years ago. In Fortran, one can pass an array constructed on the fly to a subroutine: ``` call sub_that_wants_3_elm_array((/1,2,3/),output_arg) ``` Is it possible to do something analogous in C? This seems awfully basic, but I haven't been able to find anything on this, either yes or no.
Yes. It's possible usingcompound literals(since C99). E.g. ``` #include <stdio.h> void fun(int *a) { printf("%d\n", a[2]); //prints 72 } int main(void) { fun((int[]){1, 99, 72}); } ``` You can find some more examples from the links as well: The New C: Compound LiteralsCompound Literals - gcc