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 de...
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 ...
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 inW...
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> ...
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"); ...
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). gmt...
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_A...
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 pointe...
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...
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 ...
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 pointe...
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...
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 ...
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 pr...
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 = mallo...
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'...
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 = ...
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: ``` val...
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...
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 ...
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 ...
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 ...
``` 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 ...
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 unfo...
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 ...
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 ...
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 ...
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 ...
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 t...
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.Incre...
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 p...
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...
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(...
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...
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(...
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 ...
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 ...
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 t...
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 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 v...
``` 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 ...
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 &&...
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 '...
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 &&...
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 '...
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 becau...
``` #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...
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 stri...
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 < ma...
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: Ap...
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 fru...
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 ...
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 usingS...
§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...
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); pthrea...
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* sec...
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 a...
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...
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 stri...
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 < ma...
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: Ap...
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 fru...
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 ...
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 usingS...
§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...
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); pthrea...
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? Ed...
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); ...
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, ...
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 ...
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, prod...
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: "); //as...
``` 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 t...
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; `...
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 you...
``` 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 pr...
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...
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 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 se...
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....
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...
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(...
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 ...
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...
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 yo...
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 f...
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 v...
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 t...
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 *...
->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...
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 t...
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 ...
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...
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 yo...
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 foun...
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 ...
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(....); ...
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 (eith...
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...
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 und...
... 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...
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 ou...
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 main...
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...
&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 c...
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 ...
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, ...
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,%[...
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 cod...
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; ...
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.