question
stringlengths
25
894
answer
stringlengths
4
863
In the following code: ``` i = x % b; ``` Is the modulo operation faster whenbis a power of 2, even ifbis not known at compile time (i.e. even though the compiler will not optimize this into a bitwise and because it does not know thatbwill be a power of 2)? If not, how can I force such an optimization if I know thatbwill always be a power of 2? EDIT: I guess what I was really asking in the first part of the question is whether thedivlinstruction (or similar) itself will run faster for powers of 2.
Whether it is faster will clearly necessarily be system-dependent. If you knowxto be non-negative, andbto be a power of two, you can usex & (b - 1).
The following statements in C: ``` iONE >>= iShift; iONE &= 0xffefffff; iONE |= (((((long)(*temp & 0x7f) - 65) << 2) + iShift + 1023) << 20) | (iTWO & 0x80000000); ``` Is there something likeshr=,And=andOr=in Delphi. Is there more appropriate way than literal porting, especially the third statement.
Those are basically two operations combined.x >>= ymeansx = x >> y.The same applies for&=and|=.And for the Delphi part:And,Or, andRight Shift.
What is the difference between the following two codes? ``` int main() { printf("hello\n"); main(); } ``` and ``` int main() { while(1) printf("hello\n"); return 0; } ``` The first one is pushed on stack every time while the stack allocation for second is done only once. Is there anything related to memory overflow in thewhile infinite loop?
As noted, the recursive method will consume stack, andultimatelyyou'll run out of stack space.
I used C-lang for UART coding. I know AT commands but a bit confused about how to include them in my UART program
As a simple trace to you: ``` const char *ATCommands[] = { "CGMI", "CGMM" }; char bufferTX[128]; int command_len= 0; command_len = sprintf(bufferTX, "AT+%s", ATCommand[commandToSend]); if (command_len > 3) { UART_send(bufferTX, command_len); } ``` Take note that some onswer of AT protocol (from slave) could beunssolicited. It is not an handshake protocol.
This kind of initialization works ``` int arr[3][4] = { {1,2,3,4}, {1,2,3,4}, {1,2,3,4} } ; ``` but this one here doesn't ``` const size_t row_size = 3; const size_t col_size = 4; int arr[row_size][col_size] = { {1,2,3,4},{1,2,3,4},{1,2,3,4}}; ``` these codes are in c but after changing the file extension to c++ and re-compilingit works fine. why such a behavior?
That used to be a problem with C and macros were used to solve such problems. But in C++ if you use "const" keyword then the compiler should automatically replace those values during compile time so there shouldn't be any problem with g++. That code runs perfectly fine when compiled with g++. Maybe you are trying to compile it with gcc (I got the same error with gcc which is as expected).
``` #include <stdio.h> int main() { FILE *file = fopen_s(file, "A.test", "r"); fputs("Hello World!\n", file); fclose(file); return 0; } ``` here is my code. but i see a below error;;;; error C4700: uninitialized local variable 'file' used how can i treat? what's problem?
You need to pass a pointer to the file pointer, so thatf_openscan set its value. Also, you overwrite the pointer with the return value, so that's going to be a problem. In addition you must open the file in write mode if you want to write to it, not read mode. You should basically read thedocumentationbetter and also read about some basic concepts such as indirection. ``` FILE *file; int err = fopen_s(&file, "A.test", "w"); if (err) { // handle error } fputs(... ```
I am new to C and I am currently working on string formatting. In particular how you would format decimals to have 2 leading places. Thus you would have 1, 20, 300 become 001, 020, 300. I understand there is %d but I haven't figured out a solution!
This could be an example ``` #include <stdio.h> int main(){ int one = 1; int two = 2; int twenty = 20; printf("One: %03d\n", one); printf("Two: %03d\n", two); printf("Twenty: %03d\n", twenty); } ``` Output: ``` One: 001 Two: 002 Twenty: 020 ```
What is the difference between the following two codes? ``` int main() { printf("hello\n"); main(); } ``` and ``` int main() { while(1) printf("hello\n"); return 0; } ``` The first one is pushed on stack every time while the stack allocation for second is done only once. Is there anything related to memory overflow in thewhile infinite loop?
As noted, the recursive method will consume stack, andultimatelyyou'll run out of stack space.
I used C-lang for UART coding. I know AT commands but a bit confused about how to include them in my UART program
As a simple trace to you: ``` const char *ATCommands[] = { "CGMI", "CGMM" }; char bufferTX[128]; int command_len= 0; command_len = sprintf(bufferTX, "AT+%s", ATCommand[commandToSend]); if (command_len > 3) { UART_send(bufferTX, command_len); } ``` Take note that some onswer of AT protocol (from slave) could beunssolicited. It is not an handshake protocol.
This kind of initialization works ``` int arr[3][4] = { {1,2,3,4}, {1,2,3,4}, {1,2,3,4} } ; ``` but this one here doesn't ``` const size_t row_size = 3; const size_t col_size = 4; int arr[row_size][col_size] = { {1,2,3,4},{1,2,3,4},{1,2,3,4}}; ``` these codes are in c but after changing the file extension to c++ and re-compilingit works fine. why such a behavior?
That used to be a problem with C and macros were used to solve such problems. But in C++ if you use "const" keyword then the compiler should automatically replace those values during compile time so there shouldn't be any problem with g++. That code runs perfectly fine when compiled with g++. Maybe you are trying to compile it with gcc (I got the same error with gcc which is as expected).
``` #include <stdio.h> int main() { FILE *file = fopen_s(file, "A.test", "r"); fputs("Hello World!\n", file); fclose(file); return 0; } ``` here is my code. but i see a below error;;;; error C4700: uninitialized local variable 'file' used how can i treat? what's problem?
You need to pass a pointer to the file pointer, so thatf_openscan set its value. Also, you overwrite the pointer with the return value, so that's going to be a problem. In addition you must open the file in write mode if you want to write to it, not read mode. You should basically read thedocumentationbetter and also read about some basic concepts such as indirection. ``` FILE *file; int err = fopen_s(&file, "A.test", "w"); if (err) { // handle error } fputs(... ```
I am new to C and I am currently working on string formatting. In particular how you would format decimals to have 2 leading places. Thus you would have 1, 20, 300 become 001, 020, 300. I understand there is %d but I haven't figured out a solution!
This could be an example ``` #include <stdio.h> int main(){ int one = 1; int two = 2; int twenty = 20; printf("One: %03d\n", one); printf("Two: %03d\n", two); printf("Twenty: %03d\n", twenty); } ``` Output: ``` One: 001 Two: 002 Twenty: 020 ```
I have this simple code: ``` #include <stdio.h> #include <stdint.h> int main(void) { uint16_t i = 0; unsigned char *b = "Yh"; i = b[1] | (b[0] << 8); printf("uint16_t: %u\n", i); return 0; } ``` As you can see, I'm addingY (HEX: 0x59, DEC: 89)andh (HEX: 0x68, DEC: 104)to auint16_twith a bitwise operation. TheYgets moved to the left 8 bits and thehis added at the end. The final content ofishould be89 104, right? If I then printi, what number should I expect to come out? I'm currently getting22888and I'm not sure why nor if that is what I should get.
89 is now in the higher 8 bits, so it's 89*28+104 = 22888. In hexadecimal, it's more visible: you took 0x59, shifted it by 8 bits left which gave you 0x5900, and then added 0x68. 0x5968 = 22888.
I know that in C# and JavaScript, the following is perfectly valid: ``` { var foo; } ``` Is having a bare block valid in C too? i.e. is this valid C? ``` { int foo; } ```
Is this valid in C too? Yes, it is and it is called acompound statement. From the C11 Standard: ``` 6.8.2 Compound statement Syntax 1 compound-statement: { block-item-listopt } block-item-list: block-item block-item-list block-item block-item: declaration statement ``` A compound-statement is itself astatementin C. For example this block is a valid block: ``` { { { printf("Hello world"); } } } ``` Even this one is valid: ``` {{{}}} ``` {}is an empty compound statement.
How can i check if a function is part of the kernel or user space? (or could be both too) Is there any overview over all kernel libs/functions? Working with C in Unix environment. e.g.rand()is pure user space,malloc()is user and kernel space etc.. The manual pages doesn't contain any information.
Thisarticle should give you some info on system calls (into kernel space). Now you can use this rough (and not very accurate) guideline: All man pages from section 2 are system calls.If a man page is from section 3, look in the SEE ALSO part at the bottom to see if it uses any commands from section 2. (Might also need to read through the man page itself.) Again, this is not very accurate, but short of reading the source code, it should give you an idea.
I'm trying to understand the sample code given for the MPU-9150 accelerator/gyroscope/magnometer. I imagine its quit basic but i haven't seen it before. ``` double dT = ( (double) MPU9150_readSensor(MPU9150_TEMP_OUT_L,MPU9150_TEMP_OUT_H) + 12412.0) / 340.0; Serial.print(dT); ``` TheMPU9150_readSensorrelates to a function for receiving a 16bit integer from the sensor using the two addresses. What i don't understand is the((double) MPU...., why is this needed, hasnt it already been declared as a double? Many thanks Alex
MPU9150_readSensor()returns anint. we want the compiler to understand that you intentionally want a double value from the function. that is why you type cast. Reference:http://playground.arduino.cc/Main/MPU-9150
How structs in C are saved in the memory? Why sometimes the struct length in the memory is bigger than expected?
That's calleddata structure alignment. Although not a perfect duplicate, you can find a good explanation of this in C atStructure padding and packing
What happens in this code? ``` #include <stdio.h> int main(){ int e; printf("%d ", e); printf("%s", e); return 0; } ``` Does e will have a) Garbage value? b) NULL In GCC it shows garbage value and in g++ it shows 0 and NULL. Thanks!!
Both statements invoke undefined behavior becauseeobject is not initialized so its value is indeterminate. The second statement also has the wrong conversion specifier,%sspecification requires achar *argument. So as someone mentioned in the comments, the correct answer is neither a) nor b) but c)demons flying out your nose.
This is probably and easy one for you guys, but I couldn't find a definitive answer and I just want to be sure I'm not overlooking anything. I have an equation, which I know permits complex solutions, but I've programmed it in C using "double" and/or "float". Does C simply ignore the complex part if I don't use "complex" types? In other words, does it simply return the real part? Will it generate any errors by not using "complex"? Thanks.
There is a 'complex' and an 'imaginary' data type in C. However, since it has only been a few years since it has been introduced, some of the old systems might not support it. So, its best to handle that kind of solutions explicitly. If you are performing an illegal operation like sqrt(-1), then itwillgenerate an error. The following post most probably answers your queries betterHow to work with complex numbers in C?
Okay so I'm trying to do a basic program in VS. Enter a number then it gets printed out. 1 is always printed. ``` int main(){ printf("Enter an integer: "); int n = scanf_s("%d", &n); printf("%d", n); } ```
You are assigning the returned value fromscanf_s()to the variablen, that means that the program will print1in case a successful read happened. What you should do is ``` int numberOfItemsMatched; int readValue; numberOfItemsMatched = scanf_s("%d", &readValue); if (numberOfItemsMatched == 1) printf("%d\n", readValue); ``` I hope the variable names are self explanatory, and it's always a good idea to use this kind of names.
``` short i = 1; fwrite(&i, sizeof(i), 1, file); fwrite(&i, sizeof(i), 1, file); ``` Is that proper? I want to write the sameitwice.
There's nothing wrong with it; just remember to check the return value.
Why dose the folowing code: ``` #include <stdio.h> #include <stdlib.h> int main() { printf("Hello world!\n"); int x; long l; double d; printf("\n%d",sizeof(x+l+d)); return 0; } ``` prints on the console 8? I originaly thought that will convertxandlto double and display 24. Why 8?
sizeofreturns the number of bytes used to store its argument. In this case its argument isx+l+d.xis anint,lalong, anddadouble. When you add integer types todoubles, the result is promoted to form adouble. So what you have written is the equivalent ofsizeof(double). Adoubletakes 8 bytes to store, so you are seeing8as the result.
While readinf MuPDF comes across the source code line ``` x = !x; ``` Want to know what does the above code do? While compilation is also gives error as ``` assuming signed overflow does not occur when simplifying condition to constant [-Werror=strict-overflow ] ```
!xwill evaluate to either0or1, depending on the value ofx. Ifxis0, it evaluates to1.Otherwise, it evaluates to0.
I am able to convert BCD to decimal, for example I can convert 0x11 to 11 instead of 17 in decimal. This is the code I used. ``` unsigned char hex = 0x11; unsigned char backtohex ; int dec = ((hex & 0xF0) >> 4) * 10 + (hex & 0x0F); ``` Now I want to convertdecback to BCD representation. I want 11 to be converted back to 0x11 not 0x0B. I am kind of confused as how to go back. Thanks!
Assuming your input is always between 0 and 99, inclusive: ``` unsigned char hex = ((dec / 10) << 4) | (dec % 10); ``` Simply take the upper digit and shift it left by one nibble, andorthe lower digit in place.
I have this simple code: ``` #include <stdio.h> #include <stdint.h> int main(void) { uint16_t i = 0; unsigned char *b = "Yh"; i = b[1] | (b[0] << 8); printf("uint16_t: %u\n", i); return 0; } ``` As you can see, I'm addingY (HEX: 0x59, DEC: 89)andh (HEX: 0x68, DEC: 104)to auint16_twith a bitwise operation. TheYgets moved to the left 8 bits and thehis added at the end. The final content ofishould be89 104, right? If I then printi, what number should I expect to come out? I'm currently getting22888and I'm not sure why nor if that is what I should get.
89 is now in the higher 8 bits, so it's 89*28+104 = 22888. In hexadecimal, it's more visible: you took 0x59, shifted it by 8 bits left which gave you 0x5900, and then added 0x68. 0x5968 = 22888.
I know that in C# and JavaScript, the following is perfectly valid: ``` { var foo; } ``` Is having a bare block valid in C too? i.e. is this valid C? ``` { int foo; } ```
Is this valid in C too? Yes, it is and it is called acompound statement. From the C11 Standard: ``` 6.8.2 Compound statement Syntax 1 compound-statement: { block-item-listopt } block-item-list: block-item block-item-list block-item block-item: declaration statement ``` A compound-statement is itself astatementin C. For example this block is a valid block: ``` { { { printf("Hello world"); } } } ``` Even this one is valid: ``` {{{}}} ``` {}is an empty compound statement.
How can i check if a function is part of the kernel or user space? (or could be both too) Is there any overview over all kernel libs/functions? Working with C in Unix environment. e.g.rand()is pure user space,malloc()is user and kernel space etc.. The manual pages doesn't contain any information.
Thisarticle should give you some info on system calls (into kernel space). Now you can use this rough (and not very accurate) guideline: All man pages from section 2 are system calls.If a man page is from section 3, look in the SEE ALSO part at the bottom to see if it uses any commands from section 2. (Might also need to read through the man page itself.) Again, this is not very accurate, but short of reading the source code, it should give you an idea.
I'm trying to understand the sample code given for the MPU-9150 accelerator/gyroscope/magnometer. I imagine its quit basic but i haven't seen it before. ``` double dT = ( (double) MPU9150_readSensor(MPU9150_TEMP_OUT_L,MPU9150_TEMP_OUT_H) + 12412.0) / 340.0; Serial.print(dT); ``` TheMPU9150_readSensorrelates to a function for receiving a 16bit integer from the sensor using the two addresses. What i don't understand is the((double) MPU...., why is this needed, hasnt it already been declared as a double? Many thanks Alex
MPU9150_readSensor()returns anint. we want the compiler to understand that you intentionally want a double value from the function. that is why you type cast. Reference:http://playground.arduino.cc/Main/MPU-9150
How structs in C are saved in the memory? Why sometimes the struct length in the memory is bigger than expected?
That's calleddata structure alignment. Although not a perfect duplicate, you can find a good explanation of this in C atStructure padding and packing
What happens in this code? ``` #include <stdio.h> int main(){ int e; printf("%d ", e); printf("%s", e); return 0; } ``` Does e will have a) Garbage value? b) NULL In GCC it shows garbage value and in g++ it shows 0 and NULL. Thanks!!
Both statements invoke undefined behavior becauseeobject is not initialized so its value is indeterminate. The second statement also has the wrong conversion specifier,%sspecification requires achar *argument. So as someone mentioned in the comments, the correct answer is neither a) nor b) but c)demons flying out your nose.
I've developed a utility to monitor the network usage (for TCP/UDP/IP)nettop, and in order to link packets captured with libpcap to their respective processes, I basically scan the virtual filesystem/proc/net/(tcp|udp)(6)and/proc/<pid>/fd. Is there a better more efficient way to do so? Cheers, Ema
I don't think so - it's how thefuser(1)command does it. The source forfusermight give some insights about additional things you may want to consider, though (esp. with IPv4 vs. IPv6).
I still do not quite understand, what exactly will happen in the situation: ``` int i = 0; for(i; i <100; i ++) { char some_array[24]; //... strcpy(some_array,"abcdefg"); } ``` Will thesome_arrayact as: some_array = malloc(24); At the beginning of the cycle andfree(some_array)at the end of the cycle? Or those variables are gonna be allocated in the stack, and after the function ends destroyed?
some_arrayis local to theblock, so it's created at the beginning of each iteration of the loop, and destroyed again at the end of each iteration of the loop. In the case of a simple array, "create" and "destroy" don't mean much. If (in C++) you replace it with (for example) an object that prints something out when it's created and destroyed, you'll see those side effects happen though.
The delay function ofdos.hheader file does not work in codeblocks. It shows that delay function is undeclared. the following link contains the program below.link ``` int main () { printf ( " This c program will exit in 10 seconds.\n"); delay(10000); return 0; } ```
I was also having same problem & I used this function ``` #include <time.h> void delay(int milliseconds) { long pause; clock_t now,then; pause = milliseconds*(CLOCKS_PER_SEC/1000); now = then = clock(); while( (now-then) < pause ) now = clock(); } ``` edited : As commented, this does make system busy. I have fund better way to do it, and works for CodeBlocks. ``` #include <windows.h> . . . Sleep(100); //sleep for 0.1 second . ```
I am very new to C and have this simple code here: ``` int main(int argc, char **argv){ FILE *input = stdin; char string[20]; while (fscanf(input, "%s",string)) { printf("String: %s \n",string); } printf("Done"); return 0; } ``` The problem I am having is that the the "Done" line never gets printed. When the while loop is finished reading from the stdin, it doesn't execute anything after it. Is there some concept that I am not aware of? Thanks in advance.
You need to change it to look forEOF: ``` while (EOF != fscanf(input, "%s",string)) { ``` TheEOFcharacter is^Zin Windows or^Din *nix (i.e. Ctrl+Z or Ctrl+D). After entering the EOF character, you still have to hit enter because keyboard input will be line buffered.
``` #include<cstdio> int main(){ int a=10,b=20; int *p=&a; *(p-1)=100; printf("%d, %d, %d\n",a,b,*(p-1)); // printf("%d, %d, %d\n",&a,&b,(p-1)); return 0; } ``` Why does the first printf (line 6) show a different result whether or not the second one (line 7) is in comments or not? I'm using C compiler (TDM-GCC 4.8.1 64bit)
pis not pointing to an array, therefore the expression*(p-1)hasundefined behaviour. This means that, once*(p-1)=100has been executed, technically the program can behave in whatever way it likes. What likely happens in practice is that you're overwriting some memory on the stack, which can lead to all sorts of side effects. If youValgrindyour code, the tool will flag this up.
This is a very simple question but even have some doubt in sequence point. ``` int a[3] = {1,2,4}; printf("%d",++a[1]); ``` o/p ``` 3 ``` Is this a valid c statement, I am getting output3, which means it is same as ``` ++(a[1]) ``` But how is this possible as we have a pre-increment operator which has to increment theafirst then the dereference has to happen. Please correct my doubt. How we are getting3?
Behavior is well defined. Operator[]has higher precedence than prefix++operator. Therefore operandawill bind to[]. It will be interpreted as ``` printf("%d", ++(a[1])); ```
I'm trying to just bind a socket with this : ``` #include <stdio.h> #include <stdlib.h> #include <netinet/in.h> #include <sys/socket.h> #include <errno.h> int main() { int fd,namelen,newfd; struct sockaddr_in sin = {AF_INET}; if(fd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)==-1) printf("socket : %d\n",errno); if(bind(fd,(struct sockaddr *)&sin,sizeof(sin))==-1) printf("bind : %d\n",errno); } ``` And that return "bind : 88", I think this mean ENOTSOCK fd, isn't a socket really ? or 88 isn't ENOTSOCK ?
Take care about parenthesis, in fact fd = 0 in your case.Because==is evaluated before=(seeC Operator Precedence), your code is equivalent tofd = (socket(...) == -1). You should replace ``` if(fd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)==-1) ``` with ``` if((fd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==-1) ```
This question already has answers here:What mean file with extension "h.in"?(3 answers)Closed8 years ago. I was compiling with gcc on Linux Because sndfile.h was not there but sndfile.h.in was found, I just tried with sndfile.h.in - which is in the same directory as the *.C file. But I got the error even though it is in the same directory. Its been a while since I programmed in Linux that these little things are bothering me - appreciate if u could help me started. Thanks
I think you are using the angular brackets for the including the file.If you place< >. It will search in/usr/include. You have to use the double quotes for including the file in the current directory. And be sure that file is available. Like this. ``` #include "sndfile.h.in" ```
I have a program in 8086 and C languages now i want to compare the machine code of each program. How can I get machine code of C and assembly 8086 code I useemu8086andDEV.
How can I get machine code of C and assembly 8086 code Compile the C code using the standard compiler Assemble the C code using the standard assembler That gives you the machine code. Then, assuming you are really wanting tocomparethe code ... : use a hex dump tool to look at / compare the two code files, oruse a disassembler and compare the dissasembled versions of the C code with your original assembly code, orlook up in your compiler documentation how to get it to output assembly language ...
I'm writing a C program and am exceeding the recursion limit via a segmentation fault. Is there any way to increase the program's recursion limit (perhaps via increasing the stack size), either via an option to GCC or via a command-line option? The program is running on Ubunutu.
You can change the stack size withulimiton Linux, for example: ``` ulimit -s unlimited ``` On Windows with Visual Studio, use/Foption.
i have this program and it's working fine until the very end. When I ask the user if he/she wants to do a discount and the user enters y/n, the program just halts and doesn't go to the if statement. Any help? Thanks :) ``` int calculate(){ printf("Do you want to make a discount? y/n \n"); scanf("%c",&ask); if (ask == 'y') { printf("Enter the actual money that you want to make a discount\n"); scanf("%f",&disc); discount= (total * (disc/100)); net= (total - discount); printf("The total bill is: %.2f\n", net); } else if(ask == 'n') { printf("The total bill is: %.2f\n", total); } //menu(); return 0; } ```
Change this ``` scanf("%c",&ask); ``` to ``` scanf(" %c",&ask); ``` to explicitly ignore any left over white space.
Is there a way to set the heap start address in GCC compiled C program in linux? In x86_64 system,my test program sets the heap address to 4 byte referenced address ( less than FFFFFFFF). I want to set this to 8 byte referenced address for some testing ( > FFFFFFFF). Does GCC provide any way to set the heap start address?
You can do this a bit indirectly usingsbrk(): ``` #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(void) { sbrk(0xFFFFFFFF); printf("%p\n", malloc(1)); return 0; } ``` This works by "allocating" 0xFFFFFFFF bytes at the very start, so that the next thingmalloc()can allocate is a higher address.
If you are reading lines from a terminal in canonical mode, is there any way to tell the difference between a line terminated with EOL (Enter) and EOF (Ctrl-D)? My understanding is that both will return the number of bytes read from read().
For EOL on an empty line, the byte count will be 1, for the newline. For EOF on an empty line, the byte count will be 0, for 'there was no more data'.
I was given the following code to use as part of an exercise. I am instructed to create a 3x3 matrix and assign specific values to it. Here is the code: ``` void minput(int* m, int row, int col) { /* assign 3X3 matrix to following value 8 1 6 3 5 7 4 9 2 */ *(m+0) = 8; } ``` What I am trying to figure out is what this piece of code*(m+0) = 8;is for. I know that adding a*in front of any variable means to "give me whatever is that the address". What does the +0 do?
*(m+0)is equivalent tom[0]. So the whole statement is assigning8tom[0].
Here is the part of code I have written to stuff 0 to a screen session open in one of my Ubuntu terminal tabs. ``` char command[60]; strcpy( command, "screen -S 8305.pts-1.MYUb -X stuff $'0'" ); system(command); ``` It gets compiled fine with only a warning like ``` ignoring return value of ‘system’, ``` But when it comes to running I get the message shown below: ``` No screen session found. ``` I have tried system() with other shell commands and it works perfectly fine. The command for screen also works fine when you run it in a terminal session not in c code.
Most probably you are running the command as a different user than the user that owns the screen. For example running the binary as sudo. You can runps auxto find the user under which your binary is running as. To make the system command work you should run it as the user who owns the screen.
I need to run some bash shell commands when my c program reaches to a certain point. What I have found by googling is that system() provides such a functionality. However, compiling the code by gcc generates a warning message like below and the bash command does not get executed. Any solution or alternative? ``` warning: ignoring return value of ‘system’, declared with attribute warn_unused_result [-Wunused-result] system(command); ```
It's a library call, and you are ignoring the return value from it, thats why that compiler warning. Assign it to a variable, check the return value (See man page of system). And that warning has nothing to do with your bash command not getting executed.
Is there a way to set the heap start address in GCC compiled C program in linux? In x86_64 system,my test program sets the heap address to 4 byte referenced address ( less than FFFFFFFF). I want to set this to 8 byte referenced address for some testing ( > FFFFFFFF). Does GCC provide any way to set the heap start address?
You can do this a bit indirectly usingsbrk(): ``` #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(void) { sbrk(0xFFFFFFFF); printf("%p\n", malloc(1)); return 0; } ``` This works by "allocating" 0xFFFFFFFF bytes at the very start, so that the next thingmalloc()can allocate is a higher address.
If you are reading lines from a terminal in canonical mode, is there any way to tell the difference between a line terminated with EOL (Enter) and EOF (Ctrl-D)? My understanding is that both will return the number of bytes read from read().
For EOL on an empty line, the byte count will be 1, for the newline. For EOF on an empty line, the byte count will be 0, for 'there was no more data'.
I was given the following code to use as part of an exercise. I am instructed to create a 3x3 matrix and assign specific values to it. Here is the code: ``` void minput(int* m, int row, int col) { /* assign 3X3 matrix to following value 8 1 6 3 5 7 4 9 2 */ *(m+0) = 8; } ``` What I am trying to figure out is what this piece of code*(m+0) = 8;is for. I know that adding a*in front of any variable means to "give me whatever is that the address". What does the +0 do?
*(m+0)is equivalent tom[0]. So the whole statement is assigning8tom[0].
Here is the part of code I have written to stuff 0 to a screen session open in one of my Ubuntu terminal tabs. ``` char command[60]; strcpy( command, "screen -S 8305.pts-1.MYUb -X stuff $'0'" ); system(command); ``` It gets compiled fine with only a warning like ``` ignoring return value of ‘system’, ``` But when it comes to running I get the message shown below: ``` No screen session found. ``` I have tried system() with other shell commands and it works perfectly fine. The command for screen also works fine when you run it in a terminal session not in c code.
Most probably you are running the command as a different user than the user that owns the screen. For example running the binary as sudo. You can runps auxto find the user under which your binary is running as. To make the system command work you should run it as the user who owns the screen.
I need to run some bash shell commands when my c program reaches to a certain point. What I have found by googling is that system() provides such a functionality. However, compiling the code by gcc generates a warning message like below and the bash command does not get executed. Any solution or alternative? ``` warning: ignoring return value of ‘system’, declared with attribute warn_unused_result [-Wunused-result] system(command); ```
It's a library call, and you are ignoring the return value from it, thats why that compiler warning. Assign it to a variable, check the return value (See man page of system). And that warning has nothing to do with your bash command not getting executed.
Inthe tutorialfor erl_driver there seems to be no indication to where does the firstErlDrvPortobject comes from. Say I want to wrap libusb-1.0 to use it from erlang. There is no place in the API described byErlDrvEntryfor any index methods. How does one find a port to open?
Normally you obtain the first port using theerlang:open_port/2function, usage of which is shown in the code example in section 6.2 ofthe tutorialyou linked to in your question.
I think block is the Objective-C feature. Recently I am adding the block to some C source file and I found it just compile OK. I get confused, for *.c file, should the compiler(Clang) consider it as the pure C file, why it can permit block?
Actually Clang introduces blocks to C and, by extension, Objective-C, C++, and Objective-C++ As you can read here in theoverview. Of course, using blocks makes your source incompatible with C11 standard but, you know, as long as your code is for Mac OS X only... EDIT: Blocks are also available in GCC, didn't know about it.
I am trying to copy from a character array to character pointer. My code: ``` char str[] = "Hello World"; char *result = (char *)malloc(strlen(str)+1); int index=0; while(index <= strlen(str)) { *result = str[index]; result++; index++; } ``` This above code is not working and below code is working ``` char str[] = "Hello World"; char *result = (char *)malloc(strlen(str)+1); int index=0; while(index <= strlen(str)) { result[index] = str[index]; index++; } ``` Can anyone explain this behavior?
we simply use the strcpy function to copy the array into the pointer. ``` char str[] = "Hello World"; char *result = (char *)malloc(strlen(str)+1); strcpy(result,str); ```
My question is; is there a functional difference between rounding a double down to an int viaroundedInt = (int)unRoundedDoubleandroundedInt = (int)(floor(unRoundedDouble))? I've seen the latter used in code, and thought that maybe it's for safety or functional reasons, but can't figure out what would be handled differently. Also: the rounded Double will not be too large to fit into an int, that's determined beforehand.
They are fundamentally different. Cast tointwill truncate the non-integer part toward0.floorwill do the same, but toward, -infinity. Example: ``` double d = -1.234; printf("%d %d\n", (int)d, (int)floor(d)); ``` Yields: ``` -1 -2 ```
I want to understand why following code is not work as it should: ``` char c; NSLog(@"Enter a single character: "); scanf("%c", &c); if (c >= '0' && c <= '9') { NSLog(@"It's a digit"); } ``` When I enter a number between 0 and 9 I get correct output - "It's a digit". But when I enter something like 197 I get the same output. But in logical operator (&&) both conditions should met. Why does it evaluate to true when the number is larger than 9? By the way, if case any of you don't know,scanfallows you to input something in the Xcode console or in the terminal.
char c, impliesscanf("%c", &c)can only read a single character into char variablec. Hence input197will read as1in toc, making logical&&true.Look at this compilation
I'm working on prefixing of a string for example :comshould give meccocom. I know to print a character in this wasprintf("%.5s",string)to print the first five values. I want to do this in a loop instead of 5 how can I replace it withiwhich is a incrementing value,something like thisprintf("%.is",string). how can I obtain this?
Inprintfformat specifiers, all field widths (before the dot) and precisions (after the dot) can be given as asterisk*. For each asterisk, there must be one additionalintargument before the printed object. So, for your problem: ``` printf("%.*s", i, string); ``` Note that the additional parameter must be anint, so if you have another integer type, you should cast it: ``` size_t len = strlen(len); if (len > 2) printf("%.*s", (int) (len - 2), string); ```
I'm using libradius in my app. The structurestruct rad_handlewhere this info is available after call ofrad_send_request()is private, so i can't accessh->servers[h->srv].addrfrom my app. Is there any way to know which one from several RADIUS servers i previously added withrad_add_server()responded to myRAD_ACCESS_REQUESTsent byrad_send_request()?
There is no way with the libradius API to determine this information. Once you've received the response from the server, it's already discarded the information about what server address replied to it. Your only option would be to make a customized version of libradius that populated this information. The library itself is quite small, so understanding it in order to make changes of that kind should be quite simple. This is of course, assuming thebsd libradius, and not theFreeRadius Client Library
I have this weird problem where I am using sprintf and it puts FF in front of the value I have. (e.g.) I should get 01, but I am getting FF01 My code looks like this ``` while(1) { if(getkey()=='g') { sprintf(str_2, "%X", ~OWReadByte()); lcd_delay(); lcd_string(str_2); } } ``` I did some checking on the LEDs and on there i get the value i want, after using sprintf it just gets screwed up.
The unary~operator changes the bits of the wholeint, not only the lower 8 bits.~0xfeu(equivalently,~0x00feu) is0xff01ufor 16-bitint. I suggest to always use unsigned types when doing bit manipulation, passing a negativeintto%Xis, strictly speaking, undefined behavior. To get rid of the higher bits, you can do ``` sprintf(&str_2[i * 2], "%02X", ~OWReadByte() & 0xffu); ```
I came across some rather interesting code today while reviewing an implementation of SHA1 in C. ``` temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1]; temp &= 0xFFFFFFFF; ``` The part I find interesting istemp &= 0xFFFFFFFF;. Note thattempis declared as anunsigned integeralready. Won't this operation simply have no effect? The only thing I can think of is that the designer is trying to enforce the use of 32-bit integers, but wouldn't this be done at compile-time?I'm curious to know peoples thoughts.
On some machines,int(and thereforeunsigned inttoo) could be a 64-bit type. The mask is a no-op on machines whereintis a 32-bit type, but critical on machines where it is a 64-bit type. The compiler will know and will optimize the operation away when it does nothing useful. Also, there used to be machines with36-bitinttypesand others with60-bitinttypes; it would matter on such machines too.
Let's say we have following code: ``` int func(char str[], int len) { // Don't return anything here. } int main() { char str[] = "Hello"; int result = func(str, strlen(str)); printf("%d\n", result); } ``` It will print some string value -1679929632 on my computer. And it changes from time to time when I execute. Can anyone explain why this happen?
If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function isundefined. If a return value is not required, declare the function to have void return type; otherwise, the default return type is int. As mentioned above its undefined so finding root cause behind some random value as return will be useless.
I want to understand why following code is not work as it should: ``` char c; NSLog(@"Enter a single character: "); scanf("%c", &c); if (c >= '0' && c <= '9') { NSLog(@"It's a digit"); } ``` When I enter a number between 0 and 9 I get correct output - "It's a digit". But when I enter something like 197 I get the same output. But in logical operator (&&) both conditions should met. Why does it evaluate to true when the number is larger than 9? By the way, if case any of you don't know,scanfallows you to input something in the Xcode console or in the terminal.
char c, impliesscanf("%c", &c)can only read a single character into char variablec. Hence input197will read as1in toc, making logical&&true.Look at this compilation
I'm working on prefixing of a string for example :comshould give meccocom. I know to print a character in this wasprintf("%.5s",string)to print the first five values. I want to do this in a loop instead of 5 how can I replace it withiwhich is a incrementing value,something like thisprintf("%.is",string). how can I obtain this?
Inprintfformat specifiers, all field widths (before the dot) and precisions (after the dot) can be given as asterisk*. For each asterisk, there must be one additionalintargument before the printed object. So, for your problem: ``` printf("%.*s", i, string); ``` Note that the additional parameter must be anint, so if you have another integer type, you should cast it: ``` size_t len = strlen(len); if (len > 2) printf("%.*s", (int) (len - 2), string); ```
I'm using libradius in my app. The structurestruct rad_handlewhere this info is available after call ofrad_send_request()is private, so i can't accessh->servers[h->srv].addrfrom my app. Is there any way to know which one from several RADIUS servers i previously added withrad_add_server()responded to myRAD_ACCESS_REQUESTsent byrad_send_request()?
There is no way with the libradius API to determine this information. Once you've received the response from the server, it's already discarded the information about what server address replied to it. Your only option would be to make a customized version of libradius that populated this information. The library itself is quite small, so understanding it in order to make changes of that kind should be quite simple. This is of course, assuming thebsd libradius, and not theFreeRadius Client Library
I have this weird problem where I am using sprintf and it puts FF in front of the value I have. (e.g.) I should get 01, but I am getting FF01 My code looks like this ``` while(1) { if(getkey()=='g') { sprintf(str_2, "%X", ~OWReadByte()); lcd_delay(); lcd_string(str_2); } } ``` I did some checking on the LEDs and on there i get the value i want, after using sprintf it just gets screwed up.
The unary~operator changes the bits of the wholeint, not only the lower 8 bits.~0xfeu(equivalently,~0x00feu) is0xff01ufor 16-bitint. I suggest to always use unsigned types when doing bit manipulation, passing a negativeintto%Xis, strictly speaking, undefined behavior. To get rid of the higher bits, you can do ``` sprintf(&str_2[i * 2], "%02X", ~OWReadByte() & 0xffu); ```
I came across some rather interesting code today while reviewing an implementation of SHA1 in C. ``` temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1]; temp &= 0xFFFFFFFF; ``` The part I find interesting istemp &= 0xFFFFFFFF;. Note thattempis declared as anunsigned integeralready. Won't this operation simply have no effect? The only thing I can think of is that the designer is trying to enforce the use of 32-bit integers, but wouldn't this be done at compile-time?I'm curious to know peoples thoughts.
On some machines,int(and thereforeunsigned inttoo) could be a 64-bit type. The mask is a no-op on machines whereintis a 32-bit type, but critical on machines where it is a 64-bit type. The compiler will know and will optimize the operation away when it does nothing useful. Also, there used to be machines with36-bitinttypesand others with60-bitinttypes; it would matter on such machines too.
Let's say we have following code: ``` int func(char str[], int len) { // Don't return anything here. } int main() { char str[] = "Hello"; int result = func(str, strlen(str)); printf("%d\n", result); } ``` It will print some string value -1679929632 on my computer. And it changes from time to time when I execute. Can anyone explain why this happen?
If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function isundefined. If a return value is not required, declare the function to have void return type; otherwise, the default return type is int. As mentioned above its undefined so finding root cause behind some random value as return will be useless.
``` #include<stdio.h> main() { int c; c=getchar(); while(c!=EOF) { putchar(c); c=getchar(); } } ``` Why this code is resulting in an infinite loop. It is from D.Ritchie's book.
It results in an infinite loop becauseEOFis not a character that can be entered via keyboard. Take a look at this:EOF in Windows command prompt doesn't terminate input stream
I expect the c program print the received 3 lines. But the result is that the c program printfrom c program:33333333nonstoppedly. I don't know whyfgets()didn't consumestdinafter executtion. ``` # pin.py from subprocess import Popen, PIPE p = Popen("/home/jchn/pstdin",stdin=PIPE,stdout=None) p.stdin.write("11111111") p.stdin.write("22222222") p.stdin.write("33333333") ``` Content ofpstdin.c ``` # pstdin.c #include <stdio.h> int main(){ char a[10]; FILE* fd = fopen("output","w"); while (1){ fgets(a,10,stdin); printf("--from c program--:%s",a); } } ```
while(1)is an infinite loop, you have no stop condition ``` while(fgets(a,10,stdin) != NULL) { printf("--from c program--:%s",a); } ```
How can I check whether there are numbers in char provided by user in C language? Last line of C code to change :): ``` char name; do{ printf("What's your name?\n"); scanf("%s\n", name); } \\and here's my pseudocode: while (name consist of a sign (0 or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9)); ```
Here is a different approach that tests for specified chars in one function call. ``` #include <stdio.h> #include <string.h> int main() { char name[100]; char charset[]= "-+0123456789"; int len; do { printf("What's your name?\n"); scanf("%s", name); len = strlen(name); } while (strcspn(name, charset) != len); printf ("Your name is '%s'\n", name); return 0; } ```
I'm programming in C and I have some kind of enum, lets say there's an enum name hello and it has 3 properties inside of it- A, B and C. How can I make A equal 0, B equal 2, and C equal 3, rather than each value simply incrementing by one? Thanks in advance!
Just do this ``` enum X { A = 0, B = A + 2, C = B + 2 }; ``` If you want to increment by 2 each time or if you want to do it only the first time ``` enum X { A = 0, B = A + 2, C = B + 1 }; ``` Note that the first will be0automatically soA = 0is not needed it is in my answer just to make it explicit thatA == 0, and in the second case and since the default increment will be1it is also not necessary to writeC = B + 1, if you apply this to the code, it would look like ``` enum X { A, B = A + 2, C }; ``` And you can ofcourse assign a value to eachenum, like ``` enum X { A = 0, B = 2, C = 3, }; ```
I am a begineer in learning Device Driver.I am practising with simple example to learn device driver. Can anyone suggest me how to start writing uart ,GPIO device driver for raspberry pi,because i started practising with raspberry pi only. Thanks in advance Regards, pradeep
If this is your very first driver, start with something simple. I would take the following steps: Write a simple character device driver that implements read/write/open/close file ops. That means they can be used with 'cat' and 'echo'.Based on the initial work from 1, you can write a GPIO driver. This should be simple because all you need to do is write or read a 0 or 1 from a specific memory address.Now that you have some experience with device drivers you can write a tty driver for your uart. There are lots of examples of tty drivers in linux already.
This question already has answers here:How to escape the % (percent) sign in C's printf(13 answers)Closed8 years ago. The output of ``` printf("%%%%%%%%"); ``` is ``` %%%% ``` I used%eight times. Why does the output only have four%s?
Because%is a format specifier escape sequence (as in%dwould print anint). To get the program to print the actual symbol, you write%%. The same goes for\(although fundamentally different, you still need to to print one).
I am trying to copy the contents from array a to array b. When I test within the function it seems to copy, but when I print out b in the main program, it shows 0s ``` void array_copy(int a[], int b[], int n) { for (int j = 0; j < n; j++) { b = a; //printf("%d\n", *b); a++; b++; } ``` and then when I try and print to test outside, I get 0s ``` printf("%d", *b); ``` Any ideas why I am getting 0 instead of what should be in there. (I have made sure array a does contain non zero values)
``` b = a; ``` This line makes the pointerbpoints to the same place whereapoints to. What you want (copying the contents) should be: ``` *b = *a; ```
``` #include <stdio.h> int main(int argc, char *argv[]) { int n = 234; // Gets first digit int digit = n / 100; putchar('0' + digit); // gets 3rd digit digit = n % 10; putchar('0' + digit); } ``` How can I get "3" aka 2nd digit? Also If the n was something like 245836 how could I extract each digit one by one?
You can do it by dividing by ten and then taking the remainder of division by ten: ``` int second = (number / 10) % 10; ``` In general, you could think of integer-dividing by ak-th power of ten as ofdroppingkleast significant digits. Taking a remainder of division byk-th power of ten is equivalent tokeepingthe lastkdigits. how could I extract each digit one by one? You can take the last digit with%10and then dropping that digit off the end by/= 10.
I'm programming in C and I have some kind of enum, lets say there's an enum name hello and it has 3 properties inside of it- A, B and C. How can I make A equal 0, B equal 2, and C equal 3, rather than each value simply incrementing by one? Thanks in advance!
Just do this ``` enum X { A = 0, B = A + 2, C = B + 2 }; ``` If you want to increment by 2 each time or if you want to do it only the first time ``` enum X { A = 0, B = A + 2, C = B + 1 }; ``` Note that the first will be0automatically soA = 0is not needed it is in my answer just to make it explicit thatA == 0, and in the second case and since the default increment will be1it is also not necessary to writeC = B + 1, if you apply this to the code, it would look like ``` enum X { A, B = A + 2, C }; ``` And you can ofcourse assign a value to eachenum, like ``` enum X { A = 0, B = 2, C = 3, }; ```
I am a begineer in learning Device Driver.I am practising with simple example to learn device driver. Can anyone suggest me how to start writing uart ,GPIO device driver for raspberry pi,because i started practising with raspberry pi only. Thanks in advance Regards, pradeep
If this is your very first driver, start with something simple. I would take the following steps: Write a simple character device driver that implements read/write/open/close file ops. That means they can be used with 'cat' and 'echo'.Based on the initial work from 1, you can write a GPIO driver. This should be simple because all you need to do is write or read a 0 or 1 from a specific memory address.Now that you have some experience with device drivers you can write a tty driver for your uart. There are lots of examples of tty drivers in linux already.
This question already has answers here:How to escape the % (percent) sign in C's printf(13 answers)Closed8 years ago. The output of ``` printf("%%%%%%%%"); ``` is ``` %%%% ``` I used%eight times. Why does the output only have four%s?
Because%is a format specifier escape sequence (as in%dwould print anint). To get the program to print the actual symbol, you write%%. The same goes for\(although fundamentally different, you still need to to print one).
I am trying to copy the contents from array a to array b. When I test within the function it seems to copy, but when I print out b in the main program, it shows 0s ``` void array_copy(int a[], int b[], int n) { for (int j = 0; j < n; j++) { b = a; //printf("%d\n", *b); a++; b++; } ``` and then when I try and print to test outside, I get 0s ``` printf("%d", *b); ``` Any ideas why I am getting 0 instead of what should be in there. (I have made sure array a does contain non zero values)
``` b = a; ``` This line makes the pointerbpoints to the same place whereapoints to. What you want (copying the contents) should be: ``` *b = *a; ```
``` #include <stdio.h> int main(int argc, char *argv[]) { int n = 234; // Gets first digit int digit = n / 100; putchar('0' + digit); // gets 3rd digit digit = n % 10; putchar('0' + digit); } ``` How can I get "3" aka 2nd digit? Also If the n was something like 245836 how could I extract each digit one by one?
You can do it by dividing by ten and then taking the remainder of division by ten: ``` int second = (number / 10) % 10; ``` In general, you could think of integer-dividing by ak-th power of ten as ofdroppingkleast significant digits. Taking a remainder of division byk-th power of ten is equivalent tokeepingthe lastkdigits. how could I extract each digit one by one? You can take the last digit with%10and then dropping that digit off the end by/= 10.
I need to know if the following code could be an undefined behaviour (I'm pretty sure it is): ``` int main(){ int z=53; z=z<<=3; return 0; } ``` This was a question in a classroom test. I told my teacher I thought it was UB, but my teacher did not believe me.
It's undefined. Reffering to N1256, C99 draft, subclause 6.5/2 (emphasis mine): Between the previous and next sequence point an object shall have its stored value modifiedat most onceby the evaluation of an expression. 72) Furthermore, the prior value shall be read only to determine the value to be stored. 73)
following (simplified) piece of code causes an ``` error C2099: initializer is not a constant ``` in last line of this snippet: ``` static const char rowmans_1_width = 16; ... const char rowmans_width[96] = {rowmans_1_width, rowmans_2_width, rowmans_3_width,... ``` Sorowmans_1_widthis defined as "const" but compiler still complains it is not constant. This happens when I compile this as C-code, when using as C++ it works smoothly. My Problem: I have to use a C compiler now and I can't simply use a ``` #define rowmans_1_width 16 ``` because I had to change very much at very different positions - means a simple search/replace would not work. So, any ideas how I can overcome this problem? Thanks!
That's right, unlike C++,constvariables in C are notconstant expressions. I don't think there is a portable way other than using the preprocessor: ``` #define rowmans_1_width 16 ```
In one of the place in my project, the crash is happening atmemcpy(). I analyzed the coredump and found that the pointer seems to be OK. The scenario is that the void buffer is the src and the charbuf[8]is the destination. Can copying thevoid *tochar *can cause crash at any situation? I have tried to reproduce the snippet here, but I didn't get any crash in the PC. ``` #include "stdio.h" void main() { void *buff = "Hero"; unsigned char buffer[5]; memcpy(buffer,buff,5); printf("The value of buffer is %s\r\n", buffer); } ```
You haven't includedstring.hand are ignoring the warning thatmemcpyhasn't been defined. This means that the args will be treated asints, and ifintand pointers are different sizes on your machine/compiler then the code will crash.
I have some functionfooand I want to get the elapsed time of it in the following format, for instance: ``` 1 seconds 101 milliseeconds 31 microseconds ``` or ``` 0 seconds 91 milliseeconds 101 microseconds ``` Now I use the following code for solving this problem: ``` static struct timeval t1, t2; gettimeofday(&t1, NULL); foo(); gettimeofday(&t2, NULL); unsigned long long t = 1000 * (t2.tv_sec - t1.tv_sec) + (t2.tv_usec - t1.tv_usec) / 1000; printf("elapsed time %llu ms\n", t); ``` I took this formula from the Net and not entirely understand it. Why I should 1000 multiplied by(t2.tv_sec - t1.tv_sec)? What's the best way of measuring elapsing time in POSIX with the milliseconds and microsecond accuracy?
Measuring time is a complex problem. Generally the best way is to useclock_gettime(). It supports several clocks with different characteristics. Checkthislink for more information.
Is it good practice to usetypedeffor putting units of measurement into name? (and rename standard types) Like this: ``` typedef int16_t MilliAmp_t; /* 1 mA */ ```
You are just renaming some types. It does not bring any additional checks in the compiler (unless that compiler is customized specifically; if usingGCCyou could consider customizing it thruMELT, but that customization is not a trivial task), in the sense that the following code ``` MilliAmp_t x=0,y=1,z=2; x = y * z; ``` will always compile without warnings (in C) even if physically multiplying two currents and put the result in some current variable does not make any sense. However, your typedef has a smalldocumentationvalue: if you declare a prototype like ``` MilliWatt_t electical_power (MilliAmp_t current, MilliVolt_t tension); ``` thensomereaders might find that helpful (but perhaps not me).
I am trying to compute the MacLaurin series for e-x= 1 - x + (x2/ 2!) - (x3/ 3!) +... My values seem to work up to a certain point and then deviate completely. Is there something wrong with rounding or am I using the wrong type of variable for such a question? ``` int i; double sum=0; double x = 8.3; for(i=0; i<26; i++) { sum = sum+ (((pow(-1,i)) * (pow(x,i)))/factorial(i)); printf("Sum = %.12f\n\n\n",sum); } return 0; ``` I don't understand why, but up to the 12th term, the values are correct but after that, it begins to completely differ.
Presumably yourfactorialfunction, which you're not showing, is performing integer arithmetic. After 12! you're going to overflow a 32-bit integer. Switch to usingdoublein thefactorialfunction too.
If I set a pointer to a struct to point to a block of memory via malloc, will all the members initialize to their respective default values? Such as int's to 0 and pointer's to NULL? I'm seeing that they do based on this sample code I wrote, so I just wanted someone to please confirm my understanding. Thanks for the input. ``` #include <stdio.h> #include <ctype.h> #include <stdbool.h> #include <stdlib.h> typedef struct node { bool value; struct node* next[5]; } node; int main(void) { node* tNode = malloc(sizeof(node)); printf("value = %i\n", tNode->value); for (int i = 0; i < 5; i++) { if (tNode->next[i] == NULL) printf("next[%i] = %p\n", i, tNode->next[i]); } } ```
malloc()function never initializes the memory region. You have to usecalloc()to specifically initialize a memory region to zeros. The reason you see initialized memory is explainedhere.
Is it good practice to usetypedeffor putting units of measurement into name? (and rename standard types) Like this: ``` typedef int16_t MilliAmp_t; /* 1 mA */ ```
You are just renaming some types. It does not bring any additional checks in the compiler (unless that compiler is customized specifically; if usingGCCyou could consider customizing it thruMELT, but that customization is not a trivial task), in the sense that the following code ``` MilliAmp_t x=0,y=1,z=2; x = y * z; ``` will always compile without warnings (in C) even if physically multiplying two currents and put the result in some current variable does not make any sense. However, your typedef has a smalldocumentationvalue: if you declare a prototype like ``` MilliWatt_t electical_power (MilliAmp_t current, MilliVolt_t tension); ``` thensomereaders might find that helpful (but perhaps not me).
I am trying to compute the MacLaurin series for e-x= 1 - x + (x2/ 2!) - (x3/ 3!) +... My values seem to work up to a certain point and then deviate completely. Is there something wrong with rounding or am I using the wrong type of variable for such a question? ``` int i; double sum=0; double x = 8.3; for(i=0; i<26; i++) { sum = sum+ (((pow(-1,i)) * (pow(x,i)))/factorial(i)); printf("Sum = %.12f\n\n\n",sum); } return 0; ``` I don't understand why, but up to the 12th term, the values are correct but after that, it begins to completely differ.
Presumably yourfactorialfunction, which you're not showing, is performing integer arithmetic. After 12! you're going to overflow a 32-bit integer. Switch to usingdoublein thefactorialfunction too.
If I set a pointer to a struct to point to a block of memory via malloc, will all the members initialize to their respective default values? Such as int's to 0 and pointer's to NULL? I'm seeing that they do based on this sample code I wrote, so I just wanted someone to please confirm my understanding. Thanks for the input. ``` #include <stdio.h> #include <ctype.h> #include <stdbool.h> #include <stdlib.h> typedef struct node { bool value; struct node* next[5]; } node; int main(void) { node* tNode = malloc(sizeof(node)); printf("value = %i\n", tNode->value); for (int i = 0; i < 5; i++) { if (tNode->next[i] == NULL) printf("next[%i] = %p\n", i, tNode->next[i]); } } ```
malloc()function never initializes the memory region. You have to usecalloc()to specifically initialize a memory region to zeros. The reason you see initialized memory is explainedhere.
When i execute this program i get a segfault and don't know why. It should return the factorial(?) of the input as long as it is bigger than 0. ``` #include <stdio.h> int factorial(int input) { if (input > 0) { return input * factorial(input--); } else { return 1; } } int main() { printf("%d", factorial(23)); return 0; } ```
factorial(input--)does not do what you think it does. Usefactorial(input-1). Here is apage that documents the post-decrement operatorthat should help in using it correctly. Youneverhave to use it. You can always do what you intend with+,-, and=(assignment). Your program is producing a segmentation fault because as you have written it,factorial(23)callsfactorial(23), resulting in astack overflow.
There is a piece of code I'm looking at that does: ``` int result = 0 ; char byte = foo[j] for (i = 7 ; i>0 ; i--) { byte = (byte & ~0x1)>>1 ; result+= array[i] * (byte & 1) ; } ``` I know that the objective of this code is to multiply the elements of the array for which the corresponding bits in byte are set to 1. I don't understand why the ~0x1 is necessary though, as every time, I'm only considering the last bit Any ideas?
Certain compilers implement >> by rotating bits instead of shifting them. This guards against this case (if the last bit is set to 0, then even if the shifting is implemented as a rotation, the answer will remain correct)
``` #include <stdio.h> #include <sys/stat.h> #include <stdlib.h> #include <time.h> int main(int argc, char*argv[]) { struct stat file; int n; if (argc != 2) { printf("Usage: ./a.out <filename>\n"); exit(-1); } if ((n = stat(argv[1], &file)) == -1) { perror(argv[1]); exit(-1); } printf("Block size : %d\n", file.st_blksize); } ``` Last line gives an error format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘__blksize_t’ [-Wformat=] How to print out "st_blksize" of data??
Actually,st_blksizeis aunsigned longtypedefed datatype, hence use ``` printf("Block size : %ld\n", file_st.blksize); ```
I am trying to learn ncurses but have hit an odd error. LINES and COLS appear to be set to 0, or else to something that is not anint: relevant parts of my code: ``` #include <stdio.h> #include <ncurses.h> ``` [...] ``` printf("%d\n%d\n%d\n",rand(),LINES,COLS); blk[i].pos[0] = (int)(rand()/LINES); blk[i].pos[1] = (int)(rand()/COLS); ``` This outputs: ``` 1556162876 0 0 Floating point exception ``` What am I doing wrong?
Per the ncurses documentation: The integer variables LINES and COLS are defined in <curses.h> and will be filled in by initscr with the size of the screen. So prior to callinginitscr, they are probably just 0.
In C, suppose I have an unsigned char A which can be either 0 or 1. I would like to find a bitwise logical operator that will convert A to !A. Note: I am using this code on a GPU, where bitwise operators are very cheap compared to logical operators. i.e. XOR is much cheaper than !
If by 'not' you mean send 1 to 0 and 0 to 1. you can use the XOR operator^to do that. If character is called c, you can writec = c ^ 1;.
This question already has answers here:Why sizeof(param_array) is the size of pointer?(8 answers)Closed8 years ago. The following is my code ``` main(){ char a[2]={'a','b'}; copy_arr(a); int i=1; char *s=a; printf("s=%d\n and",sizeof(s)/sizeof(*s)); printf("a=%d\n",sizeof(a)/sizeof(*a)); } ``` The output comes out to be s=4 and a=2 What does size of function returns in case of the pointer.
``` sizeof(s)/sizeof(*s) ``` This returns ``` sizeof(pointer)/ sizeof(s[0]) /* Note that s[0] = *s */ 4/1 ( I guess pointer is of size 4 on your system) = 4 ``` The other is ``` sizeof(a)/sizeof(*a) ``` sizeof(array)/sizeof(a[0])which is(2*1)/1 = 2
This question already has answers here:Changing value of const int using using pointer [duplicate](2 answers)Closed8 years ago. I got a program crash when I am trying to modify constant variable through a pointer. ``` #include <stdio.h> static const int x = 5; void changeX(int *x) { (*x) = 20; printf("%d", (*x)); } int main(void) { printf("Jelele"); changeX((int *)&x); return 0; } ``` I know it isn't a good practice and there is no need to make such that ... I am just testing something ... My question is: Why program crashes ?!
``` static const int x = 5; ``` This is a constant variable stored in read-only location so when you try to write to this location then you see a crash. Like ``` (*x) = 20; /* This is UB */ ``` Check the below link: Where are constant variables stored in C?
I am not really that advanced in C but I found this in a piece of code ``` ssize_t ret = 0; ret += sprintf(buf + --ret, "\n"); ``` What does this mean?And can we really do--retin this case?
``` ret += sprintf(buf + --ret, "\n"); ``` The above line does not mean anything, because it isUndefined Behavior (UB). Thus, the answer is an emphaticNo!. Why? Becauseretis written twice, and there is no intervening sequence-point. (The actual increment ofretcan happen at any time after reading it to determine the value of--ret, and before the closing semicolon.Thus, it conflicts with the change by the assignmentret += ....Also, the read ofretinret += ...conflicts with the update ofretin--ret.) As an aside, in C++ since C++11 (sequencing instead of sequence-points) it would be well-defined.
I have a switch case that looks like this: ``` switch ( class.Function() ) { case firstThing: { } break; case secondThing: { //call third thing } break; case thirdThing: { } break; } ``` Is there any way to call a specific case in C / Objective-C?
Don't know why you would want to do that, but in your example, if you simply leave out the break statement at the end of case secondThing: the user will continue through the subsequent case statement until they hit a break.
Without using the following code how can I initialize an entire column of a 2D-array with a particular value, say 1? ``` int a[row][col]; for(i=0; i<row; i++) { a[i][col]=1; } ```
As of C99, standardized 15 years ago, you can use explicit indexing: ``` int a[10][10] = { [0][0] = 1, [1][0] = 1, /* more code here */, [9][0] = 1 }; ``` With GCC you can use even more powerful syntax but of course you lose portability and are no longer programming in standard C.