question
stringlengths
25
894
answer
stringlengths
4
863
The title maybe a little confusing.. so here is my attempt of explaining it: I have a command for my program: ``` c file1.txt > file2.txt ``` This command in the commandline takes the first file and pipes the output of the program (that is printed) to the second file. So im scanning a user message in: ``` printf(...
One way is to usestderrfor the information you don't want copied to the output file: ``` fprintf(stderr, "Enter a message:"); ```
I have a string that looks like this:{opt,2}{home,4}...I have to scan opt and 2 into a string and integer. I am doing this: ``` char str[40] = "{opt,2}{home,4}"; char s[20]; int *x; sscanf(str, "{%[^,],%[0-9]}", s,&x); ``` This segfaults. What is the right way?
To scan text like that, you don't need regex, you could just use simplescanfspecifiers. ``` char s[16]; /* The string in the pair */ int n; /* The integer in the pair */ int len; /* The length of the pair */ for (; sscanf(buf, "{%[^,],%d}%n", s, &n, &len) == 2; buf += len) { /* use str and n */ } `...
I understand that it is bad to return a local variable from a function which is stored in stack segment. What if I convert a char[] to const char *, then return it, is it considered as a good practice? If so, what segment will the const char * be stored in? something like this: ``` const char * foo() { char str[...
Casting toconst char*does nothing. It still points to thestrvalue, which becomes invalid when you return because it's on the stack. Adding theconstjust makes it so that whatever uses the return value can't modify the data pointed to by the pointer (unless they cast off the const). But since it points to a returned fu...
I have an array of char (string) that contain a decimal number. How do I convert it to unsigned char? ``` char my_first_reg[2]; memcpy( my_first_reg, &my_str_mymatch[0], 1 ); my_first_reg[1] = '\0'; // now my_first_reg contain reg number ... how to convert to unsigned char ```
To convertmy_first_reg[0]the ASCII character to its numeric value: ``` unsigned char value = my_first_reg[0] - '0'; ``` This works because digits in the ASCII table are sequential: ``` '0' = 0x30 = 48 '1' = 0x31 = 49 '2' = 0x32 = 50 '3' = 0x33 = 51 '4' = 0x34 = 52 ... '9' = 0x39 = 57 ``` ...
This question already has answers here:Purpose of while(1); statement in C(12 answers)Closed7 years ago. I saw in a lots of example a form of use for the while loop that I'm not sure it's ok to use in a code. ``` while(1){ // code lines if(condition){ break; } // code lines } ``` Is this ...
is this ok to use? what exactly Yes, and its commonly used in programming. while(1)is the same aswhile(true), basically a condition thats always true, ensuring thewhileloop never stops until you manually break out of it withbreak; There are many applications for this behavior. It could be that the exit condition is...
I am using sizeof function to calculate the size of a string. It should have printed 2.But why 4? Here is the code. ``` #include <stdio.h> #include <string.h> void main() { char *b = "ab"; printf(" %d ",sizeof(b)); //printf("%s ",b); } ```
Because on your platform pointers are 4 bytes. Or 32bit if you prefer. NOTE: Usingvoid main()as a signature formain()indicates that you are studyingcfrom an old book probably, be careful!
In C, while reading into a buffer from a socket file descriptor, how do I make the read stop if a delimiter is detected? Let's assume the delimiter is a '>' character. ``` read(socket_filedes, buffer, MAXSZ); /* stop if delimiter '>' is detected */ ```
You have two options here: Read a single byte at a time until you encounter a delimiter. This is likely to be very inefficient.Read in a full buffer's worth of data at a time, then look for the delimiter there. When you find it, save off the remaining data in another buffer and process the data you want. When you'...
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 code for solving arithmetic expression like:4+3-2*6*(3+4/2) For that I need to compare the ...
Use a lookup table. If using ASCII, it is just a 256 element table. You index it with the char.
I am trying to display...(three dots), but each dot then a second delay then a second dot then a second delay then a third dot. I tried this ``` for(int i = 0;i < 3;i++) { sleep(1); printf("."); sleep(1); } ``` But this just waits for 6 seconds and then prints the three dots all together but I don't want that. Is t...
Try: ``` #include <stdio.h> #include <unistd.h> int main() { for(int i = 0;i < 3;i++) { printf("."); fflush(stdout); sleep(1); } } ``` printf()prints tostdoutwhich is bufferred. Flush out the buffer after eachprintf(). << std::flush;is the C++ equivalent to this.
every time I run the program below in the following way:./a.out -a -bit runs properly. But if choose to run./a.out -a, I result in a segmentation fault (core dumped). Is there any way I can fix this? ``` int main(int argc, char *argv[]) { if (argc > 1) { if (strcmp(argv[1],"-a") == 0) {... ...
When you run it with./a.out -a, only one argument, then you should not do the checkstrcmp(argv[2],"-b"), because there is no third argument, and readingargv[2]would result in undefined behavior. You can fix it by adding an extra check before doing thestrcmp(argv[2],"-b"). ``` int main(int argc, char *argv[]) { ...
I am revisiting code that I wrote a while ago that does some math on large numbers. When I wrote the code, the lab had a few x86s that were split between 32 and 64 bits. My work was on UltraSPARCs, and I vaguely remember pulling this line of code from an Intel manual to be sure that the code was being used on a 64-b...
The bytes.byte 15and.byte 162represent theCPUIDinstruction.When it executes you get results inEAX,EBX,ECX, andEDX. These results will be stored in the array elements: ``` x[0] <- EAX x[1] <- EBX x[2] <- EDX x[3] <- ECX ```
I am learningC. I am starting to understand pointers and type casting. I am following along with some guides and examples and I ran across this declaration: ``` uint32_t *sp; ... *(uint32_t*)sp = (uint32_t)somevalue; ``` What is happening here? The first asterisk specifically is a mystery to me.
Breaking it down: ``` *(uint32_t*)sp ``` basically says to treatspas a pointer touint32_t((uint32_t *)is acast expression), and to dereference the result. So, ``` *(uint32_t*)sp = (uint32_t)somevalue; ``` means, "takesomevalue, convert it to typeuint32_t, and store the result to the thingsppoints to, and treat th...
I stumbled upon some code where thetypedefkeyword is in between the type and the alias name like in ``` int typedef INT; ``` It compiles in gcc and clang (live example). I am not very good in understanding standardese. So my question is: Is this standard conformant? Can I rely on compilers to support it?
Thetypedefkeyword is classified as a storage class specifier in C, though the standard explicitly remarks that that's for convenience in expressing the formal language syntax. It nevertheless follows thattypedefcan appear in exactly the same places that any other storage class specifier, such asexternorstatic, can ap...
In the code below, could somebody explain what the second argument is? is it a "constant pointer the data". Thanks
The second argument is a const pointer to a const data. ``` const uint8_t * const == uint8_t const * const uint8_t const * const == const pointer to const uint8_t ``` To help you, think of the backwards reading: int*- pointer to intint const *- pointer to const intint * const- const pointer to int etc. So in you...
The title maybe a little confusing.. so here is my attempt of explaining it: I have a command for my program: ``` c file1.txt > file2.txt ``` This command in the commandline takes the first file and pipes the output of the program (that is printed) to the second file. So im scanning a user message in: ``` printf(...
One way is to usestderrfor the information you don't want copied to the output file: ``` fprintf(stderr, "Enter a message:"); ```
Question about the 8-bit and 16-bit values. I have the function: ``` get( uint8 *temp ); ``` I will use it like this: ``` uint16 getTemp; get( (uint8*) &getTemp ); ``` Will this work or why not use a uint8 directly for getTemp and skip the typecasting here? Could it be a bigger address for the pointer in this cas...
The address size will remain the same and the address value as well. There are two issues however: assignment will modify only half of the variableit will work differently on little endian architecture (low 8 bits will be set) and big endian architecture (high 8 bits will be set).
This question already has answers here:I want this to crash, but it doesn't(4 answers)Closed7 years ago. ``` #include<stdio.h> #include<stdlib.h> int main() { int *a[10]; a[2] = (int*)malloc(sizeof(int)); a[2][3]=4; printf("%d", a[2][3]); return 0; } ``` I have given only the memory equivalent o...
That's because nothing is preventing you accessing arrays out of bound and this invokes undefined behavior. Any expected or unexpected behavior of program can be seen.
Say I want to multiplyxby(3/8). So I can get the result using shift operation as follows (The result should round toward zero): ``` int Test(int x) { int value = (x << 1) + x; value = value >> 3; value = value + ((x >> 31) & 1); return value; } ``` So I'll have4inTest(11)and-3inTest(-9). The probl...
How can I fix this? (overflow at some ranges) Divide by 8 first. For each multiple of 8, the result increases by 3, exactly. So all that remains is to figure out 3/8 of numbers -7 to 7, which OP'stest()can handle. Simplifications possible. ``` int Times3_8(int x) { int div8 = x/8; int value = div8*3 + Test(x%...
``` char *foo(char *dest, const char *src) { unsigned i; for (i=0; src[i] != '\0'; ++i) dest[i] = src[i]; dest[i] = '\0'; return dest; } ``` I know that the code is moving through both variable's arrays, and while it's doing that, it makes dest[] have the same character as src[] How can i do...
Simply ``` while (*src != '\0') *dst++ = *src++; *dst = '\0'; // Perhaps you will also need this! ``` Remember at the end of the loop thatdstis pointing to the end of the array not to the begining. And also copy the'\0'terminator, or you don't want to?
I want to have an array of arrays that store 2 items, so would this be the best way to do it? ``` char array[5][2]= {{"data1","1"}, {"data2","2"}, {"data3","3"}, {"data4","4"}, {"data5","5"}}; ``` and how would I store something in "data2","2" for examp...
A 2D char array won't work here, but an array of struct would suit your need: ``` struct string_pairs { char str1[10]; char str2[10]; } array[] = {{"data1","x"}, {"data2","x"}, {"data3","x"}, {"data4","x"}, {"data5","x"}}; ```
What is the asmjit equivalent ofmov eax,[ecx+0CC]? This is close:c.mov_ptr(x86::eax, x86::ptr(x86::ecx, 0x0CC)); but the arguments are wrong. Any ideas?
The answer is: a.mov(x86::eax, x86::ptr(x86::ecx, 0x0CC));
This question already has answers here:Undefined behavior and sequence points(5 answers)Sequence points and partial order(3 answers)Closed7 years ago. ``` #include <stdio.h> #include <string.h> int main() { int i=3,y; y=++i*++i*++i; printf("%d",y); } ``` The i value is initially getting incremented to 4.Then it...
It will execute like this;First it is considers like this,y = (++i * ++i) * ++i // so first i is incremented to 4 and again it will incremented to 5.So now first expression will executed like thisy = (5 * 5) * ++i; y = 25 * ++i;Now again i is incremented to 6 and final expression is like this,y = 25 * 6; y = 150;
Example: ``` int amount = 10050; printf("format_string", amount); // What should the format string look like to get $100.50 as the output? ``` Is it possible to tell theprintffunction that I would like to have a dot placed two digits from the right without doing anything like this: ``` int amount = 10050; printf("$...
You could convert it tofloat, divide by 100, and print it with a float format. ``` printf("$%.2f", ((double)amount)/100); ```
I've been studying therotatealgorithm, and came across a formula to normalize a negative number of rotations:n - (~r % n) - 1. I've been wondering how that's different ton - (abs(r) % n)or evenn - (-r % n). Does theNOTdo anything special that a basicabsdoesn't? Or just for performance?
Supposer == n. Or, in general,r % n == 0 Since-r % nis 0,n - (-r%n)isn. However,~ris-r - 1so-r % nisn - 1, andn - (~r%n) - 1is0. For any otherr, the two expressions have the same value. The range ofn - (-r % n)is[1...n]while the range ofn - (~r % n) - 1is the desired[0...n-1].
I'm curious, I'm programming inCon PuTTy, does anyone know how I can get rid of this warning? warning: ignoring return value of ‘realloc’, declared with attribute warn_unused_result [-Wunused-result] realloc(strp->data, nbytes); ``` ^ ``` Relevant code to the line it wants to 'warn' me about: ``` //If the previous...
The correct way to call realloc is something like this: ``` tmp = realloc(strp->data, nbytes); if (tmp == NULL) { // your realloc didn't work and strp->data still points to the // the original location return EMEMORY; } strp->data = tmp; ```
I'm porting an application that uses the Xbox controller to Linux. On windows, it essentially just usesXInputGetState()to read the state of the controller, so I'm looking for a replacement for that function on Linux. I see thatwine hasn't implementedXInputGetState(), but at the same time there are a large number of g...
You can either: use theSDL libraryuse the functions inlinux/joystick.hyourselffind some other library which abstracts (3) for you likethisor the one linked by user3716731. The (1-2) solutions are mainlyC, but so is the XInput API, so you probably can deal with it. I would probably go with number 1, because that app...
If I have a file that contains lines with float numbers like this: ``` 4.5 -3.2 3.3 5.62 0.56 3.231 5.632 -4.56 2 5.8212 4 6.7 ``` How can I read it line by line and splitting the numbers to save them in an array (they are separated by 1 tabulator). Thank you EDIT: I did the following and it works, thanks everyon...
Usesfgetsgo get a line of your file in a string. Than usesscanfto parse the float into variables.
Instead of2*i, I carelessly wrote2i: ``` int foo(int i) { 2i; return 2i; } ``` I expected the compiler to catch the error. But it did not. So is2ia valid statement in C? If so what does it do? Puzzled! I compiled using gcc version 5.3.0 and here is the assembly output: ``` .file "strange.c" .text ...
This is agccextension, and2iis the imaginary constant. So you can write a complex number like so: ``` #include <complex.h> _Complex x = 4 + 5i; ```
How do I return a double without gettingrounded: ``` int function() { double d = 5.894; printf("d=%f\n", d); return d; } int main() { double d = function(); printf("d=%f\n", d); return 0; } ``` This gives me ``` d=5.894000 d=5.000000 ``` What am I missing here?
Your function returns ٰintit must returndouble Change ``` int function() ``` to ``` double function() ```
I am using c-icap to modify HTTP transactions. According to the documentation. I should be able to do so by using the following functions. ``` int ci_http_response_create ( ci_request_t * req, int has_reshdr, int has_body ) ``` http://www.firefly.kutc.kansai-u.ac.jp/~k843966/c-icap/doc/group__HTTP.ht...
ci_http_response() is not for "modify" but "create". if you want to modify service_io() or end_of_data()
Instead of2*i, I carelessly wrote2i: ``` int foo(int i) { 2i; return 2i; } ``` I expected the compiler to catch the error. But it did not. So is2ia valid statement in C? If so what does it do? Puzzled! I compiled using gcc version 5.3.0 and here is the assembly output: ``` .file "strange.c" .text ...
This is agccextension, and2iis the imaginary constant. So you can write a complex number like so: ``` #include <complex.h> _Complex x = 4 + 5i; ```
How do I return a double without gettingrounded: ``` int function() { double d = 5.894; printf("d=%f\n", d); return d; } int main() { double d = function(); printf("d=%f\n", d); return 0; } ``` This gives me ``` d=5.894000 d=5.000000 ``` What am I missing here?
Your function returns ٰintit must returndouble Change ``` int function() ``` to ``` double function() ```
I am using c-icap to modify HTTP transactions. According to the documentation. I should be able to do so by using the following functions. ``` int ci_http_response_create ( ci_request_t * req, int has_reshdr, int has_body ) ``` http://www.firefly.kutc.kansai-u.ac.jp/~k843966/c-icap/doc/group__HTTP.ht...
ci_http_response() is not for "modify" but "create". if you want to modify service_io() or end_of_data()
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 What is the purpose of condition variables in Monitors? Why really do we need the condition variables? It m...
Acondition variableis basically acontainer of threadsthat are waiting for a certain condition. Monitors provide a mechanism for threads to temporarily give up exclusive access in order to wait for some condition to be met, before regaining exclusive access and resuming their task.Reference linkhere. Conceptually a co...
So I have this code: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> char field1[45]; char field2[444]; char *fields[] = { field1, field2 }; int main (int argc, char *argv[]) { sprintf(fields[0], "hello\n"); printf(fields[0]); } ``` I have no need for accessing the fields using field1 and ...
You could write: ``` char *fields[] = { (char[45]) { 0 }, (char[444]) { 0 } }; ``` I'd suggest against using this design though as it makes it difficult to perform a check that you won't be overrunning the buffer.
I'm still fairly new to C programming so sorry for this really basic question. Can anyone tell me what this particular code does part by part? What does->after the stack do? ``` int StackInit(struct Stack *stack) { stack->currentItemIndex = -1; stack->initialized = true; return SUCCESS; } ```
->is the structure dereference operator. The left side takes a pointer to astruct, and the right side is a struct member. It dereferences the pointer, then gets the named member. So for example,stack->initializedis equivalent to(*stack).initialized.
I am trying to make C code, that will copy string into matrix of type double so i need to take strings from one of two inputs: stdin and .txt file. Is that possible to make line: ``` while(fgets(tmpbuffer, MAXLEN, stdin) != NULL) ``` and ``` while(fgets(tmpbuffer, MAXLEN, filepointer) != NULL) ``` working without ...
Sure! Consider just wrapping the whole thing in a function that takes aFILE*parameter: ``` void do_something(FILE* fp) { while (fgets(tmpbuffer, MAXLEN, fp) != NULL) { ... } } ``` Now, you can calldo_something(stdin)ordo_something(filepointer)as appropriate.
So I was given a struct: ``` struct Xxx { struct Yyy{...}; Yyy **yyys; // matrix of yyys }; ``` I am confused about how pointer to pointer is related to a matrix? And how can I initialize a newYyyand a newXxx?
The first level pointer would point to an array of pointers, and each second level pointer would point to an array ofYyy. They can be set up as follows: ``` struct Yyy **makeMatrix(int rows, int cols) { int i; struct Yyy **result = malloc(rows*sizeof(struct Yyy *)); for (i = 0; i < rows; i++) { r...
I have an array like ``` int outer[4][3] = { { 1, 2, 3 }, { 2, 3, 5 }, { 1, 4, 9 }, { 10, 20, 30 } }; ``` and I would like to get a pointer/array for the n-th one-dimensional array insideouter, something like ``` void foo () { printf("%d %d %d\n", outer[1][0], outer[1][1], outer[1][2]); int ...
For pointer to array, declareinneras a pointer to an array of 3int ``` int (*inner)[3] = &outer[1]; ``` If you want a pointer to first element of arrayouter[1]then ``` int *inner = outer[1]; ``` will do the job. You can also do ``` int *inner = &outer[1][0]; ```
Trying to test precision making a sum from 1 to a million but my output keeps coming out as inf. ``` #include <stdio.h> int main() { float x=0.0 ; double y =0.0; int i; for(i=1; i<100000; i = i+1) { x=(float) x+( 1.0f/(3.0f*(float)(i*i))); y=(double) y+ ( 1.0/(3.0*(double)(i*i))); } printf("Natural Order \n"); p...
The expressioni^2meansi BITWISE-XOR 2, not repeated multiplication. Some values ofi^2are zero - wheni=2- which means you sometimes divide by zero. Replace(i^2)with(i*i).
I think theTail-recursiveis really helpful in functional programming language. How about C? Does C language or compiler supporttail call elimination?Do the program create new stack frame for the new call? From wiki: Tail calls can be implemented without adding a new stack frame to the call stack. Most of the frame ...
Tail-recursive is usually used in functional languages because it's natural way to implement loops on structures which are actually not that much recursive in procedural languages. Therefore procedural languages don't need it. However, it's up to compiler to decide if it finds such optimization.
So I have this struct: ``` typedef struct type { int a; char* b; } type; ``` In themainprogram, I make 2 arrays of these structs, and usemalloc(): ``` type *v; type *w; v=malloc(50*sizeof(type)); w=malloc(50*sizeof(type)); ``` Now I if I want to free these arrays of structs is it correct to do: ``` fr...
Yes, it is correct. You only need to pass the pointer returned bymalloc()and family. You don't need to mention / supply the size of the allocated memory while callingfree(). The size will be taken care automatically (by OS). FWIW, in case, you have allocated dynamic memory to the members, likew[i].bs, you need tofr...
I'm very new to Tizen and also to C. I want to develop a nativ Tizen app for the wearable Samsung Gear S2. I opened a Basic standard Projekt and wanted to run it on my watch. In the console was at the end the error: "Cannot find binary file(/Users/yvonne/worksspace/HelloW/Debug/hellow)". I found this file. It definit...
I can't say where the error does came from, but now it is fixed. My colleague said, that it could be, because the clock used the WLan to be connected to my smartphone and not to the laptop, although Eclipse said it is connected. But thats only a theory.
``` #include<stdio.h> int main() { int num[]={24, 34, 12, 44, 56, 17},i; for(i=0;i<=5;i++) { printf("%d\n",i[num]); printf("%d\n",num[i]); printf("%d\n",*(num+i)); } return 0; } ``` // Are all three formats allowed inCto print an array and which is the fastest one?
All are same ``` num[i] = *(num + i) = i[num] ``` When it comes to which is faster the compiler performs the same operation in all the cases so it is same.
I was interview in company and I was asked a question, question was bit strange so wanted to ask with expert guys. The question suppose I have function which returns bool type. Let us say this : ``` public bool func(int param) { bool retVal; // here is some algorithm which as a result either set the retVal to fa...
I think your code would be like this: ``` public bool func(int param) { bool retVal; return !retVal; } ```
I have an array like ``` int outer[4][3] = { { 1, 2, 3 }, { 2, 3, 5 }, { 1, 4, 9 }, { 10, 20, 30 } }; ``` and I would like to get a pointer/array for the n-th one-dimensional array insideouter, something like ``` void foo () { printf("%d %d %d\n", outer[1][0], outer[1][1], outer[1][2]); int ...
For pointer to array, declareinneras a pointer to an array of 3int ``` int (*inner)[3] = &outer[1]; ``` If you want a pointer to first element of arrayouter[1]then ``` int *inner = outer[1]; ``` will do the job. You can also do ``` int *inner = &outer[1][0]; ```
Trying to test precision making a sum from 1 to a million but my output keeps coming out as inf. ``` #include <stdio.h> int main() { float x=0.0 ; double y =0.0; int i; for(i=1; i<100000; i = i+1) { x=(float) x+( 1.0f/(3.0f*(float)(i*i))); y=(double) y+ ( 1.0/(3.0*(double)(i*i))); } printf("Natural Order \n"); p...
The expressioni^2meansi BITWISE-XOR 2, not repeated multiplication. Some values ofi^2are zero - wheni=2- which means you sometimes divide by zero. Replace(i^2)with(i*i).
I think theTail-recursiveis really helpful in functional programming language. How about C? Does C language or compiler supporttail call elimination?Do the program create new stack frame for the new call? From wiki: Tail calls can be implemented without adding a new stack frame to the call stack. Most of the frame ...
Tail-recursive is usually used in functional languages because it's natural way to implement loops on structures which are actually not that much recursive in procedural languages. Therefore procedural languages don't need it. However, it's up to compiler to decide if it finds such optimization.
So I have this struct: ``` typedef struct type { int a; char* b; } type; ``` In themainprogram, I make 2 arrays of these structs, and usemalloc(): ``` type *v; type *w; v=malloc(50*sizeof(type)); w=malloc(50*sizeof(type)); ``` Now I if I want to free these arrays of structs is it correct to do: ``` fr...
Yes, it is correct. You only need to pass the pointer returned bymalloc()and family. You don't need to mention / supply the size of the allocated memory while callingfree(). The size will be taken care automatically (by OS). FWIW, in case, you have allocated dynamic memory to the members, likew[i].bs, you need tofr...
I'm very new to Tizen and also to C. I want to develop a nativ Tizen app for the wearable Samsung Gear S2. I opened a Basic standard Projekt and wanted to run it on my watch. In the console was at the end the error: "Cannot find binary file(/Users/yvonne/worksspace/HelloW/Debug/hellow)". I found this file. It definit...
I can't say where the error does came from, but now it is fixed. My colleague said, that it could be, because the clock used the WLan to be connected to my smartphone and not to the laptop, although Eclipse said it is connected. But thats only a theory.
``` #include<stdio.h> int main() { int num[]={24, 34, 12, 44, 56, 17},i; for(i=0;i<=5;i++) { printf("%d\n",i[num]); printf("%d\n",num[i]); printf("%d\n",*(num+i)); } return 0; } ``` // Are all three formats allowed inCto print an array and which is the fastest one?
All are same ``` num[i] = *(num + i) = i[num] ``` When it comes to which is faster the compiler performs the same operation in all the cases so it is same.
I am building an executable and a.sofile using another.so ``` mylib.so: mylib.o ld -shared -o mylib.so packer.o mylib.o -ldl -L../lib -lcustombuild server: server.o packer.o gcc packer.o server.o -o server -L../lib -lcustombuild ``` The filelibcustombuildis in dir lib one level above current dir (i.e. ../l...
-L only tells the linker where to find the link-time library. The .so file still needs to be known to the run-time library loader. So you either need to use something like theLD_LIBRARY_PATHenvironment variable, or therpathlinker options, to tell the loader where to find your .so file, or put the .so file into one of...
I'm just starting with MPIR and I'm executing this code: ``` mpf_t t2; mpf_init2(t2, 10000); mpf_set_d(t2, 5.999999999999); gmp_printf("fixed point mpf %.40Ff", t2); ``` The output is: ``` fixed point mpf 5.9999999999989999110994176589883863925934 ``` This seems highly innacurate, although I've set the precision t...
5.999999999999is adouble. Now, adoublecan't actually hold the value 5.999999999999, but it can hold the value 5.9999999999989999110994176589883863925934 which is almost exactly the same - and you'd never notice the difference, right? Usempf_set_strinstead: ``` mpf_set_str(t2, "5.999999999999", 10); ``` (10 is the b...
It is my understanding thatvoid **, is avoidpointertoa pointer. So then what does the third dereference operator do? We are Dr referencing the pointer that we are pointing to?
Avoid**is a pointer to avoid*.void**isnot special in any way- it's just a pointer to something, where that something happens to be avoid*. (void**)somethingcastssomethingto avoid**.*somethingdereferencessomething.Therefore,*(void**)somethingcastssomethingto avoid**, and then dereferences it (yielding avoid*).
Before I define a macro function, I can check that it doesn't already exist(this avoids overwriting a previous definition). I can implement the check and definition like this: ``` #ifndef MACRO(X) #define MACRO(X) FUNCTION(X) #endif ``` Or like this: ``` #ifndef MACRO #define MACRO(X) FUNCTION(X) #endif ``` Both ...
Without. The standard specifies that#ifndefis equivalent to#if !defined, and that the argument todefinedmust be a (possibly parenthesized)identifier. You can't have parens in an identifier, sodefined MACRO(X)is not an allowed form. This use ofdefinedcauses undefined behaviour, so it is not portable.
I've seen these two different ways to cast anintto adoublein C: ``` double double_var = (double) int_var; double double_var = double(int_var); ``` What's the difference between these two methods? When should I use one over the other?
AsJonathan Lefflerstated, the first is from C and the second from C++: The first one is a C-style cast; the second is the instantiation of adoubleby passing the constructor anintvalue. So the second isn't really a cast but the creation of a new instance(So it is more C++ than C). If you only do someCthen using cons...
I am using cpplint with Syntastic on VIM, however I am not able to use cpplint for C files. I enabled cpplint for cpp files using the following line in .vimrc file: ``` let g:syntastic_cpp_cpplint_exec = 'cpplint' ``` I tried using the same for c: ``` let g:syntastic_c_cpplint_exec = 'cpplint' ``` But it does not...
'cpplint' isn't included in the list of syntax checkers for C which are used by Syntastic:https://github.com/scrooloose/syntastic/wiki/C. You can use only avrgcc, checkpatch, clang_check, clang_tidy, cppcheck, gcc, make, oclint, pc_lint, sparse, splint for C.
I have the following problem when using memcpy: Suppose that an hexadecimal data must be copied in binary, e.g.: 203800000E820006, then apply the following instruction: ``` unsigned char buffer[8]; memcpy(buffer,"\x20\x38\x00\x00\x0E\x82\x00\x06",8); ``` However, when I write the data in binary, it only prints the ...
The buffer you have is not a string. You can't treat it like one by passing it to functions expecting a string such asstrcat,strcpy,strcmp, or the%sformat specifier ofprintf. You have an array of characters, so print them as such: ``` int i; for (i=0;i<sizeof(buffer);i++) { printf("%02hhX ", buffer[i]); } print...
I am reading a line from a file and I do not know the length it is going to be. I know there are ways to do this with pointers but I am specifically asking for just a plan char string. For Example if I initialize the string like this: ``` char string[300]; //(or bigger) ``` Will having large string values like this ...
Any hard coded number is potentially too small to read the contents of a file. It's best to compute the size at run time, allocate memory for the contents, and then read the contents. SeeRead file contents with unknown size.
``` calc(mesh, prob_data, &cells_fd[crr], species, cr); ``` I'm looking at a function call in a code, and I just wanted to verify if I am looking this correct. In the above call, I am interested in the argument cells_fd[crr]. Does the "&" in front of the argument mean that cells_fd[crr] is being passed into the func...
cells_fd[crr]is equivalent to*(cells_fd + crr), and thus&cells_fd[crr]is equivalent to&*(cells_fd + crr)which is(cells_fd + crr)as the dereference and address operators cancel out. Thus, your interpretation is correct in that&cells_fd[crr]passes the address ofcells_fd[crr], so thatcalc()may overwrite the contents, bu...
Before I define a macro function, I can check that it doesn't already exist(this avoids overwriting a previous definition). I can implement the check and definition like this: ``` #ifndef MACRO(X) #define MACRO(X) FUNCTION(X) #endif ``` Or like this: ``` #ifndef MACRO #define MACRO(X) FUNCTION(X) #endif ``` Both ...
Without. The standard specifies that#ifndefis equivalent to#if !defined, and that the argument todefinedmust be a (possibly parenthesized)identifier. You can't have parens in an identifier, sodefined MACRO(X)is not an allowed form. This use ofdefinedcauses undefined behaviour, so it is not portable.
I've seen these two different ways to cast anintto adoublein C: ``` double double_var = (double) int_var; double double_var = double(int_var); ``` What's the difference between these two methods? When should I use one over the other?
AsJonathan Lefflerstated, the first is from C and the second from C++: The first one is a C-style cast; the second is the instantiation of adoubleby passing the constructor anintvalue. So the second isn't really a cast but the creation of a new instance(So it is more C++ than C). If you only do someCthen using cons...
I am using cpplint with Syntastic on VIM, however I am not able to use cpplint for C files. I enabled cpplint for cpp files using the following line in .vimrc file: ``` let g:syntastic_cpp_cpplint_exec = 'cpplint' ``` I tried using the same for c: ``` let g:syntastic_c_cpplint_exec = 'cpplint' ``` But it does not...
'cpplint' isn't included in the list of syntax checkers for C which are used by Syntastic:https://github.com/scrooloose/syntastic/wiki/C. You can use only avrgcc, checkpatch, clang_check, clang_tidy, cppcheck, gcc, make, oclint, pc_lint, sparse, splint for C.
I have the following problem when using memcpy: Suppose that an hexadecimal data must be copied in binary, e.g.: 203800000E820006, then apply the following instruction: ``` unsigned char buffer[8]; memcpy(buffer,"\x20\x38\x00\x00\x0E\x82\x00\x06",8); ``` However, when I write the data in binary, it only prints the ...
The buffer you have is not a string. You can't treat it like one by passing it to functions expecting a string such asstrcat,strcpy,strcmp, or the%sformat specifier ofprintf. You have an array of characters, so print them as such: ``` int i; for (i=0;i<sizeof(buffer);i++) { printf("%02hhX ", buffer[i]); } print...
I am reading a line from a file and I do not know the length it is going to be. I know there are ways to do this with pointers but I am specifically asking for just a plan char string. For Example if I initialize the string like this: ``` char string[300]; //(or bigger) ``` Will having large string values like this ...
Any hard coded number is potentially too small to read the contents of a file. It's best to compute the size at run time, allocate memory for the contents, and then read the contents. SeeRead file contents with unknown size.
``` calc(mesh, prob_data, &cells_fd[crr], species, cr); ``` I'm looking at a function call in a code, and I just wanted to verify if I am looking this correct. In the above call, I am interested in the argument cells_fd[crr]. Does the "&" in front of the argument mean that cells_fd[crr] is being passed into the func...
cells_fd[crr]is equivalent to*(cells_fd + crr), and thus&cells_fd[crr]is equivalent to&*(cells_fd + crr)which is(cells_fd + crr)as the dereference and address operators cancel out. Thus, your interpretation is correct in that&cells_fd[crr]passes the address ofcells_fd[crr], so thatcalc()may overwrite the contents, bu...
``` int main() { short int a[4] = {1,1, [3] = 1}; int *p = (int*)a; printf("p: %p %d \n ", p, *p); printf("p+1: %p %d\n", (p +1), *(p+1)); } ``` why does *p = 65537 and *(p+1) = 65536?
Well, to understand why*Pis 65537 and*(p+1)is 65536 lets take a look at the memory: ``` 00000001 00000000 | 00000001 00000000 | 00000000 00000000 | 00000001 00000000 ``` I've split a byte by a space and a singleshort intby a |. Now we cast the ptr to aint*and it now takes four bytes instead of two: ``` 00000001 000...
This question already has answers here:How does the C offsetof macro work? [duplicate](4 answers)Closed7 years ago. What does ((struct name *)0)->member) do in C? The actual C statement I came across was this: ``` (char *) &((struct name *)0)->member) ```
This is a trick for getting the offset ofstruct's member calledmember. The idea behind this approach is to have the compiler compute the address ofmemberassuming that the structure itself is located at address zero. Usingoffsetofoffers a more readable alternative to this syntax: ``` size_t offset = offsetof(struct n...
Guys gave me their library:libA.aandlibB.a. Also, I have header files:header_A.handheader_B.h. I need to add them to myMakefile. I've added this: ``` INCLUDES = -I/home/me/lib_from_guys/include LIBS = -L/home/me/lib_from_guys/libraries CFLAGS = -llibA -llibB hello: $(CC) $(INCLUDES) $(LIBS) $(CFLAGS) $< -o $@ ``...
This has been a standard behavior in C for many, many years. The-lXoption will automatically prompt the linker to look for something namedlibX, notX. So, yes, you always exclude thelibportion of the name to-l.
I have two arrays of decimals with the same number of indexes in each. How can I right-align the LSB in each column like this?: ``` 359230595 10 1746442051 8 1170647010 8 202212421 7 800051251 7 1112147574 8 1135948848 8 3367006 5 3869426816 7 ``` Either using printf, or even better would be ge...
I feel confident that this has been asked and answered before. To make it easy on you, however... printfhas an alignment operation that you can use. You can find it if you read the manual page. For example: ``` printf("%*d %*d\n", 10, x, 10, y); ``` Note that the*has been inserted where you would typically find ...
Is there a way to move back the line just read after callingfgets? I know when you usefgetcyou can doungetc. Is there a way I can do something similar forfgets? The reason I am asking this is because I have anfgetsin an if statment and I dont want thefgetsto be actually executed I just want to know whether it is goin...
There is no fungets. Youcansave a position in an input stream usingftell, and reposition to that point usingfseek. It is useful for files, but not reading from the terminal (i.e., the standard input). Further reading fgetpos, fseek, fsetpos, ftell, rewind - reposition a stream12.18 File Positioning(The GNU C Libra...
I've been into this problem lately, and I just ca't figure out how. I wan't an output to be like this: ``` Enter Number: 5 1 5 2 4 3 3 4 2 5 1 ``` And here's my code: ``` int c; int n; int i; printf("Enter Number Count Limit: "); scanf("%d",&n); for (c=1;c<=n;c++) { for (i=c;i<0;i--) ...
I do not thing there's a reason to use 2 for loops. I would go with something like this: ``` for (c=0; c<n; c++){ printf("%d\t%d\n", c+1, x-c); } ```
I need to get the path of %APPDATA% in my c program, to save a file in%APPDATA%\myprogram\How can I do that ?
You should be able to get that information throughgetenv, here is an example. ``` #include<stdio.h> #include<stdlib.h> int main () { char * app_data; app_data= getenv ("APPDATA"); if (app_data!=NULL) printf ("The appdata path is: %s",app_data); return 0; } ```
I have a x86_64 machine and want to compile for a machine, which has i586 arch. I installed:libc6-dev-x32andlibc6-dev:i386 Then I tried to compile a simple hello world like this: ``` gcc -m32 -march=i586 -mcpu=i586 test.c -o test -static ``` It works on my machine but on the target I get the illegal instruction er...
You statically link against the glibc of your host system, which makes use of theCMOV*-instructions. So compiler switches won't help. One option is to link againstdietlibc: Install the packagedietlibc-dev:i386Link against it:diet gcc -m32 -march=i586 -mcpu=i586 test.c -o test -static Now your binary should not incl...
I want a way to check when the last line of the file is being read. Is there a way I can do this?
Yes. Attempt to read another line. If that yields an end-of-file condition, then the line you read before was the last line. There are kinda-sorta-maybe ways to get similar results without trying to read another line but they only work under specific conditions and are prone to race conditions. If this is too complex...
I have a number of macros in the form ``` #define F(A,B) Some function of A and B ``` and for readability I would like to define arguments for these macros e.g. ``` #define C A,B ``` so that I can say ``` F(C) ``` but the preprocessor tries to expand F before C and complains that F needs 2 arguments. Is there ...
You can use an intermediate macro that takes a variable number of arguments: ``` #define F1(A,B) #define F(...) F1(__VA_ARGS__) #define C A,B int main(void) { F(C) F(1,2) return 0; } ``` This should compile. You will still get a compilation failure if you pass more or less than two arguments, or argum...
This question already has answers here:using assembly code inside Objective c program (Xcode)(1 answer)How do I do inline assembly on the IPhone?(5 answers)Closed7 years ago. This question is for educational purpose only. I want to know the way to include an inline assembly code (I am using Xcode, with i7 Intel proce...
Read the clang manuals (clang is the compiler used by xcode). E.g., see here:http://clang.llvm.org/compatibility.html#inline-asm
I created a simple function titled GetInput which prints "hello" if the user inputs "y" When I compile the program, and then enter "y" the program doesn't print "hello" unless I type in a couple of random characters then press enter. The image links are below: https://i.stack.imgur.com/dkwsq.png [1. The compiled c...
For: scanf("%c\n", &c); Remove the '\n' and it should work fine. Change to: scanf("%c", &c);
I'm trying to convert a piece of code from Java to C and I got stuck here, trying to get a character at each position. ``` char ch; line += ' '; while (pos < line.length()) { ch = line.charAt(pos); ... ``` is there anything similar in C to convert the linech = line.charAt(pos)from java to C?
in C, the easiest way to get a char from an array of character (I.E. a string) given the variables in your posted code, ``` char ch; line += ' '; while (pos < line.length()) { ch = line.charAt(pos); ... ``` assuming that the string is terminated with a NUL byte ('\0')assuming there is room in theline[]array...
I created a simple function titled GetInput which prints "hello" if the user inputs "y" When I compile the program, and then enter "y" the program doesn't print "hello" unless I type in a couple of random characters then press enter. The image links are below: https://i.stack.imgur.com/dkwsq.png [1. The compiled c...
For: scanf("%c\n", &c); Remove the '\n' and it should work fine. Change to: scanf("%c", &c);
I'm trying to convert a piece of code from Java to C and I got stuck here, trying to get a character at each position. ``` char ch; line += ' '; while (pos < line.length()) { ch = line.charAt(pos); ... ``` is there anything similar in C to convert the linech = line.charAt(pos)from java to C?
in C, the easiest way to get a char from an array of character (I.E. a string) given the variables in your posted code, ``` char ch; line += ' '; while (pos < line.length()) { ch = line.charAt(pos); ... ``` assuming that the string is terminated with a NUL byte ('\0')assuming there is room in theline[]array...
I'd like to write a low-level logging function that would look like: ``` DO_DBG("some string", val1, val2) ``` What I want it to do, is to store the pointer to the string rather than a copy of the string, for performance reasons. This assumes that the string is a read-only literal. To prevent people having to de...
You could use the automatic literal string concatenation to your advantage: ``` #define DO_DBG(s, a, b) _DO_DBG("" s, a, b) ``` And implement your real macro as_DO_DBG.
I have those 2 structures and that simple init function. ``` typedef struct ls{ int k; struct ls *next; } NOD; typedef struct h{ int k; NOD *lis; struct h *next; } hash; ``` My init function looks like this: ``` hash *init_h(hash *h){ h=NULL; h->lis=NULL; return h; } ``` In main: ...
``` hash *init_h(hash *h){ h=NULL; // h is set to NULL h->lis=NULL; // then you dereference NULL.... crash return h; } ``` You can't dereference a NULL pointer
``` printf("%s", 0x216f6c6c6548); // "Hello!" reversed ``` It should print "Hello!" but it doesn't. I expected the same result of: ``` long long ll = 0x216f6c6c6548; printf("%s", &ll); ``` or ``` printf("%s", "Hello!"); ``` Is it possible to print a number as a string? UPDATE Is it possible to printdirectlya nu...
You have to extract the characters from the number: ``` print_ull_as_str (unsigned long long ll) { while (ll != 0) { printf("%c", (char )(ll & 0xffu)); ll >>= 8; } } ```
Why I'm getting compiling error in following code? and What is the difference betweenint (*p)[4],int *p[4], andint *(p)[4]? ``` #include <stdio.h> int main(){ int (*p)[4];// what is the difference between int (*p)[4],int *p[4], and int *(p)[4] int x=0; int y=1; int z=2; p[0]=&x; p[1]=&y; p[2]=&z;...
There is no difference between ``` int *p[4]; ``` and ``` int *(p)[4]; ``` Both declarepto be an array of 4 pointers. ``` int x; p[0] = &x; ``` is valid for both. ``` int (*p)[4]; ``` declarespto be a pointer to an array of 4ints. You can get more details on the difference between ``` int *p[4]; int (*p)[4];...
My code ``` #include <stdio.h> #define FILENAME "m_6" int main() { float f; FILE * file; // read values if ( ! (file = fopen(FILENAME,"r"))) return 1; while ( fread( &f, sizeof(float), 1, file )) printf("%e\n", f); fclose( file ); } ``` When I compile with gccgcc -c n1.c -o n1 and tr...
gcc-ccompiles source files without linking. Cancel-cfrom from command.
I'm trying to access the next or previous element when calling va_arg in an argument list. "n" is actually the length of the argument list. ``` va_list pointer; va_start(pointer, n); int temp = va_arg(pointer, int); ... if(temp < va_arg(pointer, int))... ... void va_end(va_list pointer) ``` Is it actually possible...
The "list" you get from theva_*"functions" (they are most often implemented as preprocessor macros) is a part of the stack, and as a true stack you can only "pop" values of it. So no you can't "swap" values, or go backwards. You can't even "push" values, only "pop". If you want to swap values, you have to get both v...
``` #include<stdio.h> int main() { int a; a=100000000; printf("%d",a); return(0); } ``` //why value of a gets printed even if it larger than the range of int?
because range of int type in c is from -32767 to 32767 You have false assumptions there. The range of typeintisnotfixed. An int is not necessarily 16 bits. The C standard doesn't define a fixed range forint. It requires a conforming implementation supportsat leastthe range -32767 to 32767 forint. But an implementat...
Is operator->allowed to use in C instead of.? Does its availability depend on compiler we are using? Is->operator available in the last C standard or does it come from the C++ standard? How those two differ?
In C,c->mis equivalent to(*c).m. The parentheses are necessary since.has a higher precedence than*. Any respectable compiler will generate the same code. In C++, unless->or*isoverloaded, the equivalence is as above.
``` #include<stdio.h> int main() { int a; a=100000000; printf("%d",a); return(0); } ``` //why value of a gets printed even if it larger than the range of int?
because range of int type in c is from -32767 to 32767 You have false assumptions there. The range of typeintisnotfixed. An int is not necessarily 16 bits. The C standard doesn't define a fixed range forint. It requires a conforming implementation supportsat leastthe range -32767 to 32767 forint. But an implementat...
Is operator->allowed to use in C instead of.? Does its availability depend on compiler we are using? Is->operator available in the last C standard or does it come from the C++ standard? How those two differ?
In C,c->mis equivalent to(*c).m. The parentheses are necessary since.has a higher precedence than*. Any respectable compiler will generate the same code. In C++, unless->or*isoverloaded, the equivalence is as above.
Is operator->allowed to use in C instead of.? Does its availability depend on compiler we are using? Is->operator available in the last C standard or does it come from the C++ standard? How those two differ?
In C,c->mis equivalent to(*c).m. The parentheses are necessary since.has a higher precedence than*. Any respectable compiler will generate the same code. In C++, unless->or*isoverloaded, the equivalence is as above.
I already have gcc version 6.1.0 installed on my computer thanks to XCode: ``` Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn) Target: x86_64-apple-darwin15.0.0 Thread model: posix...
Homebrew doesn't have recipes for every individual minor version of GCC, only for the major versions like 4.4. Conveniently, though, 4.4.7 is the most recent version of GCC 4.4, so you're fine. Runbrew install gcc44; the compiler will be installed asgcc-4.4.
I have started working on a KMD project for exercise. I have opened an empty KMDF project and started writing the km component. Now I want to add a User Mode component.. Do I need to open a new project that contains both parts or is there a way to add user mode component on a KMDF project?
After advising someone experienced with driver development in visual studio I came to this answer: The user mode component has to be separate from the kernel mode component. In Visual Studio it is done easily with adding another project to the same solution (no need to create a new solution). Then, the kernel mode com...
I'm compiling a c application with gcc that uses gtk3 I use thegtk_window_set_icon()to set icon, and it shows on the window and the taskbar. I want to know how can I compile my application so that the file .exe itself has the same icon. (i.e. when I open up the folder where the .exe is located I would see the icon o...
In fact GTK has nothing to do with. GTK is a library for graphicaluser interface. But here what you want is to manage yourexectuable file. Since you're on Windows, this is achived by using aresource file. For an icon you can have something like this (name itresource.rcfor example): ``` 1 ICON test.ico ``` Then with...
I've tried to read whole file withfgets, and when I use it in while loop, it never ends. When I usefscanfeverything works fine. ``` while((fscanf(f,"%s",ime)) != EOF) { fputs(ime,p); fputc('\n',p); } ``` But this doesn't work, how to fix it? I get infinite loop ``` while((fgets(ime,100,f)) != EO...
Is it really this hard to read thedocumentation? char *fgets(char *str, int n, FILE *stream)On success, the function returns the same str parameter. If the End-of-File is encountered and no characters have been read, the contents of str remain unchanged and a null pointer is returned. If an error occurs, a null poi...
Hello I am writing a program in C. I start it like that after compilation. ``` /a.out <source.txt >output ``` I want all messages to be printed to the output.txt. However I would like to send errors to the console, not to the file. The problem is when i use this statement in my code: ``` freopen( "errors.txt", "w",...
By default thestdoutandstderrare together routed to your console. However you can redirect the error stream to a file with the help of the following form of your command line: ./a.out2>logfile.log. In that case thestdoutwill still come to the console, butstderrwill go to the file.
Are the following two methods of creating arrays in C equivalent? ``` int main( void ) { int *array = malloc(sizeof(int) * 10); int array2[10]; } ``` My thought is that method two is syntactic sugar for method one, but I'm not sure. Also, what do array and array2 contain after these declarations? I know arr...
They are not remotely equivalent. This: ``` int *array = malloc(sizeof(int) * 10); ``` will allocate a block of memory of the heap, and leave you with a pointer to that memory. This: ``` int array2[10]; ``` will allocate some memory on the stack. Read this excellent answer about stack and heap memory:What and whe...
``` #include <stdio.h> #include <conio.h> const int MAX = 3; int main() { int var[] = { 10, 100, 200 }; int i, *ptr[MAX]; for (i = 0; i < MAX; i++) { ptr[i] = &var[i]; /* assign the address of integer. */ _getch(); } for (i = 0; i < MAX; i++) { printf("Value of var[%d]...
The definitionint *ptr[MAX];whereMAXis not a compile time constant expression is supported since C99 for automatic variables. Even defined as aconst int MAX = 3,MAXis not considered a compile time constant in C. Your version of Visual Studio does not seem to support this syntax, but the online compiler at tutorialsp...
I am writing an embedded application in plainC99in Visual Studio with VisualGDB and Resharper c++. The Resharper website states that it fully supportsC99. But if I have a typedef struct like this ``` typedef struct { int Bar;} Foo_t; ``` And some function that return this struct ``` Foo_t Foo(void){ return (Foo...
We are sorry for the inconvenience. I've created an issue in YouTrack about it:https://youtrack.jetbrains.com/issue/RSCPP-15938You can follow this request and vote for it.