question
stringlengths
25
894
answer
stringlengths
4
863
For the moment, my C codebases compile relatively quickly. However, I would like to utilise aninformedapproach to reducing the number of times a given header is re-processed. I guess that being able to see reference counts would help me to do so. How would I do that?
Both CLang and GCC support the-Hoption. It will dump into the console each header file included. Then, you can easily read these lines and analyze them to detect compiler bottlenecks. Fromman gcc: -HPrint the name of each header file used, in addition to other normal activities. Each name is indented to show how deep in the#includestack it is.Precompiled header files are also printed, even if they are found to be invalid; an invalid precompiled header file is printed with...xand a valid one with...!.
I want to set the last three bit of a byte to a specific vaue. What’s the best way to archive this goal? I can think of at least two solutions… Let’s assume I have the following Byte: 1101 0110 and want to set the three last bits to 011. Solution 1: ``` 1101 0110 &1111 1000 //and with mask to clear last three bits |0000 0011 //add the target bits ``` Solution 2: ``` 1101 0110 >> 3 //shift right to remove last three 0001 1010 << 3 //shift left to clear last three |0000 0011 //add target bits ``` Is there a better/shorter/more efficient way?
The best way is to say ``` b = (b & ~7u) | 3 ``` because3=0...011and7u=0..111in binary, and the complement of7uis~7u=11...1000, so the operation does what you want. It first clears the last three bits (by doingb & ~7u) and then sets the first and the second bits (by doing bitwise-OR with3).
I am trying to print smiley face using C. My program is ``` #include <stdio.h> int main() { int x; char i=1; for(x=1;x<=800;x++) { printf(" %c ", i); if(x==800) printf("\n"); if(x==800) break; } } ``` I am using Ubuntu Terminal. It is working fine inWindowsbut not inUbuntu. Please help. Thanks in advance
If you want to output a smiley face you cannot use the ascii characters. Again, look at that ascii manpagefor the complete set of available characters. However you can use theUTF-8encoding, if your terminal support it. The code snippet below print a smiley face with sunglasses on my terminal: ``` #include <stdio.h> int main() { char s[] = { 0xf0, 0x9f, 0x98, 0x8e, 0}; printf("%s\n", s); } ``` Another possibility is to use ``` printf("\u263A\n"); ``` According to hisUTF-8page which report theC/C++/Javasource code
I am trying to set RTC time onSTM32L051T6microcontroller usingepochtime. So following is my code. ``` void Rtc_SetTime(uint32_t time_) { struct tm* brokenTime; const time_t temp = 3600; brokenTime = gmtime(&temp); if (NULL == brokenTime) { printf("Error: Failed to convert time.\r\n"); } } ``` When I call above function. It always goes toifstatement and prints Error. I have tried passing values 3600, 1459841178 as arguments. All fails. What is wrong with the code?
I found the following here:http://support.raisonance.com/content/gmtime-and-localtime-broken-arm-gcc-lib So it might not be implemented.... I think gmtime and localtime is broken in arm-gcc lib for STM32F10x.I have try it in keil uVision and working fine there(localtime anyway, gmtime not implemented in keil). gmtime and localtime is searching for _sbrk when linking."sbrkr.c: (.text+0xc): undefined reference to `_sbrk'"
Is there a way to performcompile-time function executionin C? With GCC? I've only seen this available usingconstexpr in C++.
As long as there are only constants involved in an expression, it will get calculated at compile-time. C++constexpris mostly a type safe way of doing so without involving macros. In C, there are only macros. For example: ``` #define CIRCLE_AREA(r) (int32_t)( (double)(r) * (double)(r) * M_PI ) int32_t area = CIRCLE_AREA(5); ``` performs all calculations at compile-time, so it is equivalent to writing: ``` int32_t area = 78; ```
Arrays in c are always passed by reference and printf is a call by value function then why do we pass array to printf function for printing a string?
First,arrays are not passed by reference in C. Theydecayto a pointer, which is passedby valueto the function.There is nopass by referencein C. It can only be emulated withpass by value. We don't really pass arrays toprintf: it's the aforementioned pointers we obtain through an implicit conversion (decay). This pointer can just as well be dereferenced to access the content of the array, so passing an array "by value" is not needed at all.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question Question about pointers. I know in the declarationint* pn = &n,pnis initialized as a pointer to the memory address ofn. However, why can we not just sayint pn = &n? If we wrote it like that, wouldn't that be the same thing as setting the variablepnto the memory location ofn? I do not exactly understand why the*is necessary.
I do not exactly understand why the * is necessary. To differentiate between a pointer and an integer probably, because they also have different meaning and functionality.
How do I self-terminate pthread execution? I have this code ``` while(1) { if(...) { terminate } work(); } ``` I have to usepthread_exit();but what do I give as parameter?
According to the manuals Thepthread_exit()function terminates the calling thread and returns a value viaretvalthat (if the thread is joinable) is available to another thread in the same process that callspthread_join(3). This is any value you want to provide to the joining thread. If you do not need a return value, you can passNULL.
Arrays in c are always passed by reference and printf is a call by value function then why do we pass array to printf function for printing a string?
First,arrays are not passed by reference in C. Theydecayto a pointer, which is passedby valueto the function.There is nopass by referencein C. It can only be emulated withpass by value. We don't really pass arrays toprintf: it's the aforementioned pointers we obtain through an implicit conversion (decay). This pointer can just as well be dereferenced to access the content of the array, so passing an array "by value" is not needed at all.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question Question about pointers. I know in the declarationint* pn = &n,pnis initialized as a pointer to the memory address ofn. However, why can we not just sayint pn = &n? If we wrote it like that, wouldn't that be the same thing as setting the variablepnto the memory location ofn? I do not exactly understand why the*is necessary.
I do not exactly understand why the * is necessary. To differentiate between a pointer and an integer probably, because they also have different meaning and functionality.
How do I self-terminate pthread execution? I have this code ``` while(1) { if(...) { terminate } work(); } ``` I have to usepthread_exit();but what do I give as parameter?
According to the manuals Thepthread_exit()function terminates the calling thread and returns a value viaretvalthat (if the thread is joinable) is available to another thread in the same process that callspthread_join(3). This is any value you want to provide to the joining thread. If you do not need a return value, you can passNULL.
Pointers can only move in discrete steps. ``` int *p; p = malloc(sizeof(int)*8); ``` Therefore, formally *(p+2) is calculated as *(p+2*sizeof(int)). However If I actually code the above two, I get different results, which seems understandable. ``` *p = 123; *(p+2) = 456; printf("%d\n",*(p+2*(sizeof(int)))); \\0 printf("%d\n",*(p+2)); \\456 ``` The question is, is this calculation implicit, done by the compiler at compile time?
The question is, is this calculation implicit, done by the compiler at compile time? Yes this is implicit, when you writeptr+nit actually advances forward n times as many bytes as size of pointee type (e.g. in case ofint*- this is 4 bytes granted integer takes four bytes on your computer). e.g. ``` int *x = malloc(4 * sizeof(int)); // say x points at 0x1000 x++; // x now points at 0x1004 if size of int is 4 ``` You can read more on pointer arithmetic.
I made a typo that looks like: ``` printf("blah-blah %d %d %d",fancy_func()),1,2; ``` I expected to get an error but for some reasons got a warning 'expression result unused' regarding '1,2' part. (Ignore missing arguments) Also this code doesn't give any errors: ``` int x,y,z; x,y,z; // OR 1,2,3; ``` This doesn't look like constant or array defination. Could someone explain why1,2,3;orx,y,z;is a valid code and what it does?
C has acomma operatorwhich makes your examples syntactically legal.
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.Closed7 years ago.Improve this question Is there a significant difference between these two methods for pointer assignment?*pp = varandpp = &var
Yes, there is asignificantdifference: *pp = var;assigns the objectpppoints to with the value ofvar.pp = &var;assignsppwith the address ofvar, making it a pointer to variablevar.
I was followingthis exercise. This page has instructions to install Valgrind 3.6.1 but this version of Valgrind is not supported by my current Linux kernel version. So, I installed Valgrind 3.11.0 and followed the instructions there after and on running this command: ``` $ valgrind ./ex4 ``` got this error: ``` valgrind: mmap(0x600000, 8192) failed in UME with error 12 (Cannot allocate memory). ``` How to do I fix it? I'm using Ubuntu 14.04 LTS with kernel version 4.4.0
The error which you have encountered is actually a kernel bug, which was fixed in the subsequent versions. More details here:https://bugzilla.redhat.com/show_bug.cgi?id=1301093 To overcome the error, I would suggest you to update the kernel.Note: I am myself using running Ubuntu 14.04 on kernel version 3.16.0-67 and it runs without any hassles. Edit: As pointed out by the OP in comments, the bug has been fixed in kernel version 4.5.2.
This command ``` gcc file.c -c ``` outputs me this ``` file.o ``` how to run above command so it outputs me object file with specified name for examplefile.dbg.o?
That's it: ``` gcc -o file.dbg.o -c file.c ```
Why this is not giving the desired output ? For Ex - take a=1,b=2,c=3,d=4 It is giving MAX4() = 2 while it should be 4 in this case. ``` #include<stdio.h> #define MAX4(a,b,c,d) MAX2(MAX2(a,b),MAX2(c,d)) #define MAX2(a,b) a>b?a:b int a,b,c,d; int main(){ /*printf("Please enter 2 integers - \n"); scanf("%d %d",&a,&b); printf("The maximum number among them is %d\n",MAX2(a,b)); */ printf("Please enter 4 integers - \n"); scanf("%d %d %d %d",&a,&b,&c,&d); printf("The maximum number among them is %d\n",MAX4(a,b,c,d));//,MAX2(a,b),MAX2(c,d)); return 0; } ```
You need to add parenthesis to enforce the order of evaluation: ``` #define MAX2(a,b) ((a)>(b)?(a):(b)) ``` The extra parenthesis around arguments are needed to allow for expressions likeMAX2(a + 1, b + 2).
This question already has answers here:C-equivalent of the 'setw' function(4 answers)Closed7 years ago. With ``` fprintf(f,"%d %d %d\n",m,l,k); ``` I got ``` 8 0 98 8 1 98 8 2 98 9 0 98 9 1 98 9 2 98 10 0 98 10 1 98 10 2 98 11 0 98 11 1 98 11 2 98 12 0 98 12 1 98 12 2 98 13 0 98 13 1 98 ``` What I really want is that each line has same format,like this ``` 9 2 98 10 0 98 ```
This code ``` fprintf(f,"%2d %d %2d\n",m,l,k); ``` yields: ``` 9 2 98 10 0 98 ```
I want to dynamically allocate a 2d array to store strings. I originally declared the array like this: ``` char lines[numlines][maxlinelength]; ``` This however gives me a stack overflow when numlines is very huge. How can I dynamically allocate it to prevent stack overflow?
Use a pointer to an array: ``` #define maxlinelength 10 char (*lines)[maxlinelength] = malloc( sizeof( char[maxlinelength] ) * numlines ) ; lines[0][0] = 'A' ; ``` This requires that the inner most size,maxlinelength, is constant. You can avoid this limitation if you use pointers to variable-length arrays in which case the syntax remains the same andmaxlinelengthdoesn't have to be a constant. Standards that supports this feature, are C99 and optionally C11. ( Aconstantis a variable whose value is known at compile time.) ( And to clarify:sizeof( *lines )is identical tosizeof( char[maxlinelength] ))
``` yyin = fopen("input_file.txt","r"); while ((nread = fread(buf, 1, sizeof buf, yyin)) > 0){ fwrite(buf, 1, nread, stdout); } fclose(yyin); yyin = fopen("input_file.txt","r"); yyparse(); fclose(yyin); ``` As you see, I open multiple times the same file. First I want to print the output in my cmd/terminal; then I want to start the parser. The problem is obvious: Each opening process costs resources, but the combination of fread and fwrite seems to "clean" my input file so that yyparse does not get any further input and basically stays empty. Do you have any idea of how to make this more performant or smooth with out 2 file openings?
You can use rewind() to return to the beginning of the file again. Seethis documentationfor more details.
How to define such an expression in c language : ``` x+(x^2)/(2*2-1) ``` wherexis a real number. I tried to enter the expression as it is but that didn't help. the thing is I don't want to use any self-defined functions, just loops. any ideas anyone?
In C,^is the bitwise XOR operator. There is no "power of" operator. So the C equivalent would look like this: ``` x+(x*x)/(2*2-1) ``` Operator precedence is just as for math, so note that the above is equivalent to ``` x + ( (x*x) / ((2*2)-1) ) ``` If you need a variable "raise x to the power of y", there is unfortunately only thepow()function, which works on floating point variables, and is therefore somewhat bloated and inefficient. However, writing your own integer version of it is trivial,see this.
I need help with a pointer declaration, I have several classes with arrays of pointers eg. ``` const char* const clsMainWin::mcpszXMLattrRoot[] = {"bottom","left","right","top",NULL}; const char* const clsMainWin::mcpszXMLattrA[] = {"x","y","z",NULL}; ``` What I want to do is define a pointer which groups the above arrays of pointers allowing me to select one of the about with a single index, eg: ``` const char* const allOptions[] = {mcpszXMLattrRoot, mcpszXMLattrA}; ``` Where: ``` allOptions[0][...] would be used to access mcpszXMLattrRoot and its contents: allOptions[1][...] would be used to access mcpszXMLattrA and its contents ``` However so far I'm struggling to get the declaration of allOptions correct.
You could store the pointer ofmcpszXMLattrRootandmcpszXMLattrA(i.e.const char * const *. ``` const char* const * allOptions[] = {mcpszXMLattrRoot, mcpszXMLattrA}; ```
Why this is not giving the desired output ? For Ex - take a=1,b=2,c=3,d=4 It is giving MAX4() = 2 while it should be 4 in this case. ``` #include<stdio.h> #define MAX4(a,b,c,d) MAX2(MAX2(a,b),MAX2(c,d)) #define MAX2(a,b) a>b?a:b int a,b,c,d; int main(){ /*printf("Please enter 2 integers - \n"); scanf("%d %d",&a,&b); printf("The maximum number among them is %d\n",MAX2(a,b)); */ printf("Please enter 4 integers - \n"); scanf("%d %d %d %d",&a,&b,&c,&d); printf("The maximum number among them is %d\n",MAX4(a,b,c,d));//,MAX2(a,b),MAX2(c,d)); return 0; } ```
You need to add parenthesis to enforce the order of evaluation: ``` #define MAX2(a,b) ((a)>(b)?(a):(b)) ``` The extra parenthesis around arguments are needed to allow for expressions likeMAX2(a + 1, b + 2).
This question already has answers here:C-equivalent of the 'setw' function(4 answers)Closed7 years ago. With ``` fprintf(f,"%d %d %d\n",m,l,k); ``` I got ``` 8 0 98 8 1 98 8 2 98 9 0 98 9 1 98 9 2 98 10 0 98 10 1 98 10 2 98 11 0 98 11 1 98 11 2 98 12 0 98 12 1 98 12 2 98 13 0 98 13 1 98 ``` What I really want is that each line has same format,like this ``` 9 2 98 10 0 98 ```
This code ``` fprintf(f,"%2d %d %2d\n",m,l,k); ``` yields: ``` 9 2 98 10 0 98 ```
I want to dynamically allocate a 2d array to store strings. I originally declared the array like this: ``` char lines[numlines][maxlinelength]; ``` This however gives me a stack overflow when numlines is very huge. How can I dynamically allocate it to prevent stack overflow?
Use a pointer to an array: ``` #define maxlinelength 10 char (*lines)[maxlinelength] = malloc( sizeof( char[maxlinelength] ) * numlines ) ; lines[0][0] = 'A' ; ``` This requires that the inner most size,maxlinelength, is constant. You can avoid this limitation if you use pointers to variable-length arrays in which case the syntax remains the same andmaxlinelengthdoesn't have to be a constant. Standards that supports this feature, are C99 and optionally C11. ( Aconstantis a variable whose value is known at compile time.) ( And to clarify:sizeof( *lines )is identical tosizeof( char[maxlinelength] ))
This question already has an answer here:Implementing Linux System Call using LKM(1 answer)Closed7 years ago. So I have seen a bunch of questions about adding system calls but I can't find any examples of one using an LKM that works. I have found resources like this:http://tldp.org/LDP/lkmpg/2.6/html/This works, in theory, but doesnt compile. Can anyone point me towards a simple example for adding a hello world system call or something. Something like this:https://tssurya.wordpress.com/2014/08/19/adding-a-hello-world-system-call-to-linux-kernel-3-16-0/that doesn't require me to recompile my kernel?
Generally, it's strongly recommended tonotimplement a whole new system call. Rather, only implement a newioctland likely some new block or character devices. For how to dothat, it looks like there is another question/answer already:How do I use ioctl() to manipulate my kernel module?
This question already has answers here:How does "while(*s++ = *t++)" copy a string?(17 answers)Closed7 years ago. I read this in a strcpy funciton. ``` while (*dst++ = *src++) ; ``` I'm not really sure the execute order. who can help me?
The postfix++operator increments the value of a variable after the statement it's in has been executed. According to C's precedence rules, the expression will be evaluated something like this: ``` while (*(dst++) = *(src++)); ``` Which will basically: Set the characterdstpoints to to the charactersrcpoints to.Increment bothdstandsrcIf the character was'\0', end the loop.Otherwise, repeat.
I am having some problems while usingfgetsandstrcat(I tried to replace thefgetsintoscanfand the program worked). It seems thestrcatis not working. ``` char name[256]; char text[256]; fgets(name,250,stdin); strcat(name,".txt"); printf("%s\n",name); ``` The output is (in separate lines): ``` d .txt ```
You have to remove the newline from the input. Like this: ``` fgets(name, 250, stdin); char *p = strchr(name, '\n'); if (p) *p = '\0'; strcat(name, ".txt"); ``` Obviously you'd want to add some error checking there but this demonstrates the idea.
I just wondered whether it is at all possible to use memory mapped files in portable C or C++. I think not because as far as I know no standard recognizes the existence of memory mapped files. Using memory mappings it is possible to have the same byte at two addresses. Also, I think it is not possible to even use a piece of memory without constructing an object there first (except throughchar*). So if we want to treat an existing mapped file as an array of integers that should be undefined behavior. So what's the situation regarding memory mapped files and the standard?
They do not. Memory mapping is generally offered by operating systems: C and C++ can also run without one. Imposing such availability on the range of platforms the languages target would be very limiting. Files may also not be supported at all in freestanding environments, let alone memory mapped ones.
``` struct circle { int center; int radius; }; struct circle *cir; cir.center cir->radius (cir.radius) (cir->center) ``` what is the difference between this 4 last lines? I know that cir.center is accessing a member of a struct circle pointed to by a variable cir. cir->radius is the same but pointed to by a pointer variable cir. But what do the () do?
Asciris declare as a pointer to the structure i.e.struct circle *cir;you have to use->operator toaccess the elements of a structure ifciris only declare as a variable of the type structure i.e.struct circle cir;then you have to use.operator toaccess the elements of structure as()does not make any difference here so(cir.radius) = cir.radiusand(cir->center)=cir->center
We need check whetherstat()call willaccess Hard diskduring its operation? i coulnt find answer for above question. can anyone help me on this?
Sincestat(2)identifies the file with a pathname, the system has no option but to query the filesystem for the information. I suppose the information could happen to be in a cache, so actually hitting the disk might not happen for a particular call, but generally the system will need to perform I/O.
``` struct circle { int center; int radius; }; struct circle *cir; cir.center cir->radius (cir.radius) (cir->center) ``` what is the difference between this 4 last lines? I know that cir.center is accessing a member of a struct circle pointed to by a variable cir. cir->radius is the same but pointed to by a pointer variable cir. But what do the () do?
Asciris declare as a pointer to the structure i.e.struct circle *cir;you have to use->operator toaccess the elements of a structure ifciris only declare as a variable of the type structure i.e.struct circle cir;then you have to use.operator toaccess the elements of structure as()does not make any difference here so(cir.radius) = cir.radiusand(cir->center)=cir->center
We need check whetherstat()call willaccess Hard diskduring its operation? i coulnt find answer for above question. can anyone help me on this?
Sincestat(2)identifies the file with a pathname, the system has no option but to query the filesystem for the information. I suppose the information could happen to be in a cache, so actually hitting the disk might not happen for a particular call, but generally the system will need to perform I/O.
I need to build a Linux user-space program that includes headers from the Linux Kernel. However those headers in turn seem to use other headers and so on. So my question is, what is the proper/good way of including all off the possible directories I could require in my Makefile? Thank you.
Most user-space programs using the Linux kernel headers don't need to do anything special.linux/is already included in the default include paths, e.g.#include <linux/netlink.h>. Distributions will include these files as part of their stanh>dard developer package, for examplebuild-essentialon Debian. You can also get headers specific for your kernel version, which is required when building a kernel module, but userspace programs will typically only interact with sockets and pipes and thus just need some structure definitions or protocol helpers for those channels (for example, Netlink).
We need check whetherstat()call willaccess Hard diskduring its operation? i coulnt find answer for above question. can anyone help me on this?
Sincestat(2)identifies the file with a pathname, the system has no option but to query the filesystem for the information. I suppose the information could happen to be in a cache, so actually hitting the disk might not happen for a particular call, but generally the system will need to perform I/O.
I need to build a Linux user-space program that includes headers from the Linux Kernel. However those headers in turn seem to use other headers and so on. So my question is, what is the proper/good way of including all off the possible directories I could require in my Makefile? Thank you.
Most user-space programs using the Linux kernel headers don't need to do anything special.linux/is already included in the default include paths, e.g.#include <linux/netlink.h>. Distributions will include these files as part of their stanh>dard developer package, for examplebuild-essentialon Debian. You can also get headers specific for your kernel version, which is required when building a kernel module, but userspace programs will typically only interact with sockets and pipes and thus just need some structure definitions or protocol helpers for those channels (for example, Netlink).
I'm getting a word from a user and I need to calculate it's length, but I can't seem to getstrlen()orsizeof()to work for some reason. What am I doing wrong here? ``` printf("Enter a word: "); char word; scanf("%c",&word); printf("%i",strlen(word)); ``` This seems really simple, but I can't print out the length of the string for the life of me.
The problem is that you are trying to read a string using only onecharstorage. The only string you can store there is thenullstring (which has length zero) i.e.word='\0' increase the size of the word buffer. Moreoverstrlenexpects achar*pointer and not a plainchar. ``` char word[100]; scanf("%s",word); printf("%i",strlen(word)); ```
I want to add a variable integer into the filename of a csv in the C-language. I am using this line of code to do that: ``` errCode = TG_SetDataLog(connectionId, "dataLog%d.csv", i); ``` If theerrCode = 0, than the functionTG_SetDataLogwill write data to a csv. I thougt i could add a variable by using%dand put the variable behind the comma, but this does not work. The following information is what i can get about theTG_SetDataLogfunction. If someone could help me it would be really helpfull.
``` char buff[64]; sprintf(buff, "dataLog%d.csv", i); errCode = TG_SetDataLog(connectionId, buff); ``` sprintf(orsnprintfthat is better because secure) is like printf, but write in a buffer, not on the standard output.
In C, I want to add a namespace prefix string(without quotes) to all functions for which I want it to happen, and later on change the namespace string any time easily. My approach: ``` #define NAMESPACE project_name void NAMESPACE_func_name() { } That should become: void project_name_func_name() { } ``` Is that possible, how? Thanks for help in advance.
You can do it with the macro concatenation operator and function-like macros: ``` #define NAMESPACE(name) project_name_ ## name void NAMESPACE(func_name)(void) { ... } ```
Can I somehow blit a part of a PNG file in the expose event in GTK2? I can load the PNG in a Pixbuf and use Cairo to use the Pixbuf as a brush, but I dont know how I can only use, lets say, the rectangle(1,1,10,10)of the PNG as a brush. Can someone point me in the right direction?
cairo_image_surface_create_from_pngis a good way to create a Cairo-centric PNG surface. You could then usecairo_surface_create_for_rectangleto restrict the size of thecairo_surface_t. Then you usecairo_set_source_surfaceto use your surface returned fromcreate_for_rectangleas a source or brush.
I'm looking for the least amount of code in C, in order to convert a char to int, where it flags -1 (or any error flag) if the char is not a valid hex digit. here's what I came up with, is there a shorter way? ``` // input example char input = 'f'; // conversion segment int x = input - '0'; if (!((x >= 49 && x <= 54) || (x >= 0 && x <= 9))) x = -1; if (x > 9) x -= 39; // test print printf("%d", x); ```
This code assumes ASCII and converts all 256 characters codes into 256 different codes, partially'0'-'9' 'A'-'F'map to0,1,...15. For additional tricks and simplification see thepost ``` unsigned char ch = GetData(); // Fetch 1 byte of incoming data; if (!(--ch & 64)) { // decrement, then if in the '0' to '9' area ... ch = (ch + 7) & (~64); // move 0-9 next to A-Z codes } ch -= 54; // -= 'A' - 10 - 1 if (ch > 15) { ; // handle error } ```
I'm looking for the least amount of code in C, in order to convert a char to int, where it flags -1 (or any error flag) if the char is not a valid hex digit. here's what I came up with, is there a shorter way? ``` // input example char input = 'f'; // conversion segment int x = input - '0'; if (!((x >= 49 && x <= 54) || (x >= 0 && x <= 9))) x = -1; if (x > 9) x -= 39; // test print printf("%d", x); ```
This code assumes ASCII and converts all 256 characters codes into 256 different codes, partially'0'-'9' 'A'-'F'map to0,1,...15. For additional tricks and simplification see thepost ``` unsigned char ch = GetData(); // Fetch 1 byte of incoming data; if (!(--ch & 64)) { // decrement, then if in the '0' to '9' area ... ch = (ch + 7) & (~64); // move 0-9 next to A-Z codes } ch -= 54; // -= 'A' - 10 - 1 if (ch > 15) { ; // handle error } ```
I want run a command write execlp function within c file in linux. I want to run the following command : ls -l I can do ls command as follows : execlp("/bin/ls" , "ls", NULL)
Add the option to the parameter list: ``` execlp("/bin/ls", "ls", "-l", NULL); ```
I have a pointer to a struct named sp. ``` struct thestruct *sp_pointer = NULL; sp_pointer = sp; ``` This stuct has a field called units. i.e.sp->units if I were to dosp_ponter->units = sp_pointer->units + 100; would this update the value in sp->units?
if I were to do sp_ponter->units = sp_pointer->units + 100;would this update the value in sp->units? Yes, it would.sp_pointeris pointing to same memory asspafter your assignment. Granted both pointers are of same type, what you have should be ok.
I'm trying to create a macro that generates a bit pattern as such: genmask(1)gives0xff00ff00.. genmask(2)gives0xffff0000.. EDIT:genmask(3)gives0xffffffff00000000 so far I have#define genmask(x) ((size_t)-1 / ((1 << 16 * (x)) - 1) * ((1 << 8 * (x)) - 1)) which will not work due to lhs > type width, EDIT: and becausegenmask(3)has to give0xffffffff00000000
``` #define genmask(x) ((unsigned long long)-1 / ((1LL << (1LL << (x)) * 4) + 1) << (4 * (1 << (x)))) ``` Demo There are only 4 values which are going to work 0-3. It is possible to write a separate macro for each of them.
I need to calculate a large number which has length about 9-10 digits. Msdn says that long long type has a range for:–9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 But when i run this code i get a garbage value printed: ``` #include <stdio.h> int main(){ int seed = 88888; //This will be always a 5 digit number so the square of // it will be 9 or 10 digits length long long square = seed * seed; printf("square = %lld", square); getchar(); return 0; } ``` Output: square = -688858048
seedis of typeint.seed*seedwill also be of typeint. And88888*88888overflows the size ofint. You then assign this garbage value to yourlong long. Change the type ofseed, or cast in you calculation: ``` long long square = ((long long) seed) * seed; ```
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question I am writing a program in C and I have the following problem: The user gives as input a two-character string, which contains one single digit number and one letter (for example 2B). How can I divide it in one integer (2) and one character (B)? Thank you very much!
You can use the%cspecifier to get individual characters ``` char a, b; printf("Give the 2char string"); scanf("%c%c", &a, &b); printf("Char 1: %c\nChar2: %c", a, b); ```
I am trying to run a test file through my C program, but I seem to be making a mistake. My program is stdin/stdout, so it should work. When I run it in the normal "Build and Run" popup of Code Blocks, by copying the file contents in, it runs perfectly fine. But when I run it in command prompt like ``` input.txt < maze.c > output.txt ``` it isn't working. I put all three files on the desktop as well, and used cd Desktop to get there. When I run that line, it opens the input file, and leaves the output file empty. Any suggestions?
The command should be : $ prog_name < input_file > output_file not : $ input_file < prog_name > output_file Also,maze.cis the source code, not the compiled program.
If my program looks like this: ``` printf("What are your 2 favourite fruits:\n"); scanf("%s", s1); printf("What are your 2 least favourite fruits:\n"); scanf("%s", s2); ``` and my first Scanf() has a space in it, the second Scanf() gets skipped. The output would look like this: What are your 2 favourite fruits: Apples and Oranges What are your 2 least favourite fruits: (doesn't wait for input) What should I do to fix this?
scanf()with%sdoes not accept strings containing white-spaces.For strings having white-spaces, usefgets()orscanf("%[^\n]s", string);This would read everything until newline character '\n'. For example: ``` printf("What are your 2 favourite fruits:\n"); scanf("%[^\n]s", s1); printf("What are your 2 least favourite fruits:\n"); scanf("%[^\n]s", s2); ```
I have c program where i have to save a file in ubuntu. The program runs fine on my local pc but i want to use a single exe for other pcs whether they run linux or windows. So, how should i give path to store file that it works everywhere?
Sorry, but you can't do what you want. When an Operating System runs a program, it looks in the file to find things that it needs to know. Windows and Linux store this information in incompatible ways, so you won't be able to create a file that will run under both Windows and Linux.
I am making one C program in which I want the function or any method to fix size of output console window. Is there any function or way in C language to perform this task? Generally the shape of output console is rectangle but to display proper output of my program I want to fix the square shape so I want to re size the output console using the programming. I am using GNU GCC compiler and Os is Microsoft Windows 8.1.
C language don't have any function to control console property but you can use windows header file to control console. You can get a handle to the console window usingGetConsoleWindow. Once you have that, you should be able to resize it usingSetWindowPos You may also need to resize the buffer for the console usingSetConsoleScreenBufferSizeprior to resizing the window. Visit
§5.1.1.2/2 in N1570: 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. A source file that is not empty shall end in a new-line character, which shall not be immediately preceded by a backslash character before any such splicing takes place. Reading this paragraph my understanding is thatonlythe backlash character(\) is deleted, when it is immediately followed by a new-line character. But after reading other posts here in SO, about this paragraph, I came to the impression that both the backlash character and the next new-line character are eliminated from the source character set making up the file. Which one is correct?
Both backslash and newline are deleted. ``` a \ b ``` is read asa b.
I wrote this c-program : ``` int counter = 0; void* increment() { int maxI = 10000; int i; for (i = 0; i < maxI; ++i) { counter++; } } int main() { pthread_t thread1_id; pthread_t thread2_id; pthread_create (&thread1_id,NULL,&increment,NULL); pthread_create (&thread2_id,NULL,&increment,NULL); pthread_join (thread1_id,NULL); pthread_join (thread2_id,NULL); printf("counter = %d\n",counter); return 0; } ``` As a result I get :counter = 10000 why is that ? I would have expected something much bigger instead as I am using two threads, how can I correct it PS : I am aware that there will be a race condition! edit :volatile int counterseems to solve the problem :)
Predicting what code with bugs will do is extremely difficult. Most likely, the compiler is optimizing yourincrementfunction to keepcounterin a register. But you'd have to look at the generated assembly code to be sure.
I have been tasked with implementing an ls function for files in an .iso file system. I need to use fread but it is segfaulting. I know the file exists and i know it has data in it. I have the format for calling fread and I have set it up as follows ``` static void ls(File *file, int32_t root_dir_size) { void* sector; int result; result = fread(sector, 1, 1, file); } ``` Why does this segfault? I am new to C and I am coming from C++ so not sure what I am missing here.
freadneeds memory into which to put the data it's reading. That memory is pointed to by the first parameter, in your casesector. However, you have not initializedsector. You will need to allocate some memory, in this case just one byte and havesectorpoint to that. For instance: ``` void *sector = malloc(1); ``` As always, don't forget to free the memory after you're done using it.
I need to calculate a large number which has length about 9-10 digits. Msdn says that long long type has a range for:–9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 But when i run this code i get a garbage value printed: ``` #include <stdio.h> int main(){ int seed = 88888; //This will be always a 5 digit number so the square of // it will be 9 or 10 digits length long long square = seed * seed; printf("square = %lld", square); getchar(); return 0; } ``` Output: square = -688858048
seedis of typeint.seed*seedwill also be of typeint. And88888*88888overflows the size ofint. You then assign this garbage value to yourlong long. Change the type ofseed, or cast in you calculation: ``` long long square = ((long long) seed) * seed; ```
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question I am writing a program in C and I have the following problem: The user gives as input a two-character string, which contains one single digit number and one letter (for example 2B). How can I divide it in one integer (2) and one character (B)? Thank you very much!
You can use the%cspecifier to get individual characters ``` char a, b; printf("Give the 2char string"); scanf("%c%c", &a, &b); printf("Char 1: %c\nChar2: %c", a, b); ```
I am trying to run a test file through my C program, but I seem to be making a mistake. My program is stdin/stdout, so it should work. When I run it in the normal "Build and Run" popup of Code Blocks, by copying the file contents in, it runs perfectly fine. But when I run it in command prompt like ``` input.txt < maze.c > output.txt ``` it isn't working. I put all three files on the desktop as well, and used cd Desktop to get there. When I run that line, it opens the input file, and leaves the output file empty. Any suggestions?
The command should be : $ prog_name < input_file > output_file not : $ input_file < prog_name > output_file Also,maze.cis the source code, not the compiled program.
If my program looks like this: ``` printf("What are your 2 favourite fruits:\n"); scanf("%s", s1); printf("What are your 2 least favourite fruits:\n"); scanf("%s", s2); ``` and my first Scanf() has a space in it, the second Scanf() gets skipped. The output would look like this: What are your 2 favourite fruits: Apples and Oranges What are your 2 least favourite fruits: (doesn't wait for input) What should I do to fix this?
scanf()with%sdoes not accept strings containing white-spaces.For strings having white-spaces, usefgets()orscanf("%[^\n]s", string);This would read everything until newline character '\n'. For example: ``` printf("What are your 2 favourite fruits:\n"); scanf("%[^\n]s", s1); printf("What are your 2 least favourite fruits:\n"); scanf("%[^\n]s", s2); ```
I have c program where i have to save a file in ubuntu. The program runs fine on my local pc but i want to use a single exe for other pcs whether they run linux or windows. So, how should i give path to store file that it works everywhere?
Sorry, but you can't do what you want. When an Operating System runs a program, it looks in the file to find things that it needs to know. Windows and Linux store this information in incompatible ways, so you won't be able to create a file that will run under both Windows and Linux.
I am making one C program in which I want the function or any method to fix size of output console window. Is there any function or way in C language to perform this task? Generally the shape of output console is rectangle but to display proper output of my program I want to fix the square shape so I want to re size the output console using the programming. I am using GNU GCC compiler and Os is Microsoft Windows 8.1.
C language don't have any function to control console property but you can use windows header file to control console. You can get a handle to the console window usingGetConsoleWindow. Once you have that, you should be able to resize it usingSetWindowPos You may also need to resize the buffer for the console usingSetConsoleScreenBufferSizeprior to resizing the window. Visit
§5.1.1.2/2 in N1570: 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. A source file that is not empty shall end in a new-line character, which shall not be immediately preceded by a backslash character before any such splicing takes place. Reading this paragraph my understanding is thatonlythe backlash character(\) is deleted, when it is immediately followed by a new-line character. But after reading other posts here in SO, about this paragraph, I came to the impression that both the backlash character and the next new-line character are eliminated from the source character set making up the file. Which one is correct?
Both backslash and newline are deleted. ``` a \ b ``` is read asa b.
I wrote this c-program : ``` int counter = 0; void* increment() { int maxI = 10000; int i; for (i = 0; i < maxI; ++i) { counter++; } } int main() { pthread_t thread1_id; pthread_t thread2_id; pthread_create (&thread1_id,NULL,&increment,NULL); pthread_create (&thread2_id,NULL,&increment,NULL); pthread_join (thread1_id,NULL); pthread_join (thread2_id,NULL); printf("counter = %d\n",counter); return 0; } ``` As a result I get :counter = 10000 why is that ? I would have expected something much bigger instead as I am using two threads, how can I correct it PS : I am aware that there will be a race condition! edit :volatile int counterseems to solve the problem :)
Predicting what code with bugs will do is extremely difficult. Most likely, the compiler is optimizing yourincrementfunction to keepcounterin a register. But you'd have to look at the generated assembly code to be sure.
This question already has answers here:Windows equivalent of inb(), outb(), low level i/o(3 answers)Closed7 years ago. For Linux you can include<sys/io.h>to have I/O Ports with hardware I assume? ``` outb(...); outw(...); inb(...); ``` Which header must I include to have these functions for Windows compilation? Edit:Windows equivalent ofinb(),outb()low-level I/Osays it's impossible on Windows; you need install a driver on Windows to use a quick fix.
Generally, for MS Windows low level io is WinAPI functions like CreateFile, WriteFile and so on.
``` #define N 10000000 int arr[N]; int main(void) { int i; for(i=0;i<N;i++) arr[i]=i+1; } ``` Why declaring the array globally do not give any compilation error? What is the chance of the availability of contiguous memory of N*4 bytes in the stack? Same for declaring the array withstatickeyword.
This image should help. You can see that on the stack we are allocating memory only for local variables and arrays and function calls and pointers. While the Global variables/ Static are stored on Perm Storage.
Hi can anyone tell me what is the paramter of isatty() in c. I have following code, but I don't understand the first output three number would be 1 and all the left is 0. ``` #include <unistd.h> #include <stdio.h> #include <stdlib.h> int main(){ for(int i=0;i<100;i++){ int t=isatty(i); printf("%d",t); } return 0; } ```
A quick look at your man pages would reveal: ``` int isatty(int fildes); DESCRIPTION The isatty() function tests whether fildes, an open file descriptor, is associated with a terminal device. ``` Further investigation would lead you to the discovery that file descriptors 0, 1 and 2 (aka STDIN_FILENO, STDOUT_FILENO and STDERR_FILENO) are by convention set up to point to your terminal when your program is running from a terminal.
Why it stops working? Can't we pass the name of the pointer as an argument for strcpy? if I change it tostrcpy(&a,&b);it works. ``` #include <stdio.h> int main() { char *a; a = "aabtyn"; char *b; b = "mihli"; strcpy(a,b); printf("%s-%s\n",a,b); return 0; } ```
Can't we pass the name of the pointer as an argument forstrcpy? Yes, we can. However, it is also important that the destination pointer points to a writeable memory; in your case, neitheranorbpoint to memory that can be written. if I change it tostrcpy(&a,&b);it works. If it appears to work on your system, it does so by mistake. What you see is undefined behavior. In order forstrcpyto work you need to do one of the following: Allocateain automatic memory by defining it aschar a[] = "aabtyn";, orAllocateain dynamic memory by callingchar *a = malloc(7);You need seventh byte for null terminator.
If I have the following fucntion ``` int execute_command(char **args) { if (args[0] == NULL) { return 1; } //more code... } ``` How can I purposely callexecute_command(blank)wherechar **blankwould be (null) initialised in such a way to allow the if statement to be evaluated as true?
A straightforward way of doing this is to create an array of pointers of size one, and set its content toNULL, like this: ``` char *args[] = { NULL }; ``` Now you can pass this array toexecute_command: ``` execute_command(args); ``` the array of pointers would "decay" to a pointer-to-pointer on function call, producing the effect that you are looking for.
I'm trying to ask the user to type the input file they want me to read, and I would like to save one input into two variables where the input file would be "file.txt", but I want the output file to be "file.txt.cvt" At the moment I'm having problems with it. Here is what I have ``` printf("Enter file name: "); //asks for filename from user scanf("%s %s.cvt", input_file, output_file); //stores string as "filename" inputf = fopen(input_file, "r"); /*file open stored string as read only. 'filename, "r"'*/ outputf = fopen(output_file, "w"); ```
``` strcpy(output_file, input_file); // Make a copy of the input file name strcat(output_file, ".cvt"); // Add the ".cvt" suffix to it ```
This question already has answers here:Using pointers to iterate through argv[](6 answers)Closed7 years ago. If I havechar **argshow can I loop through therowsof the array to determine how many there are? For example, ifchar **args == {"one", "two", "three"}, how can I loop through each element, keeping count, and then return 3?
Since yourargsis null-terminated, simply write ``` int i; for (i = 0; args[i]; i++) // do something ```
This might be areallystupid question, and if it is, please excuse me for it, but I have been looking for an answer before and I haven't found anything. Is it possible to write something like ``` case 'i': do { root=insert(root,code[1]); scanf("%s",code); }while (code[0]=='i'); break; ``` in C? Thank you for your answer and sorry again if this is a stupid question. Have a nice day :)
If it is necessary for your project, then you can use it. There is no harm in using it. Compiler wouldn't throw any error or warning. It will work as expected if created with care. But it could make your code unreadable and also it will increase the level of indentation. You can create a function which will have your loop. It could increase readability of the code. For example, ``` case 'i': func(); break; ```
``` char *p; fgets(p,10,stdin); ``` Why is this crashing my program? Seems like I can't use char pointers in Fgets but I can use arrays so it makes no sense.
Seems like I can't use char pointers in Fgets but I can use arrays No, you can use both, as long as you allocate memory to the pointer before passing that tofgets(). In this case, using pointers, ``` char *p; ``` pis unitialized and points to some arbitrary memory location which is invalid. You need to allocate proper memory topbefore you can read/write something to/from the memory location pointer byp.
Why does this give stopped running after compiling. It gives the output correctly but right after that it corrupts. ``` #include <stdio.h> int main() { char *cities[] = {"Adiyaman","Kayseri","Istanbul"}; int i; for(i=0; *(cities+i) != NULL; i++) { printf("%s\n",*(cities+i)); } return 0; } ```
Define the array the following way ``` char *cities[] = { "Adiyaman","Kayseri","Istanbul", NULL }; ``` Otherwise the loop will not work because the array does not have an element that is equal to NULL. It would be simpler to write the loop the following way ``` for ( i = 0; i != sizeof( cities ) / sizeof( *cities ); i++) { puts( cities[i] ); } ``` Or if you want to use pointers then ``` for ( char **p = cities; p != cities + sizeof( cities ) / sizeof( *cities ); p++) { puts( *p ); } ```
I have a function that takes in a file pointer (FILE * file) and copies everything in that file. Now, is it possible to erase everything inside this file? I do not have the file name so I can not usefopen(filename, "w")again. I havestdio.handstring.hincluded.
You can use theftruncate()system call to empty a file using its file descriptor, e.g. ``` ftruncate(fileno(fh), 0); ``` You will probably want to follow that up with a call torewind(fh)so that any further writes to the file are made at the beginning, rather than at the previous offset.
A function declared ``` void f(const char * const p) { ... } ``` means that it takes a constant pointer to a constant character. But, with the variablepscoped only within the function itself and its usage hidden from the callee, does it matter if the secondconstis there? In other words, wouldn't the following be semantically identical to the first from the perspective of the callee? ``` void f(const char *p) { ... } ```
The first const indicates that you can't change the data is pointing to, the second indicates that this pointer can't be overwritten. So, for a caller of this function, it doesn't matter. For the implementation of the function, it can be useful, though it will only have effect locally.
I have a problem, that I need to scan two integers in one line divided by a space, so the code looks something like this: ``` scanf("%d %d",&integer1,&integer2); ``` And in this code I need to check whether there were scanned two integers. Can someone help me? Thank you in advance
By defaultscanf()reads the space there is no meaning in giving space. If you want to read two integersscanf("%d %d",&integer1,&integer2);andscanf("%d%d",&integer1,&integer2);both will help you. It will accept the following inputs: ``` 1 2 12 22 3 2 5 //EOF ``` your program will pass only after reading two integers. You don't need to check anything.To eliminateEOF By defaultscanfreturns number of values read so make use of it. ``` if(scanf("%d%d",&integer1,&integer2) != 2) { //if more than two values are entered //perform some error handling } ```
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 why this question is entering in infinite loop. Acc to me ans should be 65001,65002....65535. Plesae elaborate.Thanks in advance ``` #include<> #include<stdio.h> #include<conio.h> int main() { unsigned int i=65000; while ( i++ != 0 ) printf("%d ",i); return 0; getch(); } ```
On modern systems, an unsigned int is at least 32 bits, but you are expecting 16 bits. You don't have an infinite loop, but it won't wrap around until at least 2^32 (4294967296).
I have this code that write and write fromEEPROMfor 4 digit number.For Ex: 2356 Code; ``` void WritePassToEEPROM(uint16_t pass) { EEPROMWrite(0000,(pass%100)); EEPROMWrite(0001,(pass/100)); } uint16_t ReadPassFromEEPROM() { return (EEPROMRead(0001)*100 + EEPROMRead(0000)); } ``` TheWrite_Pass_To_EEPROM()function writes to 2 addresses0000and0001. for2356,2356%100is56and2356/100is23. So, at address0000it will be 56 and at address0001it will be23. While readingEEPROM_Read(0000)will return34andEEPROM_Read(0001)*100will return2300.2300 + 56is2356. But if i need to write5digit number like65238what should i do.
This will go up to 0xffff (65535). ``` void WritePassToEEPROM(uint16_t pass) { EEPROMWrite(0000,(pass & 0x00ff)); EEPROMWrite(0001,(pass & 0xff00) >> 8); } uint16_t ReadPassFromEEPROM() { return ((uint16_t)(EEPROMRead(0001) << 8) + (uint16_t)EEPROMRead(0000)); } ```
I have a connected socket that I want to abortively close, but I do not want an RST to be sent to the other end. Can this be done?
Your question embodies a contradiction in terms. 'Abortively close' == RST. Even if the actual abortive close didn't send it immediately, TCP is obliged to send it on receipt of any other traffic for the connection, including data, ACKs, or even the peer's closing FIN.
The standard library of my C compiler definesNULLthis way: ``` #define NULL 0 ``` I would expect: ``` #define NULL ((void *)0) ``` Could someone tell me which one is correct and why? Thank you!
The last revisions of C standard, C99 and C11, equates the null quantity to zero or null pointer.FromISO/IEC 9899:201x §6.3.2.3 Pointers, point 3: An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function. So what you see is a perfectly compliant NULL declaration of a C99-C11 compiler as opposed to the previous#define NULL ((void *)0)of pre C99 compilers.
I am trying out some basic datastructure stuff in C. And I am coming back to C after a long time. Here is my simplestruct: ``` typedef struct { int data; LLNode *next; //Error: unknown type name 'LLNode' }LLNode; ``` But it gives a compilation error as shown above. Is it because while compilingstructcompiler is not aware of existence ofLLNode? That means I must be first declaringLLNodebeforestruct. Is it like that? If yes how I am supposed to do it?
Do this that way: ``` typedef struct LLNode LLNode; struct LLNode { int data; LLNode *next; //No error }; ``` You cannot useLLNodetype before it is defined. With this method you declare what isLLNodefirst. Even thoughstruct LLNodeis not defined yet, this declaration suffice to declareLLNode *members (but you could not declare aLLNodemember yet) as a pointer's size does not depend on the pointer's type.
This question already has answers here:Strange array initialize expression?(3 answers)Closed7 years ago. I am readingBruce Dawson's article on porting Chromium to VC 2015, and heencountered some C code that I don't understand. The code is: ``` char c[2] = { [1] = 7 }; ``` Bruce's only comment on it is: "I am not familiar with the array initialization syntax used - I assume it is some C-only construct." So what does this syntax actually mean?
C99allows you to specify the elements of the array in any order (this appears to be called "Designated Initializers" if you're searching for it). So this construct is assigning7to the second element ofc. This expression is equivalent tochar c[2] = {0, 7};which does not save space for such a short initializer but is very helpful for larger sparse arrays. See this page for more information:https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html
I am new to kernel programming, and confused about how you should handle data in user memory. If I confirm that the return value ofstrlen_user(user_str)does not equal zero, is it okay to pass user_str toprintk, or should I always copyuser_strto kernel memory instead?
You should always copy the userspace string when accessing it from kernel. Suppose that userspace application have several threads. One allocates string on heap and passes it to your kernel module. The other thread simultaneously frees the allocated string. Then the following situation can happen: first userspace thread passes the string to kernelkernel validates string to be okay withstrlen_user(user_str)second userspace thread frees string memorykernel starts working with said string That may lead to different unwanted consequences including kernel panic. So, usestrncpy_from_user()function for copying string from userspace and only work with copy afterwards.
I am passing pointer to pointer totypedef structto the function. When I try to change the content oftypedef struct, it gives me following error: request for member 'a' in something not a structure or union } The code: ``` typedef struct _tempStruct { int a; int b; }TempStruct; void _function(TempStruct ** param) { TempStruct *temp = *param; temp -> a = 5; //no error *param -> a = 6; //error: request for member 'a' in something not a structure or union } ``` Here is the link of code on ideone. What I am missing?
->has a higher precedence than that of*(indirection), so ``` *param -> a = 6; ``` should be ``` (*param)->a = 6; ```
I was debugging a Linux C program with CLion's internal debugger (which is gdb on Linux). The program forked a child process that was supposed to get suspended at the break point I set. But the debugger didn't stop there even if I had enteredset follow-fork-mode childinside the gdb panel. So how can I make that happen with CLion?
I followedanswerposted by @MarkusParker, but instead ofset auto-load safe-path /I usedset detach-on-fork offto prevent disconnect from child process. This instruction works for me: Set a break point at the beginning of your program (ie. the parent program, not the child program).Start the program in the debugger.Go to the debugger console (tab with the label gdb) in clion and enterset follow-fork-mode childandset detach-on-fork off.Continue debugging.
I have a connected socket that I want to abortively close, but I do not want an RST to be sent to the other end. Can this be done?
Your question embodies a contradiction in terms. 'Abortively close' == RST. Even if the actual abortive close didn't send it immediately, TCP is obliged to send it on receipt of any other traffic for the connection, including data, ACKs, or even the peer's closing FIN.
The standard library of my C compiler definesNULLthis way: ``` #define NULL 0 ``` I would expect: ``` #define NULL ((void *)0) ``` Could someone tell me which one is correct and why? Thank you!
The last revisions of C standard, C99 and C11, equates the null quantity to zero or null pointer.FromISO/IEC 9899:201x §6.3.2.3 Pointers, point 3: An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function. So what you see is a perfectly compliant NULL declaration of a C99-C11 compiler as opposed to the previous#define NULL ((void *)0)of pre C99 compilers.
I am trying out some basic datastructure stuff in C. And I am coming back to C after a long time. Here is my simplestruct: ``` typedef struct { int data; LLNode *next; //Error: unknown type name 'LLNode' }LLNode; ``` But it gives a compilation error as shown above. Is it because while compilingstructcompiler is not aware of existence ofLLNode? That means I must be first declaringLLNodebeforestruct. Is it like that? If yes how I am supposed to do it?
Do this that way: ``` typedef struct LLNode LLNode; struct LLNode { int data; LLNode *next; //No error }; ``` You cannot useLLNodetype before it is defined. With this method you declare what isLLNodefirst. Even thoughstruct LLNodeis not defined yet, this declaration suffice to declareLLNode *members (but you could not declare aLLNodemember yet) as a pointer's size does not depend on the pointer's type.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question While reading a script on keeping log of which key is pressed on the keyboard (windows platform), I've found the following snippet. I already have read the msdn document on GetAsyncKeyState() and searched the for explanation but did not find any satisfactory answer. Thanks in advance :) ``` if (GetAsyncKeyState(character) == -32767){ //do something } ```
Theshort(16-bit) value-32767is0x8001in hexadecimal. This makes it easy to see that bits 0 and 15 are set. Theman pagesays"If the most significant bit is set, the key is down, and if the least significant bit is set, the key was pressed after the previous call to GetAsyncKeyState."As both those bits are set, those two conditions were both true.
Im curious if they have an official name or just 'dot' and 'arrow'? I try search this in cpluscplus and in Deitel, but didn't find anything
The C standard calls themmember access operators, but only in the index. They aren't given a name anywhere else except the one place in the index. In the same place, the->operator is calledarrow operator,the.operator is calledstructure/union member operator.
I want to send duplicate string to my bison file. In my flex file I use it like this ``` "<" {return strdup(tOPEN);} ">" {return strdup(tCLOSE);} ``` Is this right things to do? Or should I use it like below the code. ``` "<" { yyval. sval = strdup(yytext); return tOPEN;} ```
``` "<" { yyval. sval = strdup(yytext); return tOPEN;} ``` this is the right way of the using.
All python thread(in CPython) are under GIL. What if the thread is created byctypes? For example, python just calls the below function throughC Libraryand the function create a thread inCarea not python. ``` #include<thread> int createUnitTestThread(int sasAddr){ sasEngine->thread = new std::thread(....); return 0; } ``` Is it the same or not ?
It's not likethreadsare under the GIL, operations in the Python interpreter are (including stuff like the fetch and execution of most opcodes, so that's why threads that execute Python code run mostly interlocked). Your C++ thread will run free as long as it doesn't call back functions in the Python interpreter (either user callbacks or functions coming from Python.h).
I'm writing an android application with cordova that requires the use of an existing C library for deserializing binary data. I believe I need to create a cordova plugin to write a javascript wrapper to access android's native java and utilize NDK, however I have no idea how to go about doing it. I have no experience writing cordova plugins, let alone one that uses NDK. Could anyone give me a walk through or even better a simple example plugin that achieves this? Thanks.
I did a lot of research and I think I figured things out, I made a repo to help anyone else that needed a simple example to learn from:https://github.com/clement360/Cordova-Hello-JNI-Plugin
I have the following struct ``` typedef struct VMCS { uint32_t revision; uint32_t abortValue; } __attribute__ ((packed)) VMCS; ``` when I try to compile my code I get this warning from gcc ``` warning: unnamed struct/union that defines no instances ``` followed by a bunch of errors caused by VMCS being undefined. The code that precedes this is very innocuous, consisting of including stdint.h and a number of #define entries. It does not seem like those could cause errors that would interfere with the struct.
... and a number of #define entries Apparently you definedVMCSas a macro with empty replacement list. Your code is seen by the compiler as ``` typedef struct { uint32_t revision; uint32_t abortValue; } __attribute__ ((packed)); ``` Hence the warning.
I've readhttp://linux.die.net/man/3/globand it seems that glob will do disk access, even though I don't want it to. Is there a C glob function to compare a string with a glob pattern and tell me if it matches? i.e. no disk access. If not, how can I use glob toexcludefiles when recursively (depth first) traversing a filesystem? ``` while((entry = readdir(dp))) { // need to continue to next iteration of loop, here, if entry->d_name matches glob pattern // do stuff and recurse } ```
Use thefnmatchfunction. It compares a filename/path against a given pattern.
Sorry if it's a stupid question, but I couldn't find much information. I just want to assign the result of a comparison in a variable, like this: ``` int a = 3, b = 2; // In actual code they're not integer literals int result = a > b; ``` When compiling,gcc(with-Wall) doesn't complain, and looking at the assembly output I found it's translated tocmpandsetle(orsetgetc.). I'm wondering whether it's invalid (C) code or considered bad practice, since I see it's never used.
This is a perfectly valid C code. The behavior is detailed in section 6.5.8.6 of the C99 standard: Each of the operators<(less than),>(greater than),<=(less than or equal to), and>=(greater than or equal to) shall yield1if the specified relation is true and0if it is false. The result has typeint. Unless you are maintaining legacy code that must be compatible with pre-C99 compilers,consider using<stdbool.h>andbooltypeinstead of anint.
I came across two solutions for reading the float value of a BLE sensor. The memcpy method is straightforward and makes sense, however the other method I came across is not very clear to me. Can someone clarify exactly how the pointer casting method works? ``` // Represents data read from BLE device. Float value of 1.5 uint32_t data = 0x3fc00000; float sensorValue; // Memcpy method, makes sense and is straightforward memcpy(&sensorValue, &data, sizeof(sensorValue)); // Works, but don't fully understand exactly how sensorValue = *(float *)&data; ```
&data is a pointer to a uint32_t. So, (float *)&data casts it as a pointer to a float. Finally, *(float *)&data dereferences that pointer. You could do the same thing as: ``` uint32_t *ui32 = &data float *f = (float *) ui32; sensorValue = *f; ``` But, the exact behavior is likely to be platform dependent.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question I would like to convert a unsigned char * variable to a unsigned int *. Something like this ``` unsigned char *test = 0; unsigned int *x = test; ```
Use a cast, which in C would be ``` unsigned int *x = (unsigned int*)test; ``` But bear in mind this would be useless in your example (and in any other example I can think of) since dereferencing the pointer would give you 1, 3 or 7 bytes of undefined memory. If you want to promote thecharto anunsigned intthen you would either have to store it as anunsigned intin the first place, or copy it onto the stack.
I am reading in a text file and using a comma as a delimiter, the line below does work however when I print out lname it does not ignore the white space after the comma and prints a space before name. How can I adjust the code to ignore white space? example of text: Rob, Smith, 4, 12, sometextSteve, Jones, 41, 286, sometext ``` sscanf(line, "%[^,],%[^,],%d,%d,%s", fname,lname,&num1,&num2,info); ```
Just add a whitespace character if you want to ignore whitespace: ``` sscanf(line, " %[^,], %[^,], %d, %d, %s", fname, lname, &num1, &num2, info); ``` The space before%dand%sare not required as they already skip leading whitespace characters. The only format specifiers which does not skip leading whitespace are%c,%[and%n. Note that a whitespace character in the format string of*scanfinstructsscanfto scan any number of whitespace, including none, until the first non-whitespace character.
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 In the following code, I am trying to read a file char by char and display each char on the console: ``` #include <stdio.h> #pragma warning(disable:4996) int main(){ FILE *file; file = fopen("input.txt", "r"); int c; while ((c = fgetc(file)) != EOF) { printf("%c ",(char)c ); } return 0; } ``` I got the following error: Can someone help me solving this issue?
You must check the result of fopen. The pointer file is NULL because the opening failed. ``` file = fopen("input.txt", "r"); if (file == NULL) { //error } ```
I have an anonymous union nested within a struct, as well as other common fields. Is there any reason to place the union in a specific place within the struct (e.g. first or last)? For example, is this: ``` typedef struct _Message { MessageType type; union { SystemMessageArgs systemArgs; OtherMessageArgs usbArgs; }; } Message; ``` better than this: ``` typedef struct _Message { union { SystemMessageArgs systemArgs; OtherMessageArgs usbArgs; }; MessageType type; } Message; ``` in any way? The context is embedded-C, specifically TI's MSP430
There may be a possible difference in padding, you can find that out by usingsizeof()on both of them and comparing the results. This may be relevant if you are dealing with heavily constrained memory amounts. Other than that, they are equivalent.