question
stringlengths
25
894
answer
stringlengths
4
863
I'm having issues with a c program that I want to debug. I would like to know how to get a file that contains every lines of my executable, so I can later set breakpoints with gdb in it. Thanks :)
For GCC specify-gwhen compiling. More here:https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html
``` #include<stdio.h> int main(void) { double c; scanf("%f", &c); printf("%f", c); } ``` This is an exerpt from a program I'm attempting to write, but I get the same issue with something this simple. when I run this, and enter "1.0", it prints out "0.007812". I've looked at several previous questions that were similar to mine and could not find an appropriate answer.
You need to use"%lf"for double. This is the warning from clang compiler. warning: format specifies type 'float *' but the argument has type 'double *' [-Wformat] scanf("%f", &c); Here is thescanf reference. It's format is%[*][width][length]specifier. The specifier for 'floating point number' isf. So we use%fto readfloat x. To readdouble x, we need to specify the length asl. Combined the format is%lf.
Making a simple program where the user inputs different classes, times and dates, and a timetable is generated (like a timetable with university classes). I've worked with Windows API for basic applications however I cannot find a way to display all the information in a timetable chart. Something like this: Is there a function that can be used in Windows API for displaying a timetable, or will I have to work with graphics to generate an image of a timetable (using OpenGL for instance)?
If you are programming in Win32 mode, to use ListView control is a better choice. You could get references from msdn:ListView ControlYou can also use the TextOut api to print information onto your Window form.
I have been trying to study the source code of clamav open source antivirus as a part of my project. Hence I downloaded the latest stable releaseclamav.0.99.2.tar.gzfrom the website. I'm using eclipse neon.2 Release 4.6.2 on Windows 10 64-bit. I created an existing make file project using the clamav folder extracted, and then converted it into an C/C++ autotools project. While configuring the project, I get an error "openssl not found", Although I have installed openssl in my cygwin64 terminal and also I run the ecipse from this terminal only. Is my approach completely wrong?
from the terminal in the linux VM, type: ``` sudo apt-get install libssl-dev ``` to install the SSL then from the clamav-0.99.2 directory type: ``` ./configure ``` when that completes then type: ``` make ``` This will take a while to complete, then (if you want to actually install the clamav application) type: ``` make install ```
This question already has answers here:Concise way to implement round() in C?(10 answers)Closed6 years ago. like 52.7-->53, 5.5-->6, 3.2->3
To handle negative numbers properly (-52.7 ==> -53 (away from zero)), you must check if the initial value is negative: ``` ((int)(num + ((num > 0)? +0.5 : -0.5))) ```
This question already has answers here:What's the difference between passing by reference vs. passing by value?(18 answers)Closed6 years ago. ``` #include <stdio.h> increment(char *c) { c++; c++; printf("works 'n' %c \n", *c); } int main() { char *p; char mon[10] = "Monday"; p = mon; increment(p); printf("expecting 'n' %c \n", *p); return 0; } ``` If character buffer pointer incremented in other function it will not reflect after coming out of the function.
Inincrement(char *c)you create a new pointercwhich is pointing to the same objectpdoes, but they arenotthe same, they are just pointing to the same thing. If you increment one, the other one stays the same. If you want to increment the pointerpyou need a pointer to this pointer, pass it to your function and changepinstead of a local copy.
I have been trying to study the source code of clamav open source antivirus as a part of my project. Hence I downloaded the latest stable releaseclamav.0.99.2.tar.gzfrom the website. I'm using eclipse neon.2 Release 4.6.2 on Windows 10 64-bit. I created an existing make file project using the clamav folder extracted, and then converted it into an C/C++ autotools project. While configuring the project, I get an error "openssl not found", Although I have installed openssl in my cygwin64 terminal and also I run the ecipse from this terminal only. Is my approach completely wrong?
from the terminal in the linux VM, type: ``` sudo apt-get install libssl-dev ``` to install the SSL then from the clamav-0.99.2 directory type: ``` ./configure ``` when that completes then type: ``` make ``` This will take a while to complete, then (if you want to actually install the clamav application) type: ``` make install ```
This question already has answers here:Concise way to implement round() in C?(10 answers)Closed6 years ago. like 52.7-->53, 5.5-->6, 3.2->3
To handle negative numbers properly (-52.7 ==> -53 (away from zero)), you must check if the initial value is negative: ``` ((int)(num + ((num > 0)? +0.5 : -0.5))) ```
Just learned that there is no pre-defined graphics library for C. I want to get the resolution of the current monitor screen.
That is simply not possible to answer as a "pure C" question; there is no "screen" in C, i.e. the language and its standard library never assumes that there is any kind of screen-like output device available. You need to settle for a suitable library for a portable solution, or figure out how to talk directly to your target environment.
How can I check if my program is running as an administrator on a Windows 7 system, using C? In batch I could do something along the lines of: ``` whoami /groups | findstr /b /c:"Mandatory Label\High Mandatory Level" | findstr /c:"Enabled group" > nul: && set IS_ELEVATED=1 if %IS_ELEVATED%==0 ( set /p _="You need to run Utilis as administrator, run with admin cmd. Press enter to exit.. ) ``` This will check if the current user is an administrator or not. How can I achieve the same concept in C?
I suggest that if you set the executable's properties and permissions, so that it canonlybe run by administrator, that could solve the problem.
In the following code from core_cm4.h why is there a double cast((uint32_t)(int32_t)IRQn)? For example in the following function: ``` __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } ``` What is the purpose of this?
Since CM4 software implements negative interrupt sources for core, you have to cast value first to 32bit signed integer and later to unsigned 32bit to make proper right shift with padding zeros on the left side of number. CM4 uses -15 to -1 as CM4-Core sources and from 0 to next as vendor specific sources.
I am using the ARMv8 instruction set with Aarch64 execution state. The problem I am having, is were supposed to translate C code into assembly, and I am stuck on the following: ``` while (c != '\n' && c != EOF) c = getchar(); ``` I know the basic setup for the while loop, as well as how to testc != '\n'but the issue I have is how to writeEOFin assembly. Can i just type ``` cmp c_r, EOF b.eq skipwhile ``` or is it something else?
It depends on what code you're using in assembly forgetchar()- If you're just using a call to the assembly version of standard C librarygetchar(), then you can test with the C library's definition ofEOF- normally-1.If you're implementing your owngetchar()in assembly, then you need to match your test to the return value of yourgetchar()implementation when it gets to the end-of-file.
If you fork() and create two processes for reading and writing to a pipe and the child process is reading from the pipe and the parent process is writing to the pipe, will writing in the parent process fail if the child process was to close the pipe that writes before the parent process has a chance to write to the pipe?
The child process closing its write end of the pipe only removes its reference to the pipe, it doesn't cause the pipe to "shut down" or any such thing, and thus won't affect the parent's reference to it in any way. This is true for theclose(2)call in general. Further reading: File descriptors
In C, I have a function that calculates the product of a and b. If a < b it returns false otherwise returns true. How can I return the product when the function is defined as boolean? ``` bool multiplication(int a, int b) { int c = a*b; if (a < b) return false; else return true; } ```
How to return bool and double simultaneously? A function can only have one return type. But you can use a workaround of using a struct containing a bool and an int members as stated in one of the comments. You can achieve your goal of writing a multiplication function of positive integers with a recursion logic the following way too: ``` int multiplication(int a, int b) { if(b <= 1) return a; return a + multiplication(a, --b); } ```
Here's what I've coded: ``` #include <stdio.h> void add(int *a, int i){ while(i != 0){ a++; i--; } } int main(){ int a = 6; add(&a, 4); printf("a = %d\n", a); return 0; } ``` And here's the result ``` a = 6 ``` The result I'm expecting is10, of course, but I don't understand whyaisn't modified when I pass it as a pointer in myaddfunction...
In the function there is advanced the pointer itself instead of incrementing the value pointed to by the pointer. Change the function the following way ``` void add(int *a, int i){ while(i != 0){ ( *a )++; i--; } } ``` Or the expression statement( *a )++;can be substituted for++*a; Also the function could be more safe if the second parameter had typeunsigned int. Otherwise you have to check the sign of the parameter.
I want to create a functionvoid vec2_from_vec3(vec2 res, vec3 from)in pure C, using operator##like so: ``` #define MAGIC_MACROS(n) \ void vec##(n-1)##_from_vec##n##(vec##(n-1) res, vec##n from); ``` but compiler woudn't let it. Is it possible? Inspired byhttps://github.com/datenwolf/linmath.h/blob/master/linmath.h
The preprocessor won't evaluate/computen-1, it will just expand it. Ex:3-1, so string concatenation won't work (a modern compiler does it but it's already too late) You can always do that which isn't that bad already: ``` #define MAGIC_MACROS(n1,n2) \ void vec##n1##_from_vec##n2##(vec##n1 res, vec##n2 from) ``` and use as: ``` MAGIC_MACROS(2,3); ``` Note that you shouldn't end your macros with;, so it's homogeneous with function calls and doesn't break editor auto-indentation.
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed6 years ago.Improve this question Specifically, what does the "-lm" mean, and is it required to include that? Is there a "dictionary" online that will explain all of these command abbreviations like "-lm"?
This is linking against themlibrary... Which is used for math functions. The-l<library name>parameter togccmeans 'link with this library'. Themis the library to link with (e.g:libm.soorlibm.a). See theGCC man page(runman gcc), and functions likesin(),sqrt(),pow(), etc. Note that in these man pages, it states: Link with -lm.
Is there a way to use a delim more then once for strtok? I can only get the code to work for either load or init but not both. Example code in which strtok is used to token input from the user in the form of load # or init #,#,direction: ``` if ((tok = strtok(choice, " ")) && strcmp(tok, COMMAND_LOAD) == 0){ tok = NULL; if((tok = strtok(tok, " ")) != NULL){ /*some code*/ } } else if((tok = strtok(choice, " ")) && strcmp(tok, COMMAND_INIT) == 0){ tok = NULL; if((tok = strtok(tok, ",")) != NULL){ /*some code*/ } } ```
Thestrtokfunction is not reentrant, you can not use it for multiple simultaneously tokenizations. Usestrtok_sinstead, if you have it. Orstrtok_ris you have it.
``` #define TERMMAX 100 typedef struct{ int coef; int expon; } poly; poly term[TERMMAX]; int avail = 0; #define TERMMAX 100 enter code here int main() { int i; FILE *fp = fopen("a.txt", "r"); while(fscanf(fp, "%d\t%d", &term[avail].coef, &term[avail].expon) != EOF) avail++; ``` the fscanf part above works just fine but the following fscanf doesn't. ``` while(fscanf(fp, "%d\t%d", &term[avail].coef, &term[avail++].expon) != EOF) ; ``` Nothing is stored in term[].expon. Why?
IIRC, the order of evaluation of function parameters is unspecified by the Standard. Any side effects of function parameters are indeterminately sequenced.
Here's what I've coded: ``` #include <stdio.h> void add(int *a, int i){ while(i != 0){ a++; i--; } } int main(){ int a = 6; add(&a, 4); printf("a = %d\n", a); return 0; } ``` And here's the result ``` a = 6 ``` The result I'm expecting is10, of course, but I don't understand whyaisn't modified when I pass it as a pointer in myaddfunction...
In the function there is advanced the pointer itself instead of incrementing the value pointed to by the pointer. Change the function the following way ``` void add(int *a, int i){ while(i != 0){ ( *a )++; i--; } } ``` Or the expression statement( *a )++;can be substituted for++*a; Also the function could be more safe if the second parameter had typeunsigned int. Otherwise you have to check the sign of the parameter.
I want to create a functionvoid vec2_from_vec3(vec2 res, vec3 from)in pure C, using operator##like so: ``` #define MAGIC_MACROS(n) \ void vec##(n-1)##_from_vec##n##(vec##(n-1) res, vec##n from); ``` but compiler woudn't let it. Is it possible? Inspired byhttps://github.com/datenwolf/linmath.h/blob/master/linmath.h
The preprocessor won't evaluate/computen-1, it will just expand it. Ex:3-1, so string concatenation won't work (a modern compiler does it but it's already too late) You can always do that which isn't that bad already: ``` #define MAGIC_MACROS(n1,n2) \ void vec##n1##_from_vec##n2##(vec##n1 res, vec##n2 from) ``` and use as: ``` MAGIC_MACROS(2,3); ``` Note that you shouldn't end your macros with;, so it's homogeneous with function calls and doesn't break editor auto-indentation.
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed6 years ago.Improve this question Specifically, what does the "-lm" mean, and is it required to include that? Is there a "dictionary" online that will explain all of these command abbreviations like "-lm"?
This is linking against themlibrary... Which is used for math functions. The-l<library name>parameter togccmeans 'link with this library'. Themis the library to link with (e.g:libm.soorlibm.a). See theGCC man page(runman gcc), and functions likesin(),sqrt(),pow(), etc. Note that in these man pages, it states: Link with -lm.
I see the standard only said that FILE is a object type, but what's the object type in c? built-in type, struct, union and emun? Is fuction type a kind of object type? Can FILE * cast to void * always correctly?
what's the object type in c? built-in type, struct, union and emun? yes, plus some other "intrinsic" types such asmtx_toratomic_flag Is function type a kind of object type? no, function types are different, they are those that are declared by designated function declarations. Functions can be called by using af(something)notation. For object types this is invalid. Can FILE * cast to void * always correctly? yes, pointer to object types (that are notconstorvolatile) can always be converted tovoid*and back without loosing anything.
I am trying to optimize following operation where I have a large number of unsigned short inputs which needs to be scaled down by a certain factor. Is there a way to optimize it to not use floating point operations ``` unsigned short val = 65523U; val = val * 0.943; ``` Note I will be running above operation on a DSP where floating point operations are costly
The simplest way is to just use a 32 bit type that can hold the result: ``` uint16_t val = 65523U; val = (uint_fast32_t)val * 943 / 1000; ``` Or if you want more type correctness and portability, while at the same time allowing the compiler to use the best possible integer type for the task: ``` #include <stdint.h> uint_fast16_t val = UINT16_C(65523); val = (uint_fast16_t) ( (uint_fast32_t)val * (uint_fast32_t)943 / (uint_fast32_t)1000 ); ```
So after looking on the massive interweb, I was unable to find an answer to this. Say I have this piece of code: ``` if(P4IN & GPIO_PIN1?0:1){ if (state==1){ state = 0; //Wait for this state to pass -- ends up saving the current state on button press. while (counter < 10000){ counter++; } } else{ state = 1; while (counter < 10000){ counter++; } } } ``` How would I rewrite this so thatif(P4IN & GPIO_PIN1?0:1)is not written like this. I do not mind creating extra if/else conditions or extending this block of code (intended for the MSP432) Thanks for your time.
You can simplify the whole thing to this: ``` if (!(P4IN & GPIO_PIN1)) { state = !state; while (counter < 10000) { counter++; } } ```
I am trying to allocate memory for an integer array ``` ptr=malloc(length*sizeof(int)); ``` which will give me the pointer to the allocated memory. I understand that I can access the values with *(ptr+k), where k is the position in the integer array. However is there a way to define a new array ``` int allocarray[length]; ``` and then assign allocarray the address ptr, so that I can access the stored values with ``` allocarray[k] ``` ? I tried the following which does not work: ``` allocarray=ptr; ``` Thank you for the help.
If you declare an array like you do above, it will be automatically allocated. However, if you say: ``` int *allocarray = (int *)malloc(length*sizeof(int)); ``` you can still access elementkusing the syntaxallocarray[k].
I am in a similar situation :Eclipse CPP and GNU following these instructions. But i need to build GLUS with MinGW and sublime text. I am learning C and OpenGL ,so i lack compilation/dependencies logic. I would just like to undertsand in a simple way. how to compile GLUS from those source:https://github.com/McNopper/OpenGL/tree/master/GLUS/srcWhere to install all the files in MinGW folder to setup things correctly. Glew and Glfw are already configure correctly and works fine. Thanks for your time.
Well Norbert Nopper kindly answer my question directly. And like the answer mention above. The path to follow to compile GLUS without any ide is by using cmake. in the GLUS folder, there is a CMake file (https://cmake.org/). With CMake, you can create the GLUS library without any IDE and for a lot of platforms – including Windows and MinGW.
``` int *ptr = malloc~ while (fscanf(fp, "%d", ptr++) != EOF) ; ``` Assuming that there's sufficient memory allocated to ptr, What does the value stored in *ptr when the function encouters EOF indicate? I tried using debugging tools in Visual Studio and found out that the value of *ptr is -33686019 Is this garbage value? or EOF?
When scanf hits EOF,no value is storedat the addressptrpoints to. Likewise if it returns 0. This is why the canonical way to iterate over input must check the scanf return value, e.g. with ``` if (fscanf(fp, "%d", &ptr_to_int) == 1) { /* successful conversion */ } else { /* Unsuccesful conversion or EOF; use feof() to test which. */ } ```
I have a sorted linked list, one function takes the root pointer and an Id and searches through the list to delete the item, however this takes linear time. Is there any way to efficiently search through the linked list without doing it linearly using the fact that its sorted? The assignment hints heavily that their is a better way but I can't think of a way to do it without being terribly inefficient or just using a linear search.
Each node in a linked list only contains a pointer to the next node (and optionally the previous node), so without any other constructs the only way to search the list is linearly. However, since you sort the list, you could build a binary tree in the process. Then you can use that tree to search the list with a time complexity ofO(log n)instead ofO(n).
I have currently got it as : ``` scanf("%d%d%d",&day1,&mon1,&year1); ``` This works fine when I pass in a date which is to be like : ``` 02-02-2016 ``` However I want it to also be fine if I pass it with slash instead of the dash : ``` 02/02/2016 ``` I have tried this way: ``` scanf("%d/%d/%d",&day1,&mon1,&year1); ``` Now this will accept the slash(/) but however does not support dash (-) How can it accept both ??? How would I go about doing that ? I am new to this language so some sort of advice would be great. Thanks in advance
You can use a format string like:"%d%*[-/]%d%*[-/]%d"to accept only dash or slash between the numbers, but throw away whatever character is there. (This is getting to the outer limits of myscanfknowledge; I don't think I've ever actually used this feature.)
When I run this code it gave a segmentation fault. ``` main () { char *line ="2,3,22"; int size=3,i,j; double value; char *val; for (i = 0; i<size ; i++) { if (line == NULL) break; printf("%s\n",strtok (line ,",")); } } ``` and gave a "warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=] printf("%s\n",strtok (line ,","));" So when I assignstrtokvalue to char* it gave an error. whystrtokreturn an int value? What is the solution?
It's using an implicit prototype forstrtok. You need to#include <string.h>(You might also need to includestddef.hforNULLand should also includestdio.hforprintf).
I have a sorted linked list, one function takes the root pointer and an Id and searches through the list to delete the item, however this takes linear time. Is there any way to efficiently search through the linked list without doing it linearly using the fact that its sorted? The assignment hints heavily that their is a better way but I can't think of a way to do it without being terribly inefficient or just using a linear search.
Each node in a linked list only contains a pointer to the next node (and optionally the previous node), so without any other constructs the only way to search the list is linearly. However, since you sort the list, you could build a binary tree in the process. Then you can use that tree to search the list with a time complexity ofO(log n)instead ofO(n).
I have currently got it as : ``` scanf("%d%d%d",&day1,&mon1,&year1); ``` This works fine when I pass in a date which is to be like : ``` 02-02-2016 ``` However I want it to also be fine if I pass it with slash instead of the dash : ``` 02/02/2016 ``` I have tried this way: ``` scanf("%d/%d/%d",&day1,&mon1,&year1); ``` Now this will accept the slash(/) but however does not support dash (-) How can it accept both ??? How would I go about doing that ? I am new to this language so some sort of advice would be great. Thanks in advance
You can use a format string like:"%d%*[-/]%d%*[-/]%d"to accept only dash or slash between the numbers, but throw away whatever character is there. (This is getting to the outer limits of myscanfknowledge; I don't think I've ever actually used this feature.)
When I run this code it gave a segmentation fault. ``` main () { char *line ="2,3,22"; int size=3,i,j; double value; char *val; for (i = 0; i<size ; i++) { if (line == NULL) break; printf("%s\n",strtok (line ,",")); } } ``` and gave a "warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=] printf("%s\n",strtok (line ,","));" So when I assignstrtokvalue to char* it gave an error. whystrtokreturn an int value? What is the solution?
It's using an implicit prototype forstrtok. You need to#include <string.h>(You might also need to includestddef.hforNULLand should also includestdio.hforprintf).
I have currently got it as : ``` scanf("%d%d%d",&day1,&mon1,&year1); ``` This works fine when I pass in a date which is to be like : ``` 02-02-2016 ``` However I want it to also be fine if I pass it with slash instead of the dash : ``` 02/02/2016 ``` I have tried this way: ``` scanf("%d/%d/%d",&day1,&mon1,&year1); ``` Now this will accept the slash(/) but however does not support dash (-) How can it accept both ??? How would I go about doing that ? I am new to this language so some sort of advice would be great. Thanks in advance
You can use a format string like:"%d%*[-/]%d%*[-/]%d"to accept only dash or slash between the numbers, but throw away whatever character is there. (This is getting to the outer limits of myscanfknowledge; I don't think I've ever actually used this feature.)
When I run this code it gave a segmentation fault. ``` main () { char *line ="2,3,22"; int size=3,i,j; double value; char *val; for (i = 0; i<size ; i++) { if (line == NULL) break; printf("%s\n",strtok (line ,",")); } } ``` and gave a "warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=] printf("%s\n",strtok (line ,","));" So when I assignstrtokvalue to char* it gave an error. whystrtokreturn an int value? What is the solution?
It's using an implicit prototype forstrtok. You need to#include <string.h>(You might also need to includestddef.hforNULLand should also includestdio.hforprintf).
I need help with how to generate random numbers between -1 and 1 using rand_r(). I didn't have much luck online looking for examples on how to do this. Any help would be greatly appreciated.
Each time you callrand_r, you pass it the address of a state variable. Before callingrand_rthe first time, this state variable should be assigned a seed value. You'll also need to keep a separate state variable for each thread so they each have their own state. ``` unsigned int myseed = time(NULL) ^ getpid() ^ pthread_self(); ... int rand1 = rand_r(&myseed); ... int rand2 = rand_r(&myseed); ``` To get a value between -1 and 1, first divide the given random value (cast to adouble) byRAND_MAX. This will give you a value between 0 and 1. You then multiply by the range of the numbers (i.e. 1 - (-1) = 2) and add the lower bound (-1): ``` double rand = ((double)rand_r(&myseed) / RAND_MAX) * 2 - 1; ```
This question already has answers here:Detecting and skipping line comments with Flex(3 answers)Closed6 years ago. I need a regular expression for inline comment in C for a compiler's lexical analyser. I tried thisScreenShotbut it is of no use as it comments out the regular expression. Here is simplest code
For catching C style comments better use start conditions. Example for flex you can findin documentation. There is simple example for ignoring C stype comments by using exclusive start condition: ``` %x comment "/*" BEGIN(comment); <comment>[^*\n]* /* eat anything that's not a '*' */ <comment>"*"+[^*/\n]* /* eat up '*'s not followed by '/'s */ <comment>"*"+"/" BEGIN(INITIAL); ```
I'm trying to do analysis on some data and I am building a few tools that I was hoping to chain together with pipes. cat file.dat | ./tool | ./tool2 ... But I'm not sure how to read the piped in data. I know it's coming in through stdin, but I can exactly wait for the file end. So I guess I'm looking for something like this: ``` long value; while(scanf("%ld\n",&value)){ value2 = do_something(value); printf("%ld\n",value2); } return 0; ``` But scanf, doesn't return 0 when stdin is "empty" what is the proper way to do this?
The functionscanfreturnsEOFwhen it reaches the end of file. You can use a code like this to check for that: ``` while (1) { long value; int ret = scanf("%ld\n", &value); if (ret == EOF) { break; } printf("%ld\n", value); } ``` See thedocsfor more details.
Does this mean anything: ``` typedef struct spBone spBone; struct spBone { ... } ``` I found the above in a header of a .c file. What could be the side-purpose of assigning anon-alternativename to a struct?
First, remember that C and C++ are different languages. C++ is rooted in C, but went in some very different directions. This is one of them. When declaring or defining a variable of typestructin C, one must always use the keywordstruct. For example ``` struct spBone myspBone; ``` is required. Why this is required likely made a lot of sense back in the 1970s. However, the programmer is establishingspBoneas an alias tostruct spBoneso that they can use the alias and ``` spBone myspBone; ``` as you can in C++.
Say we have a char array of size 40, ``` char buffer[40]; ``` Secondly, let's say that this array is completely full, that someone has written 40 characters to it. Thus, we could say that the elements of this array take up 40 bytes, as each char is 1 byte. My question is this: How much space does our arrayactuallytake up in memory? Will it take up 40 bytes of space, or more? Are extra bits needed to identify this array as of type char, and are extra bits needed to allow for null termination? If so, it could be that we need something more like ~42 bytes to store this array in memory. As such, I want to know if I can reliably fit an array of 40 chars in a memory space with 40 allocated bytes.
Unlike languages like Java or C#, C does not store any type meta information at runtime. Therefore,char[40]requires exactly 40 bytes.
I'm working on 8051 micro-controller platform with KEIL as IDE and C as the programming language. I'm trying to create array of bits for use in switch function. ``` sbit P1; sbit P2; sbit P3; buttons [2:0] = P1 | P2 | P3 switch (buttons[2:0]) { case 0x1: //First button is pressed case 0x2: //Second button is pressed case 0x4: //Third is pressed default: //Multiple buttons are pressed. Hence invalid } ``` I couldnot find a way to combine bits into a single entity and use it for switch function. Can anyone suggest way around to do the task in any possible method.
Finally i have found a way around to solve my problem. ``` int buttons=0x00; buttons = ((0xFF & !P1) << 2) | ((0xFF & !P2) << 1) | ((0xFF & !P3) << 0); ```
I have a random number generator feeding numbers into an array, but when I print out the table, the last line is always a set of values out of the boundaries that I defined in the following function: ``` #include <stdio.h> #include <stdlib.h> int main() { int temp[22]; int n; for(n=0; n<23; n++){ temp[n] = rand()%(100 + 1 - 60) + 60; printf("%d , %d \n", n, temp[n]); } return 0; ``` Ive created something of this nature before, but now its acting up, I just dont know where.
You are accessing the array outside the bounds which isundefined behaviour. Instead make use ofsizeofoperator to avoid such problems: ``` for(n = 0; n < sizeof temp/sizeof temp[0]; n++) ``` But note that iftempwere to be an malloc'ed pointer (int *temp = malloc(23 * sizeof *temp);) thensizeofwouldn't work.
The python script contains lots of libraries imported My C code so far: ``` #include <stdio.h> #include <python2.7/Python.h> void main(int argc, char *argv[]) { FILE* file; Py_SetProgramName(argv[0]); Py_Initialize(); PySys_SetArgv(argc, argv); file = fopen("analyze.py","r"); PyRun_SimpleFile(file, "analyze.py"); Py_Finalize(); return; } ``` Is there any other way that I can use so that even if any modification in arguments or number of python scripts I call inside c program increases the same code can be used with little changes? Can I use system call and use the result obtained from it?
One useful way is calling a python function within c, which is that you need instead of execute whole script. As described in>> here
The python script contains lots of libraries imported My C code so far: ``` #include <stdio.h> #include <python2.7/Python.h> void main(int argc, char *argv[]) { FILE* file; Py_SetProgramName(argv[0]); Py_Initialize(); PySys_SetArgv(argc, argv); file = fopen("analyze.py","r"); PyRun_SimpleFile(file, "analyze.py"); Py_Finalize(); return; } ``` Is there any other way that I can use so that even if any modification in arguments or number of python scripts I call inside c program increases the same code can be used with little changes? Can I use system call and use the result obtained from it?
One useful way is calling a python function within c, which is that you need instead of execute whole script. As described in>> here
I have a c executable which gets data from a iot hardware and print information on console using printf. I want to run this executable from python which I am able to do so using subprocess.call in following way ``` subprocess.call(["demoProgram", "poll"]) ``` and print the output to console. But I need to capture this output(printf) using my python code to process information further in real time. How can I capture this output using subprocess in real time?
The following opens a subprocess and creates an iterator from the output. ``` import subprocess import sys proc = subprocess.Popen(['ping','google.com'], stdout=subprocess.PIPE) for line in iter(proc.stdout.readline, ''): print(line) # process line-by-line ``` This solution was modified from the answer to asimilar question.
When summarized the chapter 2, the author mentioned that "Specifically, a 200-digit number is raised to a large power (usually another 200-digit number), with only the low 200 or so digits retained after each multiplication." Q:What is this mean? P.S:My English is a little bad.
If we replace 200 with 3, it would mean something like computing 123^456, but only retaining the low 3 digits (the ones, tens and hundreds places), mathematically equivalent to (123^456)%1000.
Insched.h, task_struct has following 2 fields: thread_group & thread_node. They keep the first element of their list but I could not find which type of variables they contain. ``` 1511 struct task_struct { .... 1657 /* PID/PID hash table linkage. */ 1658 struct pid_link pids[PIDTYPE_MAX]; 1659 struct list_head thread_group; 1660 struct list_head thread_node; .... } ```
thread_groupandthread_nodeare both intrusive linked-lists of all the threads in a thread group - they are use to link togethertask_structs, they don't "contain" anything. The difference between the two is thatthread_grouphas its head in thetask_structof the thread group leader, whereasthread_nodehas its head in thesignal_structshared by the thread group. In the medium-termthread_groupis going away.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed6 years ago.Improve this question I'm programming an OS. So I want to know how can an expression like (2*(7+8)-9)+2 can be initialised into variable using user defined function like extract() : ``` extract(char a[]) { //some code } char expr[] = "(2*(7+8)-9)+2"; int value = extract(expr); ``` I'm doing this for variable initialisation from string.( Any tips/ideas/suggestions? )
StackOverflow has already covered the topic of Infix expression parsing and Recursive Decent parsing using C++here. Read it over to understand the algorithm, then see if you can convert it to C. That will definitely be "fun" and teach you a little bit about C along the way.
``` #include<stdio.h> int main(){ int a = 320; char *ptr; ptr =( char*)&a; printf("%d",*ptr); return 0; } ``` I just wanted to know what is the use(char*)? What if I used(int*)instead of that?
Your variable is of type integer i.e.int a = 320;Your pointer is of type character i.e.char *ptr; character pointer can only points to character type variable, but you in your code want to point a integer variable so how would that be possible? By this line of code:ptr =( char*)&a;what it doing is type casting your pointer varble explicitly or forcefully (whatsoever you might want to call), by making it character type.
My GNU-Linux platform (debian stretch) has the C typesu_int8_t,u_int16_t,u_int32_tandu_int64_tdefined in the filesys/types.hwhileuint8_t,uint16_t,uint32_tanduint64_tare defined instdint.h. I have found these types useful in the course of practicing X86-64 assembly language and interacting with C. Is there any reason why I should prefer one header file over the other (be it 'best practice', portability etc.)?. Is the answer any different for C++?
stdint.his standard C, which maps tocstdintin standard C++. sys/types.his not portable C.
I know thatint *(*func)()means a function pointer which takes no arguments and returns an integer pointer but what does the following syntax means in C: ``` int *(*func())[] ``` Any explanations on how do we read such syntax in C would be very helpful.
funcis a function and returning a pointer to an array of pointers to int. reference link :http://gateoverflow.in/35193/regarding-pointers
Trying to figure out where I am going wrong in this code, I realize I keep getting 1 because that's what am I passing in the function but how else can I do this? ``` #include <stdio.h> #include <stdlib.h> int totalOdd(); int main(){ printf("%d\n",totalOdd(1)); } int totalOdd(int n){ int odd = n; if(odd >= 100){ return 0; } else{ totalOdd(odd+2); } return odd; } ```
try this one one : ``` #include <stdio.h> #include <stdlib.h> int totalOdd(int); int main(){ printf("%d\n",totalOdd(1)); } int totalOdd(int n) { int odd = n; if(odd > 100){ return 0; } else{ return (n+totalOdd(odd+2)); } } ``` in your code , addition was missing
``` unsigned short octet2, octet3, octet4; sscanf(ipAddr.c_str(), "%hu.%hu.%hu.%hu", &octet2, &octet2, &octet3, &octet4); ``` ipAddr is a string. From the above code, it is successfully breaking the octets up. However, I'd like to just avoid touching the first octet of the IP address. I want to avoid extra operations of writing into octet2 twice. For example, with the IP address 1.2.3.4, I'll break up the IP address into 2, then 3, then 4 without touching 1. My operations will be done over a million times, unless there is a better method than sscanf please let me know.
you could scan but not store the first argument by prefixing first format specifier by*to tellsscanfto parse but not store the field (and you only need 3 parameters in that case): ``` sscanf(ipAddr.c_str(), "%*hu.%hu.%hu.%hu", &octet2, &octet3, &octet4); ```
Simple question. I've been trying to find the answer before asking but i dont know if im wording the question right. I want to write in C usingwrite(int fd, char* buffer, size). ``` char buffer[40]; //just assume the buffer has been read into. write(fdout,buffer,40); ``` I want to write say starting at index 2 of the buffer so from buffer[2] to the end skipping the first 2 characters. To do this would I have to make another char* and concat the buffer excluding the first 2 characters?
You just need a pointer into the proper place in the buffer: ``` write(fdout, &buffer[2], 40-2); ```
I am programming in C using Atmel Studio (for those unfamiliar with this it is used to program to micro controllers such as arduino. You can not simply print, you have to send the data Serially to an application such as Terminal.) I have so far: ``` uint8_t * stackHolder; char buffer[128]; stackHolder = &buffer[127]; ``` Lets say that the address ofbuffer[127]happens to be0x207. I can see that the value ofstackHolderis0x207using the debugger. I have a function that takes achar *and prints that. So my question is how can I convert theuint8_t * stackHolderinto achar *so I can pass it to my print function?
How can I convert theuint8_t * stackHolderinto achar *? Bycasting: ``` print((char*) stackHolder); ```
I need the result of this variable in a program, but I don't understand why I can't get the right result. ``` double r = pow((3/2), 2) * 0.0001; printf("%f", r); ```
The problem is integer division, where the fractional part (remainder) is discardedTry: ``` double r = pow((3.0/2.0), 2) * 0.0001; ``` The first argument of thepow()expects a double. Because the ratio:3/2uses integer values, the result passed to the argument is 1. By changing to float values, the result of the division can retain the fractional part, and the result becomes 1.5, the form expected by the function.
In the following code,BITS_IN_INTis anlong unsigned intwith value32. Why does the modulo operation return the value0instead of the expected20? ``` #include <stdio.h> #include <stdlib.h> #include <limits.h> #define BITS_IN_INT sizeof(int) * CHAR_BIT int main() { size_t i = 20; printf("%zu\n", i); printf("%lu\n", BITS_IN_INT); printf("%lu\n", i % BITS_IN_INT); return 0; } ```
After macro expansion, the last printf looks like: ``` printf("%lu\n", i % sizeof(int) * 8); ``` So, the expression (in printf) is evaluated as if: ``` (i % sizeof(int)) * 8 ``` Ifsizeof(int)is 4 (which seems to the case on your platform) theni % sizeof(int)yields 0;0 * 8is0. Avoid macros if you can. If not, always use parentheses around your macros: ``` #define BITS_IN_INT (sizeof(int) * CHAR_BIT) ``` NB:%zuis the correct format specifier for printingsize_tvalues.
I'm trying to pass a struct to a callback set with curl_easy_setopt. Here's the struct: ``` typedef struct gfcontext_t { int sockfd; char requested_path[1024]; char path[1024]; } gfcontext_t; struct gfcontext_t ctx; ``` I've got these two lines setting up the callback: ``` curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ctx); ``` and the callback itself looks like this: ``` size_t write_callback(void *buffer, size_t size, size_t nmemb, void *userp) { printf("userp: %s\n", userp.requested_path); } ``` The machine says "request for member ‘requested_path’ in something not a structure or union." So I guess the struct (ctx) is not being passed correctly. Can anyone point me in the right direction?
userp is a pointer. You should type cast it togfcontext_t *. ``` printf("userp: %s\n", ((gfcontext_t *)userp)->requested_path); ```
I need to create a program that get's the sum of numbers from 100 to 500. ``` int sum = 0; for (int i = 1; i <10; i++) { sum = sum + i; printf("%d", sum); } ``` It should print 55 (the sum of numbers between 1 and 10), but it prints out 136101521283645. After this I need a program that gets the sum of numbers from 100 to 500.
Here you are only doing the sum for i from 1 to 9, and you print that sum every loop. Instead, you should do this: ``` int sum = 0; for (int i = 1; i <= 10; i++) { sum += i; } printf("%d", sum); ``` For 100 to 500, do that: ``` int sum = 0; for (int i = 100; i <= 500; i++) { sum += i; } printf("%d", sum); ```
I have a dynamic array of c-strings char **my_strings = (char**)malloc(50 * sizeof(char*)); and I want to find it's actual length (how many strings it actually contains). How can I do this?
You can't tell: it's your job to keep track of the size, or to use a magic value (NULL, say) to mark the final element. Note that the c runtime probably keeps track of the amount of memory allocated, but this is not exposed to you in any portable way.
When attempting to compile ``` #include<stdio.h> int main(){ printf("Hello World"); return 0; } ``` I get the following errors with Solaris11 gcc: hello.c:4:23: error: expected expression before ';' tokenhello.c:6:1: error: expected ';' before '}' token Visual C++ can compile this code.
the ';' in line four (thereturnstatement) is not a standard ';'.
I've already installed kernel-devel on centos, still cannot find kernel header ``` # yum install kernel-devel Loaded plugins: fastestmirror, ovl Setting up Install Process Loading mirror speeds from cached hostfile * base: mirrors....net * extras: ... * updates: mirrors.....net Package kernel-devel-2.6.32-642.15.1.el6.x86_64 already installed and latest version ``` But still the header files are not found by gcc: ``` # cat testkmem.c #include<sys/types.h> #include<sys/kmem.h> int main(){ return 0; } # gcc testkmem.c testkmem.c:2:21: error: sys/kmem.h: No such file or directory ``` How to solve this compilation issue, any extra yum packages that are needed?
Do you know locate command? ``` $ locate kmem.h /usr/src/kernels/3.10.0-514.10.2.el7.x86_64/include/config/memcg/kmem.h /usr/src/kernels/3.10.0-514.10.2.el7.x86_64/include/trace/events/kmem.h ``` :-), I think yourPATHhas error.
This is a homework assignment. I have a makefile that by default compiles an executable usinggcc -o myprogram myprogram.c In the assignment we are supposed to make 3 extra make cases: "The makefile should also support inserting a sleep of 10 seconds into 3 different specified places of the program using these 3 casesmake test1,make test2,make test3. I know how to use make to have extra cases like this from the default, but my question is can makefiles be used to insert code into myprogram.c before compiling the executable? Or would i have to create myprogram1.c myprogram2.c etc and then use those for the cases? Thank you!
A simple solution would be a macro that you can define at compile time, like ``` int main(void) { SLEEP_HERE; return 0; } ``` and at compile time ``` gcc -Wall -Werror -DSLEEP_HERE='sleep(10)' -o myprogram myprogram.c ```
``` #include <stdio.h> struct bar { int data[10]; }; int main(void) { printf("%d", ((struct bar*)0)+5); return 0; } ``` Output is 200. I came across this on some c programming website. Can someone explain me this?
Edit:I am updating based on the comment section. We understand that arithmetic onnull pointeris undefined behavior. You can read morehere. The current code does not specifically useNULL. Instead it uses literal0which is then casted intonull pointerwith((struct bar*)0). As a result, in this code we have an undefined behavior, as well. If instead of0, we had another literal (say1), then whether it produces a value (201in case of using1) or causes an error would be implementation-dependent. This output (200) comes from here:sizeof(struct bar)is 40 bytes and a pointer arithmetic is carried out (5 x 40 = 200).
``` #include<stdio.h> int main() { int n=3; while(n>0) { printf("P"); n--; sleep(1); } return 0; } ``` With this code 3 P's are appearing at the same time after 3 seconds. But I want it to appear one by one with 1 second time interval. How should I modify it?
The problem is the buffer is not flushed byprintf. To do so, you can either print '\n' after your P :printf("P\n"); Either call fflush on stdout : ``` printf("P"); fflush(stdout); ```
I have this code: (assuming short ints are 16 bits wide, and ints are 32 bits wide) ``` short int x = -5; int y; y = x; ``` Does padding on the left with the sign bit to increase precision change the value of a negative number?
Does padding (sign-extension) on the left with the sign bit to increase precision change the value of a negative number? Taking into acount@Amin Negm-Awad, when a variable is assigned from one type to another,andthevalueis representable in both types, like -5 as inintorshort, there is novaluenor precision change. This applies if a type isint,short,char,float, etc. It also applies if integer types are 2's complement or not. The size of the type makes no difference. Endian makes no difference, Thevalueis preserved.
I was wondering about the "? :" operators in C. Can one use the conditional operator inside another conditional operator like this? ``` int a = 0; a == 1?a += 1:a == 0?a += 2:a = 3; ``` This is a very bad example, but I hope you understand what I'm trying to ask.
Of course you can, like this : ``` int a = 0; a == 1?(a += 1):((a == 0)?(a += 2):(a = 3)); ``` It is the same as writing : ``` int a = 0; if (a == 1) a += 1; else if (a == 0) a += 2; else a = 3; ``` which is much more clear to read and understand.
I'm implementing some form of internal profiler. Is there a way to know when and for how long a thread is context switched out? I know windows has it w the event tracing api and I know perf logs how many context switches happens. Is there a way to do it on linux? Needing root privileges is not an issue since it will be an internal tool.
Sort of. Seehttp://man7.org/linux/man-pages/man2/getrusage.2.htmlabout thegetrusage()function. Notice that the structure it returns has voluntary and involuntary context switch numbers. Also, you have user and system time. Other APIs return wall-clock time. Any wall-clock time greater than your user and system time is time you weren't running. Other than that, you could probably use the kernel ftrace ability. Seehttps://www.kernel.org/doc/Documentation/trace/ftrace.txt Readhttp://www.brendangregg.com/blog/2015-07-08/choosing-a-linux-tracer.htmlfor even more options.
I'm starting coding in C and I was doing an exercise, but saw a miscalculation testing this code: ``` int main(){ int number; int square; printf("Pick a number: "); scanf("%d",&number); while(number<=0) { printf("ERROR: The number MUST be greater than zero\nPick a number greater than zero: "); scanf("%d",&number); } square = pow(number,2); printf("\nThe square of the number is: %d\n\n",square); system("pause"); return 0;} ``` now... everything works just fine, but when I use the number "5", it shows the result "24", when it should be "25". anyone knows why this happen?
powtakesdoublearguments and returns adouble. So you're getting a rounding error.
This question already has answers here:Number at f(93) in fibonacci series has negative value, how?(3 answers)Closed6 years ago. I don't know why am I getting the last number as negative. I want to get the output as 0 1 1 ... 'n' numbers (fibonacci series) ``` #include<stdio.h> int main() { int n; scanf("%d",&n); int a=-1,b=1,c=0; for(int i=0;i<n;i++) { c=a+b; printf("%d",c); a=b; b=c; } return 0; } ```
Yes, it is definitely out of int range ``` 1836311903 //before last -1323752223 //last ``` the max int is 2,147,483,647 If you want more than n=48, you must declare a,b,c as long type ``` #include<stdio.h> int main() { int n; scanf("%d",&n); long a=-1,b=1,c=0; for(int i=0;i<n;i++) { c=a+b; printf("%ld\n",c); a=b; b=c; } return 0; } ```
I am going through my revision material and can't understand the following: I have a compiled CmyCProgramprogram which prints out its input in the form of text. So if it were called in bash by./myCProgram input.txtandinput.txtcontained"this is a test"the program would output on stdout"this is a test". I have a range of potential bash program calls to test and I pass all but one, it is of the following ``` ./myCProgram file.txt < input.txt ``` It is is decribed as: Your program takes a file as a single command line argument and then expect input on stdin. Can anyone explain to me what is going on here and suggest how I should handle it within my code?
This redirects the content of input.txt to your program via stdin. This does the same as: ``` ./myCProgram file.txt ``` and then typing in the contents of input.txt
I was wondering about the "? :" operators in C. Can one use the conditional operator inside another conditional operator like this? ``` int a = 0; a == 1?a += 1:a == 0?a += 2:a = 3; ``` This is a very bad example, but I hope you understand what I'm trying to ask.
Of course you can, like this : ``` int a = 0; a == 1?(a += 1):((a == 0)?(a += 2):(a = 3)); ``` It is the same as writing : ``` int a = 0; if (a == 1) a += 1; else if (a == 0) a += 2; else a = 3; ``` which is much more clear to read and understand.
I'm implementing some form of internal profiler. Is there a way to know when and for how long a thread is context switched out? I know windows has it w the event tracing api and I know perf logs how many context switches happens. Is there a way to do it on linux? Needing root privileges is not an issue since it will be an internal tool.
Sort of. Seehttp://man7.org/linux/man-pages/man2/getrusage.2.htmlabout thegetrusage()function. Notice that the structure it returns has voluntary and involuntary context switch numbers. Also, you have user and system time. Other APIs return wall-clock time. Any wall-clock time greater than your user and system time is time you weren't running. Other than that, you could probably use the kernel ftrace ability. Seehttps://www.kernel.org/doc/Documentation/trace/ftrace.txt Readhttp://www.brendangregg.com/blog/2015-07-08/choosing-a-linux-tracer.htmlfor even more options.
I'm starting coding in C and I was doing an exercise, but saw a miscalculation testing this code: ``` int main(){ int number; int square; printf("Pick a number: "); scanf("%d",&number); while(number<=0) { printf("ERROR: The number MUST be greater than zero\nPick a number greater than zero: "); scanf("%d",&number); } square = pow(number,2); printf("\nThe square of the number is: %d\n\n",square); system("pause"); return 0;} ``` now... everything works just fine, but when I use the number "5", it shows the result "24", when it should be "25". anyone knows why this happen?
powtakesdoublearguments and returns adouble. So you're getting a rounding error.
This question already has answers here:Number at f(93) in fibonacci series has negative value, how?(3 answers)Closed6 years ago. I don't know why am I getting the last number as negative. I want to get the output as 0 1 1 ... 'n' numbers (fibonacci series) ``` #include<stdio.h> int main() { int n; scanf("%d",&n); int a=-1,b=1,c=0; for(int i=0;i<n;i++) { c=a+b; printf("%d",c); a=b; b=c; } return 0; } ```
Yes, it is definitely out of int range ``` 1836311903 //before last -1323752223 //last ``` the max int is 2,147,483,647 If you want more than n=48, you must declare a,b,c as long type ``` #include<stdio.h> int main() { int n; scanf("%d",&n); long a=-1,b=1,c=0; for(int i=0;i<n;i++) { c=a+b; printf("%ld\n",c); a=b; b=c; } return 0; } ```
I am going through my revision material and can't understand the following: I have a compiled CmyCProgramprogram which prints out its input in the form of text. So if it were called in bash by./myCProgram input.txtandinput.txtcontained"this is a test"the program would output on stdout"this is a test". I have a range of potential bash program calls to test and I pass all but one, it is of the following ``` ./myCProgram file.txt < input.txt ``` It is is decribed as: Your program takes a file as a single command line argument and then expect input on stdin. Can anyone explain to me what is going on here and suggest how I should handle it within my code?
This redirects the content of input.txt to your program via stdin. This does the same as: ``` ./myCProgram file.txt ``` and then typing in the contents of input.txt
I have a string input that goes like this string@floatValue A set of values in this format is being passed as an input to the program. I am trying to read them usingscanf()but to no avail. Some of the formats that I have tried are scanf("%[^@]s%f",&s,&f); scanf("%s@%f",&s,&f); scanf("%s[@]%f",&s,&f); No matter what I give the whole value (the string with the @ symbol and the float value) is being stored in the s itself. In a previous post I saw someone using this%4[^\n]which can be used to read 4 inputs or until a new line is encountered. Unfortunately the input size is not known to me. I tried a workaround usinggetchar()function. In that too after reaching '@' symbol I am usingscanf("%f",&f)to read the input, which is throwing me segmentation error. How can I solve this?
Remove an&befores, this should work: ``` scanf("%[^@]@%f",s,&f); ```
I did some experiment, pulling my hair out to figure the solution, please help! ``` #include <stdio.h> int main() { int USD , JPY; int lower,upper,skip; lower = 1; upper = 1000; skip = 50; USD = lower; while (USD <= upper) { JPY = USD * 114; printf("%d\t\%d\n", USD, JPY); USD = USD + skip; } } ``` Results : ``` 1 114 51 5814 101 11514 151 17214 etc ``` My expected result is below : ``` 1 114 50 5700 ----> incremented by 49 100 11400 -----> incremented by 50 150 17100 -----> incremented by 50 and same with the rest, all incremented by 50 ```
Try ``` USD = USD + skip - (USD == 1); ``` This works whenloweris 1. If you want to make it general for everyloweryou need, as pointed by @EOF ``` USD = USD + skip - (USD == lower ? lower : 0); ```
Statement: "array of N pointers to functions, returning pointers to functions and returning pointer to integer" Can anyone help me with understanding the function prototype for above statement ? Given answer-int *(*(*a[N])()) (); Please can anyone explain me how we arrive at the above answer ?
``` *a[N] ``` is the array of N pointers, calling it x ``` *(x)() ``` returning function pointer, calling it y ``` int *(y) () ``` is function pointer returning integer
I am writing a C code, this code consist with many sub functions and also within a sub function there is another sub function after execution of this sub sub function I need to go back in the beginning of main function. My question is how can I exit from this function and come back main function? As this code is too big That is why I have not include this code in here.I thinkreturn;cant do this thing because it returns only to the function where it got function call. I am beginner in C programming so please suggest what thing I have to do for this?
THIS ANSWER NEEDS A HEALTH HAZARD - THIS IS THE WRONG WAY TO PROGRAM You can usesetjmpandlongjmpto do this. ButPLEASEdo everything in your power to avoid this - by thinking about the design of the code beforehand
I did some experiment, pulling my hair out to figure the solution, please help! ``` #include <stdio.h> int main() { int USD , JPY; int lower,upper,skip; lower = 1; upper = 1000; skip = 50; USD = lower; while (USD <= upper) { JPY = USD * 114; printf("%d\t\%d\n", USD, JPY); USD = USD + skip; } } ``` Results : ``` 1 114 51 5814 101 11514 151 17214 etc ``` My expected result is below : ``` 1 114 50 5700 ----> incremented by 49 100 11400 -----> incremented by 50 150 17100 -----> incremented by 50 and same with the rest, all incremented by 50 ```
Try ``` USD = USD + skip - (USD == 1); ``` This works whenloweris 1. If you want to make it general for everyloweryou need, as pointed by @EOF ``` USD = USD + skip - (USD == lower ? lower : 0); ```
Statement: "array of N pointers to functions, returning pointers to functions and returning pointer to integer" Can anyone help me with understanding the function prototype for above statement ? Given answer-int *(*(*a[N])()) (); Please can anyone explain me how we arrive at the above answer ?
``` *a[N] ``` is the array of N pointers, calling it x ``` *(x)() ``` returning function pointer, calling it y ``` int *(y) () ``` is function pointer returning integer
I am writing a C code, this code consist with many sub functions and also within a sub function there is another sub function after execution of this sub sub function I need to go back in the beginning of main function. My question is how can I exit from this function and come back main function? As this code is too big That is why I have not include this code in here.I thinkreturn;cant do this thing because it returns only to the function where it got function call. I am beginner in C programming so please suggest what thing I have to do for this?
THIS ANSWER NEEDS A HEALTH HAZARD - THIS IS THE WRONG WAY TO PROGRAM You can usesetjmpandlongjmpto do this. ButPLEASEdo everything in your power to avoid this - by thinking about the design of the code beforehand
``` #include<stdio.h> int main( ) { char ch = '1' ; printf ( "\n%d %c\n", ch, ch ) ; return 0; } #include<stdio.h> int main( ) { char ch = 1 ; printf ( "\n%d %c\n", ch, ch ) ; return 0; } ``` What is the difference between these two declarations of char?? Which one is correct??
The first piece of code assigns the character'1', which has an ASCII value of 49. Printing this as a character will yield1, while printing as a number will yield49. The second piece of code assigns the value 1. Printing it as a character yields an unprintable character with an implementation defined representation, while printing it as a number will yield1. As for which is "correct", that depends on how you want to use it.
Is a 'for loop' a function? If not, what is it? How it works? Example in C: ``` for(int i=0; i<32; i++) { ... } ``` Example in Python: ``` for i in range(0, 32): print "..." ```
No, the wholethingis called "iteration statement". The one which includes theforkeyword is calledforstatement. QuotingC11, chapter 6.8, Astatementspecifies an action to be performed. [...] and from §6.8.5 iteration-statement:while ( expression ) statement do statement while ( expression ) ; for ( expressionopt ; expressionopt ; expressionopt ) statement for ( declaration expressionopt ; expressionopt ) statement
I am using GDB Machine interface to debug binary file which read from stdin and write to sdtout. I would like redirect both stdin and stdout to files. With plain GDB i can use run command like this: ``` run < input.txt > output.txt ``` Is there any way to maybe use GDB/MI command -exec-run similarly to this? Here is similar questionGDB/MI detecting target waiting for inputbut it seems so complex compared to plain gdb solution. I also have not found anything in docs:ftp://ftp.gnu.org/old-gnu/Manuals/gdb/html_chapter/gdb_22.html#SEC216
You should be able to use the mi command-inferior-tty-setalong with the mkfifo utility.
My function isvoid x(int *y); I want to call it likex(&6);orx({6});, I do not want to define an integer and assign 6 to it, I want single line.
What you need iscompound literals ``` #include <stdio.h> void x(const int *y) { printf("%d\n", *y); } int main(void) { x(&(int){6}); return 0; } ```
What does the standard (are there differences in the standards?) say about assigning a float number out of the range of an integer to this integer? So what should happen here, assuming 16 bit short, to keep the number small(USHRT_MAX == 65535) ``` float f = 100000.0f; short s = f; s = (short) f; unsigned short us = f; us = (unsigned short) f; ```
This is undefined behaviour (with no diagnostic required). See C11 6.3.1.4 (earlier standards had similar text): When a finite value of real floating type is converted to an integer type other than_Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined. So, assuming your system hasUSHRT_MAXas65535,short s = f;and all subsequent lines cause undefined behaviour.
Let's say we have a c program as follow: ``` int fun(char *path) { FILE *f = fopen(path, "r"); int result; // Do something here without closing the file return result; } int main(int argc, char *argv[]) { int i = fun(argv[1]); printf("%d\n", i); return 0; } ``` I know that it is not a good habit to not close a file. But I wonder when will be file be closed by the OS. Whenfunreturns or whenmainreturns? How about when the program is killed?
It'smain. File handles are allocated to the process, not any given function. Think of what would happen if you declaredfas a global variable. Any process termination will close files and free any other system resources associated to the process.
In this code oncefis assigned some value ofi, for example from inside the loop after 3 iterationsf=i=2, then next timefcannot be assigned the value again: the value offhas to be rock solid to first assignment only. ``` for(i=0;i<N-1;i++) { if(array[i+1]>array[i]); else if(array[i+1]<array[i]) { f=i;s=i+1;} else {f=i; s=i+1;} } ``` Oncefis initialized to one value ofiit should not change. Is there any operator in C which helps? I thought ofstaticbut it's absolutely the wrong choice.
You could setfequal to some placeholder value initially. Then, check for this placeholder and only make an assignment once: ``` int f = -1; for (i=0; i < N-1; i++) { if (array[i+1] > array[i]); else if (array[i+1] < array[i]) { if (f == -1) f = i; s = i+1; } else { if (f == -1) f = i; s = i+1; } } ```
How do I check if the system on which my program is running on is an arm based or not using c/c++?
Here's what you are looking for, ``` #include <stdio.h> #include <windows.h> int main(void) { SYSTEM_INFO SystemInfo; GetSystemInfo(&SystemInfo); if(SystemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_ARM) { // System's processor is ARM based } return 0; } ``` Edit: As Anders suggested, useGetNativeSystemInfofor better and accurate results.
What is the correct order for the following structures? It's throwing field has an incomplete type error. ``` #include <stdlib.h> struct nl_msg { int nm_protocol; int nm_flags; struct ucred nm_creds; struct nlmsghdr * nm_nlh; size_t nm_size; int nm_refcnt; }; struct nl_msg; struct nl_tree; struct ucred; int main() { return 0; } ```
In your code (rather, translation unit.), there's nowherestruct ucredis defined. You need to define_GNU_SOURCEMACRO and includesys/socket.hheader which defines this structure. See this online.
I always hear that you should never usesystem()and insteadfork/execbecause system() blocks the parent process. If so, am I doing something wrong by callingwaitpid(), which also blocks the parent process when I do afork/exec? Is there a way around callingwaitpid...I always thought it was necessary when doing afork/exec. ``` pid_t pid = fork(); if (pid == -1) { // failed to fork } else if (pid > 0) { int status; waitpid(pid, &status, 0); } else { execve(...); } ```
TheWNOHANGflag (set in the options argument) will make the call towaitpid()non-blocking. You'll have to call it periodically to check if the child is finished yet. Or you could setupSIGCHLDto take care of the children.
I'm using posix threads and have a workerRoutine that in some cases has to wait for I/O. ``` //WorkerRoutine while(true){ if(NO CURRENT WORK){ //sleep for I/O continue; } //Other cases.... } ``` My I/O function updates a statically-sized list. My problem is, when there's no current work for a worker, there's busy waiting. I'd like to have a sleep function in the worker function and a wake function in my readList (the I/O) function. What's the best way to do this in C?
The closest pthreads equivalent of Java'swaitandnotifymethods are available as functions acceptingcondition variables. Set up a condition variable, callpthread_cond_waitto wait for work, andpthread_cond_signalto announce that work is available. Usage examples can be easily foundon StackOverflow.andelsewhere. If you are waiting for IO, another possibility is to usepollor equivalent to sleep until data arrives.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed6 years ago.Improve this question How can I rotate an image by 90 degrees (right and left) a one-dimensional array n-elements? My array is 24-bits bitmap (NxN) For example, my array ``` A[16] = { 1,2,3,4 5,6,7,8 9,10,11,12 13,14,15,16} ``` rotate to new array: ``` {4,8,12,16 3,7,11,15 2,6,10,14 1,5,9,13} ``` and to: ``` {13,9,5,1, 14,10,6,2, 15,11,7,3, 16,12,8,4} ```
You can use therotation matrix. The rotation matrix for 90 degrees is simply ``` [0 -1 1 0] ``` hereyou can see how to do matrix multiplication in c if you need.
I'm developping an easy game written in C (Visual C++) and I want to know if there is a way to play sounds, thanks (I'm using Visual Studio)
Take a look at thePlaySound()function. If you callPlaySound()with theSND_ASYNCflag, the function returns immediately after beginning the sound. For example: ``` #include <windows.h> #include <mmsystem.h> PlaySound(L"test.wav", NULL, SND_ASYNC | SND_FILENAME); ``` You'll also have to addWinmm.libin your project settings. Here's a quick example that should work: ``` #pragma once #include "stdafx.h" #include <windows.h> #include <mmsystem.h> int _tmain(int argc, _TCHAR* argv[]) { if(!PlaySound(L"test.wav", NULL, SND_ASYNC | SND_FILENAME)) printf("error\n"); else printf("ok\n"); getch(); return 0; } ``` and in stdafx.h: ``` #pragma once #include <iostream> #include <tchar.h> #include <conio.h> ```
I'm new to OpenGL programming. I installed Ubuntu 64bit OS and installed all required libraries. But today when compiling I got stuck with an error for which I'm unable to find a solution When I compiled my program with this command: ``` cc aa.c -lglut -lGLU -lGL ``` the following error appeared ``` /urs/bin/ld: /tmp/ccCVosZx.o: undefined refrence to symbol 'cos@@GLIBC_2.2.5' //lib/x86_64-linux-gnu/libm.so.6: error adding symbols: DSO missing from command line ```
Looks like you need to link to the math library explicitly with-lm.
This question already has an answer here:Pointer to a specific fixed address(1 answer)Closed6 years ago. A bit of a silly question but here it is - how do I get a value based on its address? Usually to get the address for a certain value I just print it out like this: ``` printf("%p", &loc); ``` But now I need to get a value based on its address in memory. How do I do that?
The standard way of accessing a particular address 0x12345678 (such as a hardware register) is: ``` (volatile uint32_t*)0x12345678 ``` If you want to use the contents of that address as if it was a variable, you could either have a pointer point there, or make a macro: ``` #define REGISTER ( *(volatile uint32_t*)0x12345678 ) ```
I want to remove warning without change data-type to char. ``` #include<stdio.h> #include<stdlib.h> main() { unsigned char ch; printf("Hello This is Problematic\n"); scanf("%d",&ch); printf("1\n"); } ``` This generates the warning test.c:7:2: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘unsigned char *’ [-Wformat=] scanf("%d",&ch);
Actually, ``` scanf("%d",&ch); ``` leaves your program withundefined behavioras the supplied argument is not the correct type for the conversion specifier. You need to write ``` scanf("%hhu",&ch); ``` QuotingC11, chapter §7.21.6.2 hhSpecifies that a followingd,i,o,u,x,X, ornconversion specifier applies to an argument with type pointer tosigned charorunsigned char.