question
stringlengths
25
894
answer
stringlengths
4
863
Is it possible to execute C code in a C program? For instance when reading input from the user.
There's nothing built in to do this. This simplest thing to do is save the given code to a separate file, invoke GCC as a separate process to compile the code, then run the compiled code in a new process.
I was thinking to solve my issue that is described in the following and then I ended with a question that I couldn't find an answer for it on Google. Question: Is it possible to use format specifier inside another format specifier in printf()? The issue is with size of leading zeros in printf() in following line of code: ``` uint16_t num=5; printf("%02d",num); ``` Is it possible to use a format specifier for that "2"? How can I adjust the size of leading zeros in the program based on different conditions (so it would be like %02d,%03d,%04d,...)? Except defining different categories and different printf() lines, is it possible to use a trick here? Is there any other function, rather than printf(), to solve the issue?
Yes, it is possible. See*width specifier ofprintf. Example: ``` printf("%0*d\n", 5, 2); ``` ... prints: ``` 00002 ```
``` int fputc(int c, FILE *stream); int fputs(const char *s, FILE *stream); ``` Why isn'tconst int crequired in fputc()'s declaration?
There's no point in marking parameters asconstin a function declaration. Arguments are passed by value, so the parameter is a copy anyway. It doesn't affect how the function can be called. However,const char *sdoes not meansisconst. What this declaration means is thatsis a pointer to aconst char; i.e. thefputsfunction promises not to write through the pointer it is given. Also, there is an implicit conversion fromchar *toconst char *(but not vice versa), meaning thatfputscan be called with both read-only and writeable strings.
I was thinking to solve my issue that is described in the following and then I ended with a question that I couldn't find an answer for it on Google. Question: Is it possible to use format specifier inside another format specifier in printf()? The issue is with size of leading zeros in printf() in following line of code: ``` uint16_t num=5; printf("%02d",num); ``` Is it possible to use a format specifier for that "2"? How can I adjust the size of leading zeros in the program based on different conditions (so it would be like %02d,%03d,%04d,...)? Except defining different categories and different printf() lines, is it possible to use a trick here? Is there any other function, rather than printf(), to solve the issue?
Yes, it is possible. See*width specifier ofprintf. Example: ``` printf("%0*d\n", 5, 2); ``` ... prints: ``` 00002 ```
``` int fputc(int c, FILE *stream); int fputs(const char *s, FILE *stream); ``` Why isn'tconst int crequired in fputc()'s declaration?
There's no point in marking parameters asconstin a function declaration. Arguments are passed by value, so the parameter is a copy anyway. It doesn't affect how the function can be called. However,const char *sdoes not meansisconst. What this declaration means is thatsis a pointer to aconst char; i.e. thefputsfunction promises not to write through the pointer it is given. Also, there is an implicit conversion fromchar *toconst char *(but not vice versa), meaning thatfputscan be called with both read-only and writeable strings.
I wanted to demonstrate that the preprocessor is totally independant of the build process. It is another grammar and another lexer than the C language. In fact I wanted to show that the preprocessor could be applied to any type of file. So I have this arbitrary file: ``` #define FOO #ifdef FOO I am foo #endif # # # Something #pragma Hello World ``` And I thought this would work: ``` $ gcc -E test.txt -o- gcc: warning: test.txt: linker input file unused because linking not done ``` Unfortunately it only work with this: ``` $ cat test.txt | gcc -E - ``` Why is this error with GCC?
You need to tellgccit's a C file. ``` gcc -xc -E test.txt ```
``` typedef struct test { int a; int b; int c; }_test; __ext_ram__ _test test1 = {0}; // Declared this global variable in external RAM ``` Do we need to use memset() for initializing it in external RAM? ``` memset(&test1, 0, sizeof(_test)); ```
Your linker do this for you. So first you define your variable (i. e. your struct). After that you declare your variable and use thesectionargument to place the variable in a given section: ``` _test __attribute__((section (".ram"))) MyStruct; ``` Now you have to create/modify your linker script to place the section in your RAM: ``` MEMORY { ... ram_data (rwx) : ORIGIN = RAM_start_addr, LENGTH = section_length ... } SECTIONS { ... .mySection section_address : { KEEP(*(.ram)) } > ram_data ... } ``` Compile it and your data is placed in RAM.
I want to print feasible solutions by adding up the maximum combinations of 2 indexes for n indexes where no index’s value can be added to itself Expected output for 4 indexes 1,2 1,3 1,4 2,1 2,3 2,4 3,1 3,2 3,4 4,1 4,2 4,3 Where I’m going wrong :: (Here’s my Code ) ``` for(i=1;i<n;i++) { for(j=1; j!=i && j<n; j++) { printf("%d,%d",i,j); } } ```
The error is you have specifiedj!=ibecause of which your inner loop will exit as soon as it encounters a condition wherejis not equal toiand will not continue for further values. You just want to skip the iteration wheni == jfor which you should use thecontinuestatement. ``` for(i = 0; i < n; i++) { for( j = 0; j < n; j++) { if(i==j) continue; printf("%d,%d", i,j) } } ```
I want to print feasible solutions by adding up the maximum combinations of 2 indexes for n indexes where no index’s value can be added to itself Expected output for 4 indexes 1,2 1,3 1,4 2,1 2,3 2,4 3,1 3,2 3,4 4,1 4,2 4,3 Where I’m going wrong :: (Here’s my Code ) ``` for(i=1;i<n;i++) { for(j=1; j!=i && j<n; j++) { printf("%d,%d",i,j); } } ```
The error is you have specifiedj!=ibecause of which your inner loop will exit as soon as it encounters a condition wherejis not equal toiand will not continue for further values. You just want to skip the iteration wheni == jfor which you should use thecontinuestatement. ``` for(i = 0; i < n; i++) { for( j = 0; j < n; j++) { if(i==j) continue; printf("%d,%d", i,j) } } ```
I am moving from mysql to MariaDB. With mysql I was linking the C connector to my application withmysql_config --libs, and according to what I can read on internet it should still be possible with MariaDB, but on my systemmysql_configdoes not exist and I do not know how to get it and if the copy I will eventually get will be still compatible with MariaDB. So the question is: how to link MariaDB to my C/C++ application? Debian 10 (Buster) 64 bits ~ mariadb-server Version: 1:10.3.15-1 ~ mariadb-client Version: 1:10.3.15-1 ~ Thank you in advance.
Well, this is what I do: sudo apt-get install libmariadbclient-dev And the link command will be-lmariadbclient
I am trying to understand this program. The code is: ``` ActiveBuffer->length += sprintf( ActiveBuffer->data + ActiveBuffer->length, "\"Timestamp[ms]\":%lld,\n", timestamp); ``` where ActiveBuffer is: ``` Buffer *ActiveBuffer; ``` andBufferis defined as: ``` typedef struct { int32_t length; char data[BUFFSIZE]; } Buffer; ``` I know that the function sprintf writes data to the buffer but I am unable to understand the additionActiveBuffer->data + ActiveBuffer->length.
Think ofActiveBuffer->data + ActiveBuffer->lengthas&ActiveBuffer->data[ActiveBuffer->length]. It's an offset into the buffer.
Which C standard header file defines the symbolic constant for theNULLcharacter (\0), which is the character used as string terminator? While I have defined it myself in the program as: ``` #define NULL_CHAR '\0' ``` I am looking for an appropriate way to do so. Additionally, assuming it's defined in some header file, will there be a downside of including the header file just for the purpose of accessing this character against defining it myself?
TheNULLmacro is defined in<stddef.h>. (It is also defined in several other headers.) It expands to anull pointer constantand is intended to be used with pointers, not with characters. There is no standard macro for'\0'. It is equivalent to0(character constants haveinttype), and a macro for it would be of limited use. The character'\0'is often referred to as a null character, but this is different from theNULLpointer constant.
``` #include <stdio.h> int main() { int p=10,q=20,r; if(r = p = 5 || q > 20) printf("%d",r); else printf("No output"); return 0; } ``` The output is 1 but how? Please explain
Precedence. To be more clear: ``` if(r = p = 5 || q > 20) ``` is the same as ``` if(r = p = (5 || q > 20)) ``` 5 is truthy, so the boolean expression evaluates to 1, which is then assigned tor
How can I define a global constant in C? I was told to do some thing like this in header.h ``` const u32 g_my_const; ``` in code.c ``` #include "header.h" const u32 g_my_const= 10U; ``` But I get a compilation error: error: uninitialized const 'g_my_const' [-fpermissive] Can some one explain how to do this properly.
Use in the header ``` extern const u32 g_my_const; ``` In this case this will be only a declaration of the constant and in the c module there will be its definition. ``` #include "header.h" const u32 g_my_const= 10U; ``` As it was already mentioned in a comment by@Thomas Jagerto your question you can use standard aliases for types by means of including the header<stdint.h> For example ``` #include <stdint.h> extern const uint32_t g_my_const; ```
This question already has answers here:What does a 'for' loop without curly braces do?(3 answers)Closed4 years ago. I am trying to understand how this bit of code below works. ``` while (c->next != NULL) c = c->next; c->points[c->pointNum] = p; c->pointNum++; ``` Are lines 2 and 3 here under the influence of the while loop? How does a one line while loop work?
The code could be rewritten like this to be clearer: ``` // advance until c->next is NULL while (c->next != NULL) { c = c->next; } // Now c is the last node in the chain c->points[c->pointNum] = p; c->pointNum++; ``` As you can see, your form takes advantage of the C language one-line support (blocks one line long need not be enclosed by braces). And as you experienced, this form, while more compact, can be more confusing.
In the following example I want to replace the 2 in FOREACH(2, CREATE) by the TWO macro. How do I do that? Currently if i put FOREACH(TWO, CREATE), it will take TWO as a string instead of translating it to 2. ``` #define FOREACH1(f) f(0) #define FOREACH2(f) f(1) FOREACH1(f) #define FOREACH(n, f) FOREACH ## n(f) #define TWO 2 #define CREATE(a) int c ## a; FOREACH(2, CREATE); int main(int argc, char*argv[]) { c0 = 1; printf("sum = %d\n", c0); } ```
You need another level of macro expansion forFOREACH: ``` #define FOREACHX(n, f) FOREACH ## n(f) #define FOREACH(n, f) FOREACHX(n, f) ```
I started learning to code with the C language. I wrote the following program: ``` #include<stdio.h> int main() { int count = 0; printf("Count %d.", count); return 0; } ``` Then I compile and run the program, the data is printed: ``` Count 0.% ``` But if I fix the lineprintf("Count %d.", count);intoprintf("Count %d.\n", count);, just adding\nafterCount %d., then the data printed is: ``` Count 0. ```
Your shell is likely adding a%sign to indicate that the line was not properly terminated. Many shells do this, like for example ZSH or Fish. ZSH should also be the default shell on macOS. Just add a\nto your call toprintfand you're good.
When I start my program I cannot insert only one number as "number 1" but two. ``` #include <stdio.h> #include <stdlib.h> int main() { int sum = 0; int array[5] = {}; for(int i = 0; i < 5; i++) { printf("Insert number %d \n", i+1); scanf("%d%", &array[i]); } for(int i = 0; i < 5; i++){ sum = sum + array[i]; } printf("Sum is %d \n", sum); return 0; } ```
Remove the second % in ``` scanf("%d%", &array[i]); ``` to be ``` scanf("%d", &array[i]); ```
My goal is to write a function which receives an unsigned char as input, and returns a modified unsigned char as an output. The char should be modified so that its first three bits are set as zeros, and the rest are left untouched. Example function written below. Any help is greatly appreciated. Apologies for the somewhat incomplete question, this is the most accurate description I can give. ``` unsigned char Changebits(unsigned char b) { //set the first three bits of the input to zeros (for example 10110111 -> 00010111) return //insert the modified unsigned char here } ```
Please read something aboutbitmanipulationin C. So your solution looks something like this (assuming 1 byte char) ``` unsigned char Changebits(unsigned char b) { return (b & 0x1Fu); } ```
My goal is to write a function which receives an unsigned char as input, and returns a modified unsigned char as an output. The char should be modified so that its first three bits are set as zeros, and the rest are left untouched. Example function written below. Any help is greatly appreciated. Apologies for the somewhat incomplete question, this is the most accurate description I can give. ``` unsigned char Changebits(unsigned char b) { //set the first three bits of the input to zeros (for example 10110111 -> 00010111) return //insert the modified unsigned char here } ```
Please read something aboutbitmanipulationin C. So your solution looks something like this (assuming 1 byte char) ``` unsigned char Changebits(unsigned char b) { return (b & 0x1Fu); } ```
RecentlyI asked in this forum , whether it is an error or not to use the following if statement which involves bit shifting of given x and y: ``` if (x<<y) ``` The conclusive answer for that question what that the statement as written above is not any kind of error , not a run-time error as well. Suppose we would expand the scope of that question and rewrite the statement above to be the following one instead: ``` if (x<<y) x++; ``` in this case, would it still have no error of any kind ( including run-time error) ?
Without any surrounding context, it is impossible to tell if this code will have any run-time errors: ``` if (x<<y) x++; ``` We don't know the types or values ofxory, nor do we know what the code is expected to do. So the closest thing to an answer we can give you is, "We don't know."
When I useprintfto print pointer values, they display in the format:000000000066FE14. I would like them to display in the0xformat, such as:0x66FE14. This is the simple test program I wrote to print pointer values: ``` #include <stdio.h> int main() { int x = 4; int *xAddress = &x; printf("Address of x: %p\n", xAddress); return 0; } ``` This produces the output: ``` Address of x: 000000000066FE14 ```
Try using theuintptr_ttype: ``` #include <stdio.h> #include <inttypes.h> #include <stdint.h> int main() { int x = 4; int *xAddress = &x; printf("Address of x: 0x%" PRIXPTR "\n", (uintptr_t) xAddress); return 0; } ```
If an C/C++ app call rename(https://linux.die.net/man/3/rename) function where 'newpath' is in a different disk volume/partition and assume the copying from current path to new path consume time. Does'rename' call block until copying from current to new is completed ? or does it return immediately (or quickly) while copying happen asynchronously ?
I'd imagine it would return immediately with an error code: ``` Errors The rename() function shall fail if: [...] EXDEV The links named by new and old are on different file systems and the implementation does not support links between file systems. ``` That said, I don't have a Linux box handy to test with, so I could be wrong about that.
If an C/C++ app call rename(https://linux.die.net/man/3/rename) function where 'newpath' is in a different disk volume/partition and assume the copying from current path to new path consume time. Does'rename' call block until copying from current to new is completed ? or does it return immediately (or quickly) while copying happen asynchronously ?
I'd imagine it would return immediately with an error code: ``` Errors The rename() function shall fail if: [...] EXDEV The links named by new and old are on different file systems and the implementation does not support links between file systems. ``` That said, I don't have a Linux box handy to test with, so I could be wrong about that.
The print function did something more than expected and this behavior changes from language to language. Please look at the given code. Python 3 code: ``` n=print("Interesting") print(n) ``` Output: ``` Interesting None ``` C code: ``` #include<stdio.h> int main(){ int n = printf("Interesting"); printf("\n%d",n); } ``` Output: ``` Interesting 11 ``` I expected the output to be some kind of error but instead both the languages handle it differently. Please explain why this happens and is the print function capable of doing something else other than just displaying?
printandprintfare functions that can have a return value. In Python,printsimply returnsNone. In C, the signature ofprintfisint printf( const char* format, ... );. It returns an integer equal to the number of characters output. A negative return value indicates that an error occurred.
Why can I not do this? ``` fopen("%s",stringarray,fpointer); ``` The above returns an error that says too many arguments to function. But this works, ``` fopen("file.txt",fpointer); ``` How can I get around this problem? Do I have to modify the headers in the code?
You cannot call ``` fopen("%s",stringarray,fpointer); ``` because that's not the wayfopenworks. You don't get to make up the way you want to call a standard function like this -- you have to call it the waythe documentationsays to. You can't call ``` fopen("file.txt",fpointer); ``` either. You have to call something like ``` fpointer = fopen("file.txt", "r"); ``` assuming that you have declared ``` FILE *fpointer; ``` so thatfpointerwill be your "open file pointer" or "file handle" as you read the filefile.txt.
so i am learning c today. I wrote some code to get input with getchar() and save it in a variable to understand how the input to integer works. So if give a input with my keyboard like "1" and press enter i get a Value of 4910 back. I expected the value of 49 cause the decimal Ascsii code for the Char "1" is 49. Where does the 10 come from? ``` #include <stdio.h> /* count lines in input */ main() { int c; while ((c = getchar()) != EOF) printf("%d",c); } ```
10 is the ASCII code of the newline character,'\n'. You input this character when you hit Enter.
The print function did something more than expected and this behavior changes from language to language. Please look at the given code. Python 3 code: ``` n=print("Interesting") print(n) ``` Output: ``` Interesting None ``` C code: ``` #include<stdio.h> int main(){ int n = printf("Interesting"); printf("\n%d",n); } ``` Output: ``` Interesting 11 ``` I expected the output to be some kind of error but instead both the languages handle it differently. Please explain why this happens and is the print function capable of doing something else other than just displaying?
printandprintfare functions that can have a return value. In Python,printsimply returnsNone. In C, the signature ofprintfisint printf( const char* format, ... );. It returns an integer equal to the number of characters output. A negative return value indicates that an error occurred.
Why can I not do this? ``` fopen("%s",stringarray,fpointer); ``` The above returns an error that says too many arguments to function. But this works, ``` fopen("file.txt",fpointer); ``` How can I get around this problem? Do I have to modify the headers in the code?
You cannot call ``` fopen("%s",stringarray,fpointer); ``` because that's not the wayfopenworks. You don't get to make up the way you want to call a standard function like this -- you have to call it the waythe documentationsays to. You can't call ``` fopen("file.txt",fpointer); ``` either. You have to call something like ``` fpointer = fopen("file.txt", "r"); ``` assuming that you have declared ``` FILE *fpointer; ``` so thatfpointerwill be your "open file pointer" or "file handle" as you read the filefile.txt.
so i am learning c today. I wrote some code to get input with getchar() and save it in a variable to understand how the input to integer works. So if give a input with my keyboard like "1" and press enter i get a Value of 4910 back. I expected the value of 49 cause the decimal Ascsii code for the Char "1" is 49. Where does the 10 come from? ``` #include <stdio.h> /* count lines in input */ main() { int c; while ((c = getchar()) != EOF) printf("%d",c); } ```
10 is the ASCII code of the newline character,'\n'. You input this character when you hit Enter.
I'm studying the preprocessors and got stuck with arrays. I use below preprocessor to initialise an array containing pre defined values. ``` #ifndef ARRAY #define ARRAY const char arr[]={10,20,30,40,50,60,80}; #endif ``` But their comes a problem. I want to take user input in that array. So, how can I write an array of dynamic size with preprocessor so that I can also take user input in it. I've tried this but it gives me an error. ``` #define n 0 #ifndef ARRAY #define ARRAY const char arr[n] {}; #endif ```
Preprocessor is going to happen once, before compiling, so you will have to figure out the maximum size of the array beforehand, in order to set a fix size,like this. Otherwise, you will have to use theheap(malloc or realloc) orVLAsto create an array whose size depends on the user(in your particular case) at runtime.
I'm going to read data directly from a "gz" format file. Using "zlib" in c, I read the data from gz file and now I have an unsigned char array namely "str". I want to extract double numbers using "sscanf". here is my code: ``` printf("%s\n", str); double d1,d2,d3; sscanf(str, "%lf %lf %lf", &d1, &d2, &d3); printf("%lf\n", &d1); printf("%lf\n", &d2); printf("%lf\n", &d3); ``` and the output is: ``` 23.323 1111.232 434434.1 0.000000 0.000000 0.000000 ``` it seems I have successfully read str from gz file, but I cannot read doubles from str.
This will work. This is because%lfexpect adoublevalue and you were passing a pointer to adoublevalue. ``` printf("%lf\n", d1); printf("%lf\n", d2); printf("%lf\n", d3); ```
So here is my code ``` #include <stdio.h> int main(void) { unsigned char ch = 244; ch = ch << 31; return 0; } ``` I can shiftchupto 31 bits that's meanschis of 32 bits but how ?sizeof(ch)is also 1 byte only.
[...] that meanschis of 32 bits [...] ? It isn't. The result of the shift, which is of typeint, is truncated to 8 bits when assigned back toch. You can verify this by examining the value ofch. gccspots this if-Wconversionis turned on: ``` $ gcc -Wconversion test.c test.c:4:13: warning: implicit conversion loses integer precision: 'int' to 'unsigned char' [-Wconversion] ch = ch << 31; ~ ~~~^~~~~ 1 warning generated. ```
I have an issue while developing the application, that is browsing devices in local network via mdns. Under windows 7 i used bonjour api from apple and all was great. After updating win7 to win10 bonjour can still find devices but it can not resolve connection to them. I found the solution that with Windows 10 Microsoft made inside solution with WINAPI and i found that:https://learn.microsoft.com/en-us/windows/win32/api/windns/nf-windns-dnsservicebrowse. Entire DNS functions like 'DnsServiceBrowse' etc.. but I can not see them into "windns.h" header like it is specified into documentation. Even in dnsapi.dll i could not find any symbols to those functions. I am working with SDK 10.0.17763.0 under visual studio 2017. My windows 10 version is 1903. Am I missing something?
It is located at the latestWindows SDK 10.0.18362.0.
i want to read a full sentence in c language using scanf but when the last character of the sentence is "n" i'am unable to do it!! i tired usingscanf("%[^\n]%*c", s); ``` #include<stdio.h> int main(){ char c,w[50],s[300]; scanf("%c%s%[^/n]",&c,w,s); printf("%c\n%s%s",c,w,s); } ``` For this input:- ``` z Learning C is fun ``` Output is:- ``` z Learning C is fu ``` Expected Output:- ``` z Learning C is fun ```
Using%[^/n]will causescanfto read input until a/or annis encountered. To read input until a newline is encountered, use%[^\n].
I have some *.c files. I want to have two binary from them for example: ``` a.c b.c -> ab d.c e.c -> de ``` The a.c and d.c has main() function. This is my code: ``` gcc a.c b.c -o ab.o -c gcc -o ab ab.o gcc d.c e.c -o de.o -c gcc -o de de.o ``` I put this code in post-build-steps in codeblocks. The problem is when I compile the project it fails because of two main.
You can use a Makefile and put two binaries on it. You can find some informations on this topic for example :A Makefile with Multiple Executables
This question already has answers here:Need help understanding "getbits()" method in Chapter 2 of K&R C(6 answers)Closed4 years ago. In ANSI C section 2.9, the bitwise operators, I am unable to understand this particular code. I know how each bitwise operator works, but combinations need some help. ``` getbits(x, 4, 3) unsigned getbits(unsigned x, int p, int n) { return (x >> (p + 1 - n)) & ~(~0 << n); } ```
~0is anintmade of binary ones (111...111111)~0<<nintroducesnzeros in the lower bits (111...111000).~(~0<<n)flips the bits (000...000111)x>>(p+1-n)shiftsxtowards the lower bits (00XXX...XXXXXX).The&operation combines the previous two results: upper zeros are kept as zeros and the lowerXbits (facing the ones) are kept as is (00000...000XXX). Thus this function retrieves an-bit pattern ofxfrom bitp, but shifted(p+1-n)positions towards lower bits (ie, placed at the lower position).
This question already has answers here:What does casting to `void` really do? [duplicate](4 answers)Closed4 years ago. I am exploring an sdk and I came across the following set of statements. ``` uint32_t init_time = 0; init_time = get_current_time_in_ms(); (void)init_time; // What does this statement do? ``` My first thought was that this is a NULL check of some sorts but I tried zero and non-zero value in a test C code doing something similar but response in both case was the same. Any help would be appreciated.
This statement does not do anything logically. It is sometimes added to avoid warnings in compilers and Static Analysers for unused variables
``` #include<stdio.h> static char c; static int i; static float f; static char s[100]; void main () { printf("%d %d %f %s",c,i,f); } ``` I expect the error in output, but the actual output is0 0 0.000000 (null)
Your format string expects 4 arguments but you only pass 3. Doing so invokesundefined behavior, meaning you can't predict the behavior of the program. In this case the string "(null)" is printed, but your code could print some random sequence of characters, no extra characters, or it could crash. There's no guarantee. Whatprobablyhappened is that the%sformat specifier attempted to read the next 8 bytes on the stack to get a pointer, and those 8 bytes happened to all be 0, so the string "(null)" is printed because it read a NULL pointer. But again, there's no guarantee of that. Also see,What is the behavior of printing NULL with printf's %s specifier?.
I have a resistance output in my program. Now I want to convert that to temperature. So for that I have a list of resistance vales and it's corresponding temperature and that list has 400 values. I am programming it in Embedded C for my AVR microcontroller. I was thinking of making a function with for loop but the number of values are very large so it is not a good idea. I expect that if I give resistance to be 70 ohms then that function or program should check in that list for the temperature at 70 ohms.
I would take the 400 data points you have, drop them into excel/program of your choice, and generate a regression function (likely linear, if it's resistance to temperature). If you're worried about speed, AVR's sometimes have pipelines for L/S, MUL, and ADD, so it could potentially be faster to calculate it than look it up.
This question already has answers here:What does casting to `void` really do? [duplicate](4 answers)Closed4 years ago. I am exploring an sdk and I came across the following set of statements. ``` uint32_t init_time = 0; init_time = get_current_time_in_ms(); (void)init_time; // What does this statement do? ``` My first thought was that this is a NULL check of some sorts but I tried zero and non-zero value in a test C code doing something similar but response in both case was the same. Any help would be appreciated.
This statement does not do anything logically. It is sometimes added to avoid warnings in compilers and Static Analysers for unused variables
``` #include<stdio.h> static char c; static int i; static float f; static char s[100]; void main () { printf("%d %d %f %s",c,i,f); } ``` I expect the error in output, but the actual output is0 0 0.000000 (null)
Your format string expects 4 arguments but you only pass 3. Doing so invokesundefined behavior, meaning you can't predict the behavior of the program. In this case the string "(null)" is printed, but your code could print some random sequence of characters, no extra characters, or it could crash. There's no guarantee. Whatprobablyhappened is that the%sformat specifier attempted to read the next 8 bytes on the stack to get a pointer, and those 8 bytes happened to all be 0, so the string "(null)" is printed because it read a NULL pointer. But again, there's no guarantee of that. Also see,What is the behavior of printing NULL with printf's %s specifier?.
I initialized q.size with 7 within main function, Then first it print q.size value as 7, but after the scanf() statement the value of q.size become 0. Why this is happening and how to solve it??? ``` #include <stdio.h> #include <stdlib.h> struct sample { int size; int rear; int front; }; int main() { struct sample q; q.size=7; char Ans; printf("%d\n",q.size); printf("Enter character : (y/n)"); scanf("%s",&Ans); printf("%d",q.size); return 0; } ``` Expected result from q.size after scanf() as 7 Actual result is 0
You're reading a string%sinto acharvariable, this causes memory corruption. You have to put%cinscanfinstead of%sin order to read a character.
I found that it can't create a zombie process when I removeexit(0);from the child part. Can you tell me why? ``` #include <stdio.h> #include <stdlib.h> #include <sys/types.h> int main() { if(!fork()) { printf("child pid=%d\n", getpid()); exit(0); } sleep(20); printf("parent pid=%d\n",getpid()); exit(0); } ```
A zombie process is a dead child process that the parent process hasn’t checked on. In the original code, the child ends 20 seconds earlier than the parent, so it’s a zombie for 20 seconds. If you remove the firstexit(0), they both stay alive for 20 seconds because in the child, control passes right out the bottom of theifblock unless something stops it. Thus, if you remove the child'sexit()then not only is it unlikely to go zombie for an observable amount of time, but you should see it print a "parent pid" message in addition to its "child pid" message.
In a function with variable arguments, we initialize an object of type va_list ,'ap' with the function va_start() as: ``` void va_start(va_list ap, parmN); ``` I don't understand1.what type of objects can be passed as parMN(last known parameter). I've done with examples of passing integers, strings with format specifiers, structures etc.2. How the parMN describes the following optional parameters.
The C standard says thatva_start()is actually a macro, not a function, so it can do things a function couldn't. The details are highly implementation dependent but you could imagine that it takes the address of parmN to determine the stack address of the next parameter. There's no need forva_start()to know about the types of the following parameters because that information is passed tova_arg(), which is another macro.
The main objective is to know if there is a way to start or execute any user-mode application from UMDF (User Mode Driver Framework) event. It doesn't matter about the event. Any event may work e.g. DriverEntry, DeviceAttach I am working on a solution to start an application, when the windows boots up. I have tried start from driver, but not found any way to include 'process.h' library, which have a function call 'system('app_name') to start. But no luckI have tried injecting DLL with injdrvhere!, but found no way out I highly appreciate if you suggest any work-around. Thanks in advance
Directly from UMDF2.0, I don't think that you can. What you can do is to use Task Scheduler to run any.EXE that you want with an Event Trigger. The event will be "fired" from the UMDF (or Even from KMDF), you can use ETW or Windows Event log.
This question already has an answer here:What is the meaning of "%-*.*s" in a printf format string?(1 answer)Closed4 years ago. I don't know how this code is working? ``` #include<stdio.h> int main() { char *s = "PRO coder"; int n = 7; printf("%.*s", n, s); return 0; } ``` The result I am getting is "PRO cod"
printfformat string%.*stakes two arguments,*for the number and finallysfor a string, so it prints the first 7 characters of the string pointers. In general, anytime there is a number, you may use*instead to read it as an argument. %7swould print seven characters or more if the string were longer, while%.7swould print up to seven characters. So sometimes one would write"%*.*s", 7, 7, sto print exactly 7 characters.
I am trying to store value of SP register to a variable in C, here is my code: ``` int address = 0; asm volatile ("STR sp, [%0]\n\t" : "=r" ( address) ); ``` but after executing this code, os print "Segmentation fault" message in screen and terminate the programme. can any one give me a advise to solve the problem?
You shouldn't even touch the stack pointer in inline assembly. It's a taboo!!! You aren't supposed to do that to start with. Just leave it to the compiler. If you aren't altering the stack pointer or writing anything onto the stack, it might work, you just used the wrong instruction. What you want to do: copy the stack pointer to a 32bit register. What you did: store the stack pointer itself to the address 0. ==> segmentation fault. ReplaceSTR sp, [%0]\n\twithmov %0, sp\n\t
For examples, inpgtable_types.h, the function prototype: ``` extern pte_t *lookup_address(unsigned long address, unsigned int *level); ``` Is clearly present in the header file. However when I compile a kernel module with this function and then insmod the.kooutput file I get alookup_addresssymbol not found error. Why is this?
Does your module have aMODULE_LICENSE("GPL v2")line in it? If not, it is assumed to be proprietary and will not allow access to GPL symbols whichlookup_addressis marked as.
The following C program that uses Python.h: ``` $ cat > test.c #include <python3.7/Python.h> int main() { Py_Initialize(); Py_CompileString("foo", "bar", 0); Py_Finalize(); } ^D ``` ...has a segfault: ``` $ gcc test.c -lpython3.7m $ ./a.out Segmentation fault (core dumped) ``` Debugging with gdb it crashes in: ``` PyParser_AddToken () from /usr/lib/x86_64-linux-gnu/libpython3.7m.so.1.0 ``` Any ideas?
Thestartvalue is supposed to bePy_eval_input,Py_file_input, orPy_single_input, not0.
Today, I usePyImport_AppendInittabto append python modules built in C.PyImport_AppendInittabneeds to be called beforePy_Initialize. I can't finalize and then initialize the engine again. The problem is that now I need to append some modules afterPy_Initialize. Is there a way to do it? I'm using Python 3.6.
Solved the problem by doing this: ``` if (Py_IsInitialized()) { PyImport_AddModule(module_name); PyObject* pyModule = moduleInitFunc(); PyObject* sys_modules = PyImport_GetModuleDict(); PyDict_SetItemString(sys_modules, module_name, pyModule); Py_DECREF(pyModule); } ``` See thisanswer.
I'm building a third-party C library with emcc (version 1.38.38) in two steps: Building static library (using emar) with *.a extensionBuilding a separate file with that static library. Unfortunately I'm getting undefined symbols. What I've tried so far: To build without emcc, using clang or gcc - everything working as expectedTo check whether symbols are in the library built (they are) It looks like I'm missing something very elementary which I yet failing to find an answer about, so I'm asking you: How to build static library that I can use later on while compiling code with emcc?
So, OK, I was stupid enough to ask this question, let me contribute to the community and confess what was the problem, may be it will help for someone else. This code works: ``` emcc -s WASM=1 -Isrc main.c src/lib.a ``` while this won't ``` emcc -s WASM=1 -Isrc src/lib.a main.c ``` The order is imporant so shame on me.
i have a trouble with : ``` system("cd mypath"); ``` when i try this in C programming language terminal doesn't do anything. i need help.
Thesystemfunction creates a whole new process, separate from the one calling the function. Each process have its own current working directory associated with it, and this working directory is specific to that process only. Changing the working directory of one process will not change it for another process. If you want to change the working directory of your own process use operating-system specific functions to to it. Likechdiron Linux (and other POSIX system like macOS), orSetCurrentDirectoryin Windows. Note that if you change directory in your own process, the directory of the shell or console that invoked your program will not be changed, as it's also a separate process from yours.
I want to get the Physically Installed RAM of the computer among other system information. Once I try to compile the code, it gives the error "undefined reference toGetPhysicallyInstalledSystemMemoryalong with a warning that states that's an implicit declaration. I'm using Code::Blocks 17.12 and the latest GCC. ``` #define WINVER 0x0A00 #define _WIN32_WINNT 0x0A00 #include <stdio.h> #include <stdlib.h> #include <windows.h> int main() { long ram; BOOL Checkram; Checkram = GetPhysicallyInstalledSystemMemory(&ram); printf("Installed RAM is: %lu", ram); return 0; } ``` I'm very new to C programming and I did read the Microsoft documentation but it still didn't help me to solve this problem. Update: I've compiled it with Visual Studio and now it works.
I've switched to visual studio and it resolved the problem.
I get 'Permission denied' whenever I try to compile and run a program in Visual Studio code, in my Mac. How do I solve this? Note the 'permission denied' in this picture
You need to say something like ``` gcc -o film film.c ``` and then ``` ./film ``` film.cis your source file. In the example I've shown, the-oflag asksgccto put its output -- the compiled program -- in filefilm(with no conventional suffix).That'sthe file you want to run.
Can we create a new data type, which will stored another data types such as: integer, char, double? So we can stored anything in variable of this type. If not, why not?
Assuming you are talking about C you can use an union : ``` typedef union { int myint; double mydouble; char mychar; } u_mydatatype; // define a new variable u_mydatatype data; // access the members according to the type you want to match data.mychar = '3'; ``` Note that all the union members stands in the same memory space (the size of the union is the size of the larger member), so if you assign by example an int to your union, the value will be irrelevant if you use it as a char, so take care of knowing the representation of the value stored in the union when you use it.
I have this matrix: ``` 1 1 1 2 2 1 2 2 ``` I want to count the occurrences of the row that have values 1 1 in it's columns. How do I do it?
Here is the not-so-scalable C way. ``` #include <stdio.h> int main(void){ int matrix[4][2] = {{1,1},{1,2},{2,1},{2,2}}; int i, j, counter=0; for (i=0;i<4;i++) { if (matrix[i][0] == 1 && matrix[i][1] == 1) counter++; } printf("count %d", counter); } ```
Does using fopen(fileName, "w") overwrite the blocks being used by a file, or does it set the blocks that were once being used as free and then start writing to new blocks?
The C standard doesn’t specify how it’s implemented. So, itmightoverwrite the blocks, but there’s no guarantee. On a Unix/Unix-like environment, for example, it’s most likely a wrapper aroundopen()with some internalFILE *manipulation that we need not worry about.
In C,0.55 == 0.55fis false while0.5 == 0.5fis true. Why is it different? Comparing0.55:#include <stdio.h> int main() { if (0.55 == 0.55f) printf("Hi"); else printf("Hello"); }OutputsHello.Comparing0.5:#include <stdio.h> int main() { if (0.5 == 0.5f) printf("Hi"); else printf("Hello"); }OutputsHi. For both the code snippets, I expectedHello.Why this difference?
0.5is adyadic rationaland of an appropriate magnitude so0.5is exactly one-half either as afloator adouble. The same cannot be said for0.55. Adoublewill store that number with no less precision than afloat, and most likely more. In both cases, thefloatis implicitly converted to adoubleprior to==, but by then any truncation has taken place.
I have a bunch of arrays of various lengths and I'd like to keep the length close to the array, is it bad programming practice to define something like this? ``` typedef struct Array { long len; int* buf; } Array; ``` Are there any obvious downsides or pitfalls to this?
No, not necessarily. You will need to pass the length of a buffer around with the pointer to make sure that you don't overrun it. It would be a slight performance hit due to the extra dereference, but that can be a worthwhile tradeoff if always having the length available avoids causing bugs. You would need to make sure that the length gets updated if you resize the buffer, and make sure that the buffer gets freed if you free your struct. Other than that, it makes sense to me, and it's what a lot of other higher-level languages do in their array implementations.
This question already has answers here:What is special about numbers starting with zero?(4 answers)Closed4 years ago. I was trying the following code ``` printf("%d", 010 % 10); ``` I was expecting it output be 0, but it is 8. Why? Is there any way to get the last digit of an integer which is taken as input.
Any numeric literal in c or c++ starting with a zero will be interpreted asoctal So your calculation is 8 modulo 10, which is 8
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.Closed4 years ago.Improve this question I often see thisC grammarin books. However it seems<identifier>is never declared. Am I missing something or is this grammar incomplete?
I can't speak for whether the grammar is complete, but<identifier>is a token (i.e. a terminal), in the same way as e.g.<string>and many others are. Tokens are not defined in the grammar itself but rather in a lexer specification. The lexer is a component of most parser systems, which reads the raw input and turns it into a stream of higher level tokens (a.k.a. lexemes) that the parser then consumes.
im trying to read a content of the file "sym.dat" even thru file has contents fread returns zero and i tried using ferror too but it didnt show any error. ``` FILE *fp; fp=fopen("sym.dat","ab"); struct node a; fseek(fp, 0L, SEEK_SET); while((fread(&a,sizeof(struct node),1,fp))==1) { printf("bello"); }} ``` it returns 0
doing fp=fopen("sym.dat","ab"); you open the file towritein it from its end, not toreadin it, so the test inwhile((fread(&a,sizeof(struct node),1,fp))==1)is immediately false and you do not print "bello" do ``` fp=fopen("sym.dat","rb"); ``` and checkfpis not NULL. Thefseekis useless, when you open it you are at its beginning Do not forget to close the file If you need to read and write in it open it with the flags "rb+", thefseekis still useless.
In GTK3, how do I get a DrawingArea to respond keyboard events? Should I connect the DrawingArea with a signal or is it more compicated? I'm using GTK3 with the C language.
I fianlly found the solutionhere. I only connected the signal, but the GTK_CAN_FOCUS also need to be set for the drawingrea.
I am trying to learn Signals. I know invalid memory access will cause segfault. So, I register a signal handler for SIGSEGV signal. ``` #include <stdio.h> #include <signal.h> void sighandler(int signum) { printf("%s\n", __func__); } int main() { int *a = NULL; signal(SIGSEGV, sighandler); *a = 5; return 0; } ``` Running this code, I am continuously getting SIGSEGV Signals. I thought i should only get the signal once. Can you guys explain why I am getting signals continuously
After the SEGV handler finishes, the instruction that triggered re-executes. Since you didn't do anything to prevent the next execution from faulting, you get SEGV again, ad infinitum. See more inthis answer.
So, I'm learning the code forthe SplitMix64 generatorand came upon this part here: ``` uint64_t z = (x += 0x9e3779b97f4a7c15); ``` Not being a C programmer, I don't really understand this construct. Does the above mean z gets assigned value of xafterx is incremented, like so: ``` x += 0x9e3779b97f4a7c15; z = x; ``` Or does that mean z gets the value of xbeforex is incremented, like so: ``` z = x; x += 0x9e3779b97f4a7c15; ``` And also, does the same behavior happen in C# ?
z gets assigned value of xafterx is incremented. Think of it like this: ``` z = (x = x + 0x9e3779b97f4a7c15); ``` The return value of an assignment is always the value of the left-hand side of the assignment after the assignment is completed.
C 11 6.3.1.3, for cast: Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type. When I try ``` printf("%d", (unsigned short) 0x80000001); ``` I expect the result is65535but I got1. Why1is returned in this case?
0x80000001=2147483649The maximum value ofunsigned shortis65535. One more than that is65536."the value is converted by repeatedly... subtracting one more than the maximum value".Repeadedly subtracting until value in range (smaller than 65536) is the same as modulus.2147483649 % 65536=1. But this is the formal theory - in practice, this is the very same as simply taking the lowest 16 bits of0x80000001, which is the value0x0001.
I installed mingw on linux and tried compiling a code for windows, this code is intended for posix systems, because I use the% m converter, but realize that when using the _POSIX_C_SOURCE 200112L macro, I can use the converter, so mingw provides a library C that supports the posix pattern? ``` #define _POSIX_C_SOURCE 200112L #include <stdio.h> int main(void){ char *a; scanf("%ms", &a); puts(a); return 0; } ```
MinGW supports a subset of POSIX-like features (%ms,alarm,signal, etc.) on top of MSVCRT, but it's not POSIX-compliant. If you need a POSIX-compliant environment on Windows, use Cygwin.
I tried to remove coverage data on my test driver file "test.c". Below is what I was using after reading some similar questions in SO. ``` $ lcov --remove test.gcda -c -d . -o a.info --rc lcov_branch_coverage=1 ``` but I got an error below. Can anyone help? ``` lcov: ERROR: only one of -z, -c, -a, -e, -r, -l, --diff or --summary allowed! Use lcov --help to get usage information ```
-ris the same as--remove. And the error message says that you cannot use-rand-cat the same time. Remove the-cparameter.
I got confused of the type of an integer constant, as describedhere: On the first row, if a constant ended without'u', why decimal constant must besignedtype, while octal or hexadecimal constant can be anunsignedtype? I think that taking the constant as an unsigned version if thesignedversion do not fit has problem, for example: ``` long long l1 = 0xffffffff + 0xffffffff; // 0xffffffff is unsigned int long long l2 = 4294967295 + 4294967295; // 4294967295 is signed long ``` l1 is fffffffe, while l2 is 1fffffffe. and obviously l1 is wrong
If I were to say, I'd answer with thathexadecimal and octal numbers represent bit pattern more closelythan decimal ones, and therefore the C standard committee has decided that hex and oct numbers may be unsigned even withoutUsuffix. Think about how many people would write code like this: ``` uint32_t b = a & 0xFFFFFFF0; uint32_t b = a & 4294967280; // or -15? ```
I was assigned to make a program which will output the user's message: reversed, vertically and vertical upside down. I did vertical upside down by total accident but now I can't figure out vertical. ``` include <stdio.h> #include <stdlib.h> #include <string.h> main(){ char str[100]; int i, len; printf("Enter a message \n"); gets(str); len =strlen(str); printf("The message reversed: \n"); for(i = len - 1; i >= 0; i--) { printf("%c", str[i]); } printf("\n"); printf("The message vertical upside down \n"); for(i = len - 1; i >= 0; i--){ printf("%c \n", str[i]); } printf("\n"); system("pause"); } ``` To be able to output message vertically and also corrections if vertical upside down is incorrect.
How about ? ``` for (i = 0; i < len; i++) { printf("%c\n", str[i]); } ```
I installed mingw on linux and tried compiling a code for windows, this code is intended for posix systems, because I use the% m converter, but realize that when using the _POSIX_C_SOURCE 200112L macro, I can use the converter, so mingw provides a library C that supports the posix pattern? ``` #define _POSIX_C_SOURCE 200112L #include <stdio.h> int main(void){ char *a; scanf("%ms", &a); puts(a); return 0; } ```
MinGW supports a subset of POSIX-like features (%ms,alarm,signal, etc.) on top of MSVCRT, but it's not POSIX-compliant. If you need a POSIX-compliant environment on Windows, use Cygwin.
I tried to remove coverage data on my test driver file "test.c". Below is what I was using after reading some similar questions in SO. ``` $ lcov --remove test.gcda -c -d . -o a.info --rc lcov_branch_coverage=1 ``` but I got an error below. Can anyone help? ``` lcov: ERROR: only one of -z, -c, -a, -e, -r, -l, --diff or --summary allowed! Use lcov --help to get usage information ```
-ris the same as--remove. And the error message says that you cannot use-rand-cat the same time. Remove the-cparameter.
I got confused of the type of an integer constant, as describedhere: On the first row, if a constant ended without'u', why decimal constant must besignedtype, while octal or hexadecimal constant can be anunsignedtype? I think that taking the constant as an unsigned version if thesignedversion do not fit has problem, for example: ``` long long l1 = 0xffffffff + 0xffffffff; // 0xffffffff is unsigned int long long l2 = 4294967295 + 4294967295; // 4294967295 is signed long ``` l1 is fffffffe, while l2 is 1fffffffe. and obviously l1 is wrong
If I were to say, I'd answer with thathexadecimal and octal numbers represent bit pattern more closelythan decimal ones, and therefore the C standard committee has decided that hex and oct numbers may be unsigned even withoutUsuffix. Think about how many people would write code like this: ``` uint32_t b = a & 0xFFFFFFF0; uint32_t b = a & 4294967280; // or -15? ```
I was assigned to make a program which will output the user's message: reversed, vertically and vertical upside down. I did vertical upside down by total accident but now I can't figure out vertical. ``` include <stdio.h> #include <stdlib.h> #include <string.h> main(){ char str[100]; int i, len; printf("Enter a message \n"); gets(str); len =strlen(str); printf("The message reversed: \n"); for(i = len - 1; i >= 0; i--) { printf("%c", str[i]); } printf("\n"); printf("The message vertical upside down \n"); for(i = len - 1; i >= 0; i--){ printf("%c \n", str[i]); } printf("\n"); system("pause"); } ``` To be able to output message vertically and also corrections if vertical upside down is incorrect.
How about ? ``` for (i = 0; i < len; i++) { printf("%c\n", str[i]); } ```
I got confused of the type of an integer constant, as describedhere: On the first row, if a constant ended without'u', why decimal constant must besignedtype, while octal or hexadecimal constant can be anunsignedtype? I think that taking the constant as an unsigned version if thesignedversion do not fit has problem, for example: ``` long long l1 = 0xffffffff + 0xffffffff; // 0xffffffff is unsigned int long long l2 = 4294967295 + 4294967295; // 4294967295 is signed long ``` l1 is fffffffe, while l2 is 1fffffffe. and obviously l1 is wrong
If I were to say, I'd answer with thathexadecimal and octal numbers represent bit pattern more closelythan decimal ones, and therefore the C standard committee has decided that hex and oct numbers may be unsigned even withoutUsuffix. Think about how many people would write code like this: ``` uint32_t b = a & 0xFFFFFFF0; uint32_t b = a & 4294967280; // or -15? ```
I was assigned to make a program which will output the user's message: reversed, vertically and vertical upside down. I did vertical upside down by total accident but now I can't figure out vertical. ``` include <stdio.h> #include <stdlib.h> #include <string.h> main(){ char str[100]; int i, len; printf("Enter a message \n"); gets(str); len =strlen(str); printf("The message reversed: \n"); for(i = len - 1; i >= 0; i--) { printf("%c", str[i]); } printf("\n"); printf("The message vertical upside down \n"); for(i = len - 1; i >= 0; i--){ printf("%c \n", str[i]); } printf("\n"); system("pause"); } ``` To be able to output message vertically and also corrections if vertical upside down is incorrect.
How about ? ``` for (i = 0; i < len; i++) { printf("%c\n", str[i]); } ```
I want to getAla. I getA. How to fix these? ``` #include <stdio.h> #include <stdlib.h> #include <string.h> void zad(char tab[]) { int i = 0; int size = strlen(tab); while(tab[i] != " ") { printf("%c", tab[i]); i++; } } int main() { char word[20] = "Ala ma kota"; zad(word); return 0; } ```
char array and char types are different in c, the first uses"as a delimiter while the second uses' So try this: ``` while(tab[i] != ' ') { ``` Which should work for your example. However, to make your code work more generally for different substrings (other than a space character) and for strings without a space in them, you need to use the size too, like this: ``` while(i < size && tab[i] != ' ') { ``` to ensure that you don't attempt to read beyond the memory where your string resides.
Is there a standard manner to determine the width of the significand of a double, in C or C++? I am aware that IEEE-754 format of a double stores the significand in 53 bits, but I would like to avoid using a “magic” number in my code. On Linux, the fileusr/include/ieee754.hexists, but it describes the format using bit fields in a structure, which I cannot determine the size of (at compile time). A Linux-only solution is acceptable.
UseFLT_MANT_DIGandDBL_MANT_DIG, defined in<float.h>: ``` #include <float.h> #include <stdio.h> #if FLT_RADIX != 2 #error "Floating-point base is not two." #endif int main(void) { printf("There are %d bits in the significand of a float.\n", FLT_MANT_DIG); printf("There are %d bits in the significand of a double.\n", DBL_MANT_DIG); } ```
I think the output should be 10 10, but it is 10 1 and idk why. I tried assigning arr[0]=55 and it made i to be 55 idk why that either. Would be glad to have an explanation ``` void foo(int arr[]) { int i=10; arr=&i; printf("%d",arr[0]); } int main() { int a[4]={1,2,3,4}; foo(a); printf("%d",a[0]); return 0; } ``` What i thought: 1010 actual o/p= 101
Witharr=&i, you change the local pointer to the array and let it point somewhere else; yet you do not change the original array's content. Writearr[0]=10, and it should give you the1010output.
I'm working on a custom unit-testing framework that doesn't display the filename/line numbers of failed tests. I know I could require them as arguments for thereport_resultsfunction but that seems like a lot of text. Is there a way to make it so that__FILE__and__LINE__are always passed with the function, even if I don't pass them when I call it? You can do something like this in C++: ``` void func(char *file=__FILE__, int line=__LINE__)(int more_args) {} ```
use a macro in your code, to call an underlying function ``` #define func(arg) real_func(__FILE__,__LINE__,arg) ``` wherereal_funcis ``` void real_func(const char *file, int line, int arg); ``` In your code, when you callfunc(12), it expands to a call toreal_func, with actual file path and line of the call. You can even support variable argument functions in C99 with variadic macros as a frontend.
I am having some trouble understanding the output of the following code snippet. ``` #include<stdio.h> int main() { char *str; str = "%d\n"; str++; str++; printf(str-2, 300); return 0; } ``` The output of the code is 300. I understand that Until the line before theprintfstatement,stris pointing to the character-%. What I need help with is understanding that why is theprintffunction printing 300.
Right before theprintf,strisnotpointing to the%but to the\n. The++operator increments the value ofstrto point to the next character in the array. Since this is done twice, it points to the\n. When you then passstr-2toprintf, it creates a pointer pointing back to the%. Soprintfsees the string"%d\n"which causes 300 to be printed as expected.
I am porting some Linux program to my embedded system. Problem is that program usesXlibto draw an output image. I've found online definitions of used structures and functions which helps me to port the app. The only thing I can't find is the definition ofColormap. I've found few descriptions thatColormapis just a table of used colors (XColor?). But I've never found original definition of it. I've searched it online and in X11 under git. I've foundColormapincluded in other structures with no definition ofColormapitself. Am I missing something?
The headers for X11 are typically under/usr/include/X11 Classically in/usr/include/X11/X.hthere istypedef XID Colormap;
I am porting some Linux program to my embedded system. Problem is that program usesXlibto draw an output image. I've found online definitions of used structures and functions which helps me to port the app. The only thing I can't find is the definition ofColormap. I've found few descriptions thatColormapis just a table of used colors (XColor?). But I've never found original definition of it. I've searched it online and in X11 under git. I've foundColormapincluded in other structures with no definition ofColormapitself. Am I missing something?
The headers for X11 are typically under/usr/include/X11 Classically in/usr/include/X11/X.hthere istypedef XID Colormap;
This question already has answers here:Weird result after assigning 2^31 to a signed and unsigned 32-bit integer variable(3 answers)Closed4 years ago. This code is not behaving as expected. It simply tries to set bit 31 in an unsigned long int. ``` int main() { printf("sizeof(unsigned long int) is %ld bytes\n", sizeof(unsigned long int)); unsigned long int v = 1 << 30; printf("v is (%lx)\n", v); v = 1 << 31; printf("v is (%lx)\n", v); } ``` Here is the output: ``` sizeof(unsigned long int) is 8 bytes v is (40000000) v is (ffffffff80000000) ``` Can anyone explain this? Maybe a problem with the printf formatting?
Inv = 1 << 31;,1is not anunsigned long int. It is anint. Shifting it by 31 bits overflows theinttype (in your C implementation). To get anunsigned long intwith a 1 in bit 31, you should shift anunsigned long intby 31 bits:v = (unsigned long int) 1 << 31;orv = 1ul << 31.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed4 years ago.Improve this question I was looking at some programming practices in Codewars and most of them start with only this line to work with: ``` char *accum(const char *source); ``` I've never seen this syntax before, what exactly does this do? I assume it assigned accum to source, but I've tried printing accum and it hits me with this error: ``` undefined reference to `accum' ```
This is a signature of a function. It allows you to use a function which is defined later in your code. If you want to declare a function that takes afloatin argument and return anintyou have to write this piece of code :int myFunction(float arg); So here, you have the signature of a function that returns achar *and take an argument of typeconst char *
This question already has answers here:Confusion about an error: lvalue required as unary '&' operand [duplicate](2 answers)Closed4 years ago. I have heard that++areturns l-value in c wheresa++returns r-value in c. Since++areturn l-value then why &(++a) throws complilation error? Here's a link:Why is ++x a lvalue and x++ a rvalue? ``` #include<stdio.h> int main() { int a=1,*p; p=&(++a); printf("%d",p); } ``` Error message: ``` guess.c: In function ‘main’: guess.c:6:4: error: lvalue required as unary ‘&’ operand p=&(++a); ```
You're mixing up C with C++. In C++, you can indeed do that. In C,++ajust gives you the new value ofa(an rvalue in C++ terms), and you can't take the address of that. And of course, your print should beprintf("%d\n", *p);, notprintf("%d\n",p);(orprintf("%p\n", (void *)p);, if you want to print the address ofa).
Whenever I try to compile c/cpp files it gives this error: ``` gcc: fatal error: cannot execute ‘as’: execvp: No such file or directory compilation terminated. ``` I have also tried to include full path of file while compiling but same error occured. Just to be sure of version mismatch I looked for both gcc and g++ version but both are same, gcc/g++ version: 9.1.0. How can I fix this?
ascommand is frombinutils. Have you installed this package?
I have a simple c code. I am running the binary of that with my pin tool: ``` pin -t tool.so -- test/test.o a ``` Here,test/test.ois a binary, andais some random command line argument to the pin tool (saytool.so), and not the binary (so, there is a distinction between passing command line argument to the pin tool and to the binary). I would like to know how can I pass command line input (sayarg1) to the binary which I am running with the pin tool. (like we would pass with -./test/test.o arg1) Note: I think knowing my pin tool and the c code is irrelevant here.
What you describe here will pass command line arguments to the program you're running. Command line arguments to the tool are all the arguments that come after the -t argument and before the -- (double dash) which indicates the binary and its arguments
I have the following code: ``` g_log(G_LOG_DOMAIN, G_LOG_LEVEL_INFO, "Test log (info level)"); g_info("Test info"); g_debug("Test debug"); g_message("Test message"); g_warning("Test warning"); g_error("Test error"); ``` However, only the message, warning, and error log levels get printed. I ranset G_MESSAGES_DEBUG=allin my shell before running the program, but the debug and info messages were still suppressed. How can I make GLib print all log levels?
Oops, looks like I didn't know how to set environment variables properly. Usingexport G_MESSAGES_DEBUG=allworks like a charm.
I want to distribute a standalone binary script with cmake. basiclly, it looks like: ``` Folder |- bin-script |- 3rd |- liblib1.so |- liblib2.so ``` I hope after user get this folder, copy it to anywhere, then he can use the bin-script directly without install any 3rd libs but directly link to the libs provided in 3rd folder. I try to add link directory with ``` set_target_properties(${LIB_NAME}-bin PROPERTIES LINK_FLAGS "-L./3rd") ``` but it seems not work.
TheRPATHcontains a list of search paths for the linker. You can add to it as you would to any other CMake list: ``` if(APPLE) list(APPEND CMAKE_INSTALL_RPATH "@executable_path/3rd") list(APPEND CMAKE_INSTALL_RPATH "@executable_path/") elseif(UNIX) list(APPEND CMAKE_INSTALL_RPATH "\$ORIGIN/3rd") endif() ```
I need to test if a ECC certificate in PEM format is of good shape in C using the wolfssl library. I do not want to test any further information only if it is a certificate and not any random Base64 encoded bytes between the -----BEGIN CERTIFICATE----- -----END CERTIFICATE----- lines. What is the easiest way to do so?
You can use thewolfSSL_X509_load_certificate_fileto check if it's a valid certificate, as shown in the example bellow. You can find the function documentationhere. ``` #include <wolfssl/openssl/x509.h> int is_x509_cert(const char* pem_cert_file_path) { WOLFSSL_X509 *cert = wolfSSL_X509_load_certificate_file(pem_cert_file_path, SSL_FILETYPE_PEM); if (cert != NULL) { wolfSSL_X509_free(cert); return 1; } else { return 0; } } ```
I'm trying to check if a certain keyword is in the string entered by the user. This is how I would do it in python. ``` keyword = "something" user_input = input("Enter a something: ") if keyword in user_input: # I don't know how to do this part print("You entered something") else: print("You didn't enter something") ``` How would I do something like that in C?
You can usestrstr()to search for a substring within a string. It's not as generic as Python'sinoperator (for instance,strstrcan't be used to check if a given value is stored within an array), but it will solve the problem that you presented. For example (untested): ``` const char *keyword = "something"; const char *user_input = input("Enter a something: "); // I'll leave this to you to implement if (NULL != strstr(user_input, keyword)) { printf("You entered something\n"); } else { printf("You didn't enter something\n"); } ```
This question already has answers here:Why does everybody typedef over standard C types?(4 answers)Closed4 years ago. Please help me understand reason of defining C types in some projects. In my current company I found that someone made definitions of types that are equivalent of those that are already defined in<stdint.h>. Such approach makes harder to integrate 3party code into project, and makes programmer work, bit more frustrating. But I can also see that some projects, like gnome do the same. There is a gchar, gsize, and gint32 for example. Because I don't see ANY reason for such approach, I kindly ask for explanation. What is the reason that<stdint.h>isn't sufficient.
This is not good practice. It only leads to less compatibility and portability. I don't see any reason that it should be done.stdint.hexists to avoid this.
I am having problems with an automated software testing, which is blaming use of freed resource when I use fd_clr(3) after using close(3) in a fd. Is there something wrong with doing this? ``` for(i = 0; i < nfds; ++i) { if (FD_ISSET(i, &myFdSet)) { close(i); FD_CLR(i, &myFdSet); } } ```
FD_CLR()only changes a localfd_set, which is a C data structure to store info about a list of file descriptors. close()is a system call that closes the file descriptor. Thefd_setis used in theselect()system call. Withselect()you get information about the state of the list of file descriptors that are stored in yourfd_setstruct. The reason why you see theFD_CLR()just below theclose(), is that there's no longer need/purpose in asking the state if the closed file descriptor.
I didn't write C code for a long time, I'm rusty. Anybody knows why the following code prints "rtyaze" to stdout ? I was expecting "rty". ``` #include <stdio.h> int main (void) { char s[] = "aze"; char ss[][3] = { "rty" }; printf("%s\n", ss[0]); } ```
By making your string at the first element of ss have 3 characters you are eliminating the null terminator. So printf continues until it finds a null terminator. By chance, your other string must have been placed in memory right after your first one. If you change the 3 in ss[][3] to a 4 you should get expected behaviour.
Letvalandxbe 32-bit unsigned integers. Letxbe in the range 0 til 8 (thus, holding at most 3 bits). What is the simplest way to overwrite the bits10,11and12ofvalto match the bits ofx? I.e., in such a way that(val >> 10) & 1 == x & 1,(val >> 11) & 1 == (x >> 1) & 1and(val >> 12) & 1 == (x >> 2) & 1? As an example, this expression accomplishes this: ``` (val & ~(0x7 << 10)) | (x << 10) ``` Is it possible to accomplish the same with fewer operations?
The expression you have is the simplest way (though I don't have a proof), assuming bothvalandxare variables rather than constants. Any decent compiler will compute the constant value of~(0x7 << 10)at compile time, of course. You might want to avoid the duplication by writing an (inline) function or macro if you need this a lot.
Long ago I wrote a variant ofstrftimewith added conversion specifications (https://www.gdargaud.net/Hack/SourceCode.html#StrfTime). Some time ago I discovered that you can add your own conversion specifiers toprintfwithregister_printf_function(https://www.gnu.org/software/libc/manual/html_node/Customizing-Printf.html) so I wanted to update my old code with this mechanism, but something similar does not seem to be available for strftime functions. Did I miss it ? Or why isn't it available ?
Theregister_printf_functionis a GNU extension that allows for registering customprintfformat specifiers. Currently the glibcstrftimefunctionimplementationandimplementationdoesn't allow registering custom format specifiers. The function justignores bad format specificationwhereasprintf checksthe array with custom registered formatting specifiers.
Letvalandxbe 32-bit unsigned integers. Letxbe in the range 0 til 8 (thus, holding at most 3 bits). What is the simplest way to overwrite the bits10,11and12ofvalto match the bits ofx? I.e., in such a way that(val >> 10) & 1 == x & 1,(val >> 11) & 1 == (x >> 1) & 1and(val >> 12) & 1 == (x >> 2) & 1? As an example, this expression accomplishes this: ``` (val & ~(0x7 << 10)) | (x << 10) ``` Is it possible to accomplish the same with fewer operations?
The expression you have is the simplest way (though I don't have a proof), assuming bothvalandxare variables rather than constants. Any decent compiler will compute the constant value of~(0x7 << 10)at compile time, of course. You might want to avoid the duplication by writing an (inline) function or macro if you need this a lot.
Long ago I wrote a variant ofstrftimewith added conversion specifications (https://www.gdargaud.net/Hack/SourceCode.html#StrfTime). Some time ago I discovered that you can add your own conversion specifiers toprintfwithregister_printf_function(https://www.gnu.org/software/libc/manual/html_node/Customizing-Printf.html) so I wanted to update my old code with this mechanism, but something similar does not seem to be available for strftime functions. Did I miss it ? Or why isn't it available ?
Theregister_printf_functionis a GNU extension that allows for registering customprintfformat specifiers. Currently the glibcstrftimefunctionimplementationandimplementationdoesn't allow registering custom format specifiers. The function justignores bad format specificationwhereasprintf checksthe array with custom registered formatting specifiers.