question
stringlengths
25
894
answer
stringlengths
4
863
I wrote an ntrip client in C using sockets(http://read.pudn.com/downloads116/sourcecode/unix_linux/493018/NtripLinuxClient.c__.htm), Receiving the reqest works fine, but after some time the server stops sending correction data because I do not now how to send nmea updates to the server. Does anyone know how that woul...
You just need to send your_nmea + '\r\n' regularly and that should work.
This question already has answers here:How can I concatenate twice with the C preprocessor and expand a macro as in "arg ## _ ## MACRO"?(3 answers)Closed5 years ago. I have something like : ``` #define NBR 42 #define THE_ANS_IS theAnsIsNBR ``` Currently the second macro is expand as 'theAnsIsNBR' as expected, but i...
``` #define Paste(x, y) x##y #define Expand(x, y) Paste(x, y) #define NBR 42 #define THE_ANS_IS Expand(theAnsIs, NBR) ```
I'm trying to write a function which will print message onto the screen using VGA text mode buffer. This is function which prints a single char: ``` void putc(uint8_t c, enum Color term_color) { uint8_t *vidptr = (uint8_t*)0xB8000; *vidptr = c; vidptr++; *vidptr = (uint8_t*)term_color; vidptr++; ...
The function putc(uint8_t c, enum Color term_color) always put the character in the same position (0xB8000).You need to declare uint8_t *vidptr outside the function to correctly increment it each call.
``` a|b=c ``` knowingaandc, how to calculateb For example: ``` 0011 | b = 0111 ``` Knowinga = 0011andc = 0111, how to figure outbto be0101
There will be more than one correct answer. For simplicity consider the trivial example:1|0 = 1i.e. a=1, b=0 and c=1. In this case, b can also be 1. So given that the bit inais 1, we won't be able to know for sure whether the bit inbis 0 or 1.
How do I make my matrix nicely spaced out? This is my code for generating the matrix: ``` void print_graph(void) { int i, j; for (i = 0; i < 20; i++) { for (j = 0; j < 20; j++) { printf("%.1d", G[i][j]); } printf("\n"); } } ``` matrix
You could indent each line with some tabs: ``` printf("\t"); for (j = 0; j < 20; j++) ... ``` For adding a space between all values you have two options: add a space after the value: ``` printf("%.1d ", G[i][j]); ``` or use the width ``` printf("% 2d", G[i][j]); ``` See also:format specs
I need to input Turkish characters from console in C. But I can't. This code working. ``` setlocale(LC_ALL, "Turkish"); printf("ü ğ ı ş ç ö"); ``` Output:ü ğ ı ş ç ö But when I try to use, it don't working. ``` setlocale(LC_ALL, "Turkish"); scanf("%c %c %c %c", c, (c + 1), (c + 2), (c + 3)); printf("%c %c %c %c", ...
It needs a command in cmd for solution of this problem. I solved. Just before program execution, commandchcp 1254, then console can input Turkish characters.
I'm preparing for a programming contest and I have stumbled upon the question below. ``` void main(){ int number, result; scanf("%d",&number); result=number-(number&-number); //this is what i'm struggling to understand printf("%d",result); } ``` Note the use of "&-" in the commented line. I couldn'...
This is a binary AND operator. The expressionx & -xzeroes out all but the rightmost 1-bit in the number x. Thenx - (x & -x)zeroes only that bit, so the result is the original number with the rightmost 1-bit cleared.
I need to input Turkish characters from console in C. But I can't. This code working. ``` setlocale(LC_ALL, "Turkish"); printf("ü ğ ı ş ç ö"); ``` Output:ü ğ ı ş ç ö But when I try to use, it don't working. ``` setlocale(LC_ALL, "Turkish"); scanf("%c %c %c %c", c, (c + 1), (c + 2), (c + 3)); printf("%c %c %c %c", ...
It needs a command in cmd for solution of this problem. I solved. Just before program execution, commandchcp 1254, then console can input Turkish characters.
I'm preparing for a programming contest and I have stumbled upon the question below. ``` void main(){ int number, result; scanf("%d",&number); result=number-(number&-number); //this is what i'm struggling to understand printf("%d",result); } ``` Note the use of "&-" in the commented line. I couldn'...
This is a binary AND operator. The expressionx & -xzeroes out all but the rightmost 1-bit in the number x. Thenx - (x & -x)zeroes only that bit, so the result is the original number with the rightmost 1-bit cleared.
How does my code actually give a segmentation fault? I'd like to keepTOSas a double pointer. ``` #include<stdio.h> #include<stdlib.h> typedef struct node_tag{ int num; struct node_tag* next; }NODE; void push(int x, NODE **TOS){ NODE* temp = (NODE*) malloc(sizeof(NODE)); temp->num = x; temp->nex...
You need to use it like this; ``` int main(){ NODE *TOS = NULL, *temp; printf("<<<Stack Push>>>\n"); push(0, &TOS); printf("%i\n", TOS->num); } ```
PHP is written by C,when i read the source code ,I found a stranger Macro expansion,which like below. (size_t)(uint32_t)-(int32_t)(nTableMask) // nTableMask=-8 I usegdbto print(size_t)(uint32_t),it is wrong (gdb) p (size_t)(uint32_t) A syntax error in expression, near `'. but when i change the expression,it work ...
``` (size_t)(uint32_t)-(int32_t)(-8) ``` is first(int32_t)(-8)or0xFFFFFFF8 then it's(uint32_t)- -8or(uint32_t)8or0x00000008 finally it's(size_t) 8assize_tmay be a different size thanuint32_t it will be0x0000000000000008on a 64bit system.
Since it seems we should avoidcharorintorshortorlongorunsigned. "If you find yourself typing char or int or short or long or unsigned into new code, you're doing it wrong", fromhttps://matt.sh/howto-c. Is it possible to instruct compiler to warn on this cases?
It is not possible to make the compiler warn about it. There might be code analyzing tools that can. To "avoid them" on a general basis is a bit harsh.charis guaranteed being a single byte, is used for text even in C11, and the standard libraries often use the platform dependent types, e.g.intas the return value ofst...
I'm writing FUSE filesystem which uses some arguments. I'd like to pass all unrecognized options to FUSE (because it has its own options). Can I do that usingargporgetopt? For now both give me "Unknown option" error.
Argp Fromthe "Argp Flags" section of the documentation: ARGP_NO_ERRSDon't print error messages for unknown options to stderr; unless this flag is set,ARGP_PARSE_ARGV0is ignored, asargv[0]is used as the program name in the error messages. This flag impliesARGP_NO_EXIT. This is based on the assumption that silen...
How does my code actually give a segmentation fault? I'd like to keepTOSas a double pointer. ``` #include<stdio.h> #include<stdlib.h> typedef struct node_tag{ int num; struct node_tag* next; }NODE; void push(int x, NODE **TOS){ NODE* temp = (NODE*) malloc(sizeof(NODE)); temp->num = x; temp->nex...
You need to use it like this; ``` int main(){ NODE *TOS = NULL, *temp; printf("<<<Stack Push>>>\n"); push(0, &TOS); printf("%i\n", TOS->num); } ```
PHP is written by C,when i read the source code ,I found a stranger Macro expansion,which like below. (size_t)(uint32_t)-(int32_t)(nTableMask) // nTableMask=-8 I usegdbto print(size_t)(uint32_t),it is wrong (gdb) p (size_t)(uint32_t) A syntax error in expression, near `'. but when i change the expression,it work ...
``` (size_t)(uint32_t)-(int32_t)(-8) ``` is first(int32_t)(-8)or0xFFFFFFF8 then it's(uint32_t)- -8or(uint32_t)8or0x00000008 finally it's(size_t) 8assize_tmay be a different size thanuint32_t it will be0x0000000000000008on a 64bit system.
Since it seems we should avoidcharorintorshortorlongorunsigned. "If you find yourself typing char or int or short or long or unsigned into new code, you're doing it wrong", fromhttps://matt.sh/howto-c. Is it possible to instruct compiler to warn on this cases?
It is not possible to make the compiler warn about it. There might be code analyzing tools that can. To "avoid them" on a general basis is a bit harsh.charis guaranteed being a single byte, is used for text even in C11, and the standard libraries often use the platform dependent types, e.g.intas the return value ofst...
``` int friends = 20; printf("I have %d friend%c", friends , (friends !=1 ? "s" : "")); return 0; ``` So whenever I run the code it debugs into this ``` I have 20 friend$ ``` It works fine when I run it with %s format specifier after thefriend.sis only one character so why doesn't it work?
so why doesn't it work?because%cexpectscharbut expression(friends !=1 ? "s" : "")results in strings(double quotes). So either use%slike ``` printf("I have %d friend%s", friends , (friends !=1 ? "s" : "")); ``` Or Replace"s"with's'and""with' 'as%cexpectschar. ``` printf("I have %d friend%c", friends , (friends !=1 ...
inotify_add_watch returns an int. I want to store the strings of the path which I am watching in an array and want to index them by the return value of inotify_add_watch. I did a small scale test(with 10 files) and it seems to return them in an ascending order (1, 2, 3, 4...). Is this guaranteed?
Nothing inthe documentationmakes that guarantee. In fact, this case: If the filesystem object was already being watched (perhaps via a different link to the same object), then the descriptor for the existing watch is returned. seems to put the answer squarely at "no". Would you rely onopenreturning file descriptor...
I am writing some linear algebra program with openBLAS. The program needs to multiply two matrices; the one is of single-precision and the other one is of double-precision. I looked up the BLAS reference "http://netlib.org/blas/blasqr.pdf", it seems that BLAS only supports operations on the same type. Is there anyth...
Yes, you need to upcast the single-precision matrix (or downcast the double-precision one)andusedgemm(orsgemm, resp.)
Can someone please explain me the working of Nested If-Else Statements writtenWITHOUTthe Curly Braces.I want to understand why Below Programme isn't giving me any output.I've checked for all the 4 possibilities.(Outer-If, Inner-If)::(True, True),(True, False),(False, True),(False, False).I'm editing with CodeBlocks,us...
They workas-ifthere was a curly brace around the followingstatement. In your case then: ``` if ( n = 0 ){ // ToDo - did you mean `==`, `n = 0` is `0`. if ( m = 0 ){ // ToDo - ditto. printf("True"); } else { printf("False"); } } ``` In your case I think the bewilderment stems from your usi...
inotify_add_watch returns an int. I want to store the strings of the path which I am watching in an array and want to index them by the return value of inotify_add_watch. I did a small scale test(with 10 files) and it seems to return them in an ascending order (1, 2, 3, 4...). Is this guaranteed?
Nothing inthe documentationmakes that guarantee. In fact, this case: If the filesystem object was already being watched (perhaps via a different link to the same object), then the descriptor for the existing watch is returned. seems to put the answer squarely at "no". Would you rely onopenreturning file descriptor...
I am writing some linear algebra program with openBLAS. The program needs to multiply two matrices; the one is of single-precision and the other one is of double-precision. I looked up the BLAS reference "http://netlib.org/blas/blasqr.pdf", it seems that BLAS only supports operations on the same type. Is there anyth...
Yes, you need to upcast the single-precision matrix (or downcast the double-precision one)andusedgemm(orsgemm, resp.)
Can someone please explain me the working of Nested If-Else Statements writtenWITHOUTthe Curly Braces.I want to understand why Below Programme isn't giving me any output.I've checked for all the 4 possibilities.(Outer-If, Inner-If)::(True, True),(True, False),(False, True),(False, False).I'm editing with CodeBlocks,us...
They workas-ifthere was a curly brace around the followingstatement. In your case then: ``` if ( n = 0 ){ // ToDo - did you mean `==`, `n = 0` is `0`. if ( m = 0 ){ // ToDo - ditto. printf("True"); } else { printf("False"); } } ``` In your case I think the bewilderment stems from your usi...
When using LibreSSL's libtls, is it possible to free the memory that is allocated bytls_init()? I found using valgrind that a simple program that only callstls_init()code leaves 2058 blocks of memory "still reachable". I am aware that "still reachable" memory is not strictly a memory leak and it will be cleaned up b...
This question was also asked on the libressl mailing list.The answer is no, at least not with the current libtls API. The current best alternative for memory testing with valgrindis to use the--suppressionsoption.
I just installed Eclipse and I get this error whenever I hit the button run: Launched Failed.Binary not found. What should I do? Please if you can explain step by step. Thank you.
Start eclipse the same as you would any other program, generate a 'project'. add files to the project, then clicking run will trigger a compile of all the files, which creates the object files. then a link of all the object files (and needed libraries) to produce an executable, then it tries to run that executable....
I have a function which receives a string as an input. I need to add a char in the beginning and end, something like'<' ++ "example" ++ '>'to get an output like<example>. Is there a function already for this or i need to write it myself?
There are plenty of functions that can do that: sprintf,snprintfstrcat to name a few. Which one you should use depends on your needs. The most versatile of all are in opinionsprintfandsnprintf. For example: ``` char result[100]; const char *middle = "example"; // the snprintf solution snprintf(result, sizeof resul...
So I have just started to learn program in C, using the Eclipse IDE. My issue is, that any output is not printed on the console until the program terminates. For example: ``` int main() { int i; printf("Provide a number.\n"); scanf("%d",&i); printf("You provided: %d\n",i); } ``` When running this code, the console...
Try this: ``` int main() { int i; fflush(stdout); printf("Provide a number.\n"); scanf("%d",&i); printf("You provided: %d\n",i); } ```
I have the following code: ``` #include <stdio.h> int main(int argc, char **argv) { int arr[2]; arr[0] = 0; arr[1] = 0; int end = 0; int i; for (i=0; i<2 ; i++){ scanf(" num %d", &arr[i]); } scanf(" end %d", &end); printf("arr0 %d \n", arr[0]); printf("arr1 %d \n", arr[1]); pri...
scanfDOES fail in the second example. The second loop iteration fails and returns 0 items read leavingarr[1]unchanged. The loop then ends and the lastscanfsuccessfully reads the second line of input.
I have a function which receives a string as an input. I need to add a char in the beginning and end, something like'<' ++ "example" ++ '>'to get an output like<example>. Is there a function already for this or i need to write it myself?
There are plenty of functions that can do that: sprintf,snprintfstrcat to name a few. Which one you should use depends on your needs. The most versatile of all are in opinionsprintfandsnprintf. For example: ``` char result[100]; const char *middle = "example"; // the snprintf solution snprintf(result, sizeof resul...
The ouput of the following code is coming out to be 512 0 2 however it should have been 512 0 0. Can somebody please help ! ``` #include<stdio.h> int main() { union a { int i; char ch[2]; }; union a z = { 512 }; printf("%d %d %d\n",z.i, z.ch[0]...
You have build a union of two bytes. Know you assign 512d (0x0200) to the union.First Byte =0x00Second Byte =0x02 The integer (int16_t)iand your arraych[2]use the same memory!
In order to get an array of struct I did: ``` int main() { typedef struct { int size; double time; } timming_s; timming_s timming[5]; timming[0] = (timming_s){(int)1e5, 0.0}; timming[1] = (timming_s){(int)2e5, 0.0}; } ``` Is there a more compact form to get it? I was trying to wri...
``` int main(void) { struct { int size; double time; } timming[5] = {{1e5, 0}, {2e5, 0}}; // } timming[5] = {{.size = 1e5, .time = 0}, {.size = 2e5, .time = 0}}; } ```
I have the following struct: ``` struct postsTempo { int ano; ShortData dias[373]; struct postsTempo* prox; }; ``` When I domalloc(sizeof(struct postsTempo))have I allocated everything that I need or do i still need tomalloctheShortDataarray? I cant add anything to that array...
Whenever you allocate memory usingmalloc()it creates the memory space for all variables declared inside the structure. So there is no need to usemallocfurther forShortData.
The other day I was trying to use a macro to define a function like so (simplified, obviously): ``` #define DEF_ADD(name) \ int add_name(int x, int y) { \ return x + y; \ } \ ``` Now, I expected the snippetDEF_ADD(hello)to define the functionadd_hello. However, the macro call instead defines a functi...
You need ``` #define DEF_ADD(name) \ int add_##name(int x, int y) { \ return x + y; \ } ``` Note well the##. I've also dropped the final newline character. Else the parameternameis not used and you createadd_nameas the function name.
I am trying to pass a 2d array into a pthread function, but I can not find a way to get access to the array content during pthread process, how can I do it? I tried ``` int ** array = (int **)arg; ``` but it caused segfault after I tried to change the stored value; Here is part of my code: ``` int message1[2][64]; ...
Couldn't find a proper duplicate for this.int **is not a 2D array but a pointer to a pointer to an int. What you want to pass inis a pointer to an array[64] ofint, i.e.int (*array)[64]. Try ``` int (*array)[64] = arg; ```
This question already has answers here:Why structs cannot be assigned directly?(2 answers)Closed5 years ago. I'm initialising an array of structures in main(); I get an error, when I declare and assign them separately. This is my code snippet from main(); ``` struct item newitem[10]; newitem[0]={1,"pen",5,10}; stru...
You have to use compound literal: ``` newitem[0] = (struct item) {1, "pen", 5, 10}; ```
im Lino, im new on this community. basically, im trying to save data into the GAMEPAK_RAM of the GBA, and the pointer dont work. the code line is this: ``` #define GAMEPAK_RAM ((volatile uint8_t*)0x0E000000) ``` and the error is this: ``` In file included from source/main.c:2:0: source/OpenEngine.h:8:21: error: inv...
``` unsigned short *SaveMemory[0xFFFF] = GAMEPAK_RAM; ``` This is the same as: ``` unsigned short *SaveMemory[0xFFFF] = ((volatile uint8_t*)0x0E000000); ``` SaveMemoryis an array and((volatile uint8_t*)0x0E000000)is a pointer. You can't set an array equal to a pointer, hence the error.
Is there a standard macro to check support of variable length arrays in C code? It it enough to check for c99 (__STDC_VERSION__ >= 199901L) in all widely used compilers?
From the C11 specification §6.10.8.3 The following macro names are conditionally defined by the implementation:[...]__STDC_NO_VLA__The integer constant 1, intended to indicate that the implementation does not support variable length arrays or variably modified types. So if__STDC_VERSION__ > 201000Lyou need to ch...
I try to read an integer from stdin with the following C program. ``` #include <unistd.h> #include <stdio.h> int main() { int a = 0; read(0, &a, sizeof(int)); printf ("a = %d\n",a); } ``` However, I got strange results: when I input 34, I suppose the program outputs 34, but it does 668723. Why?
AsWeather Vaneposted in thecomments: read()readsbytesnot ascii The read() function shall attempt to read bytes from the file ASCII34\nbecomes0001010 00110100 00110011in binary. (Or really\n43due to endianness) Next0001010 00110100 00110011converted to decimal becomes668723
I'm trying to do math calculations that they require more than 100 decimals of precision. C data types cannot go beyond 16 bytes (long double), so I cannot compute more than ~17 decimals. Is there a way to create a variable in C that can get more precision?
Realistically you need an arbitrary-precision arithmetic library, seeWikipediafor some options. I personally have foundGNU MPFRto be fairly reliable, though I have also heard good things aboutArb.
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed5 years ago.Improve...
newis not part ofCkeywords. Your IDE probably tries to parse this file as C++. Anyway, it's good idea to avoid using C++keywordseven in C code for better interoperability.
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.Closed5 years ago.Improve this question I'm really confused on what the correct syntax is to passing an array of struct pointers to a function? For...
I think it is more clear to use struct Book **bookList as the parameter.
In Linux, ``` #include <stdlib.h> void exit(int status); ``` What doesexit()sendstatusto, the parent process or the OS kernel? APUE says that exit()performs certain cleanup processing and then returns to the kernel. But when I run a program in shell, the program returns its exit status to the shell which i...
As you're probably aware, Linux (like most Operating Systems) keeps processes separate. That's why the result ofexitis passed via the kernel to the parent process.
I'm trying to convert this loop into a for loop, but I can't get it to work, it's in C. ``` while(args[argCounter]){ if(!strcmp(args[argCounter], "|")){ args[argCounter] = NULL; cmdbegin[child] = argCounter + 1; child++; } argCounter++; } ```
I would translate it as follows: ``` for (int argCounter = 0 ; args[argCounter] ; argCounter++){ if(!strcmp(args[argCounter], "|")){ args[argCounter] = NULL; cmdbegin[child++] = argCounter + 1; } } ``` I added declaration and initialization ofargCounterwhich you did not show. The conversion w...
I am doing and example for C programming class: ``` #define xSize 2 #define ySize 3 int x,y, a[xSize][ySize]; for (x=1; x<=xSize; x++){ for (y=1; y<=ySize; y++){ a[x][y]=(x*x)+(y*y);}} for (x=1; x<=xSize; x++){ for (y=1; y<=ySize; y++){ printf("a[%d][%d]= %d ", x, y, a[x][y]);}} ``` It gives an Error when I tr...
When you specifya[xSize]andb[ySize]. The arrayacan store up toxSizevalues whilebcan store up toySizevalues. However that starts from index 0 toxSize-1and 0 toySize-1in arraysaandbrespectively. So when you are using for loop you are iterating the loop with indexes from 1 toxSizewhen actually the array is limited to a m...
I want to know how much memory was used before executing a program, which usesmalloc(), and how much it is allocated after the program has finished his execution. I want to do this to check if myfree()actually cleans up all the memory that I've allocated. When I used to do concurrent programming in order to do this ...
an extra point to answer, valgrid has a tool called massif , which is a heap profiler. it can be used to analyse heap usage throughout the program. you can also see the heap usage graphically, with help of massif and ms_print command more info and documentation can be foundhere
I've found that there are two different structures for getting TCP headers namely tcp and tcphdr. The links for both the structures arehere:tcpandhere:tcphdrrespectively. What is the difference between them and do they depend on the system they're running?
One is fromhttp://minirighi.sourceforge.net/Minirighi multi-threading operating system for IA-32 And another is from Linux kernel version 2.6. (http://www.cse.scu.edu/~dclark/am_256_graph_theory/linux_2_6_stack/structtcphdr.html) TCP packet/header implementation is internal to the TCP/IP stack which is usually part...
I am using stat file system in a program and I want to print the device id using printf("\nst_dev = %s\n",buf.st_dev); but i am getting error: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘__dev_t’ [-Wformat=] What should b used instead of %s here?
st_devis of typedev_twhich is aninteger typeas perPOSIX definition: dev_t shall be an integer type. So printing it using%scertainly wrong. There's no portable way to print it because there's no format specifier defined for it in POSIX. You could useintmax_tto print it: ``` printf("\nst_dev = %jd\n", (intmax_t)buf.s...
I'm trying to convert this loop into a for loop, but I can't get it to work, it's in C. ``` while(args[argCounter]){ if(!strcmp(args[argCounter], "|")){ args[argCounter] = NULL; cmdbegin[child] = argCounter + 1; child++; } argCounter++; } ```
I would translate it as follows: ``` for (int argCounter = 0 ; args[argCounter] ; argCounter++){ if(!strcmp(args[argCounter], "|")){ args[argCounter] = NULL; cmdbegin[child++] = argCounter + 1; } } ``` I added declaration and initialization ofargCounterwhich you did not show. The conversion w...
I am doing and example for C programming class: ``` #define xSize 2 #define ySize 3 int x,y, a[xSize][ySize]; for (x=1; x<=xSize; x++){ for (y=1; y<=ySize; y++){ a[x][y]=(x*x)+(y*y);}} for (x=1; x<=xSize; x++){ for (y=1; y<=ySize; y++){ printf("a[%d][%d]= %d ", x, y, a[x][y]);}} ``` It gives an Error when I tr...
When you specifya[xSize]andb[ySize]. The arrayacan store up toxSizevalues whilebcan store up toySizevalues. However that starts from index 0 toxSize-1and 0 toySize-1in arraysaandbrespectively. So when you are using for loop you are iterating the loop with indexes from 1 toxSizewhen actually the array is limited to a m...
I want to know how much memory was used before executing a program, which usesmalloc(), and how much it is allocated after the program has finished his execution. I want to do this to check if myfree()actually cleans up all the memory that I've allocated. When I used to do concurrent programming in order to do this ...
an extra point to answer, valgrid has a tool called massif , which is a heap profiler. it can be used to analyse heap usage throughout the program. you can also see the heap usage graphically, with help of massif and ms_print command more info and documentation can be foundhere
This code makes an ASCII representation of a Sierpinski triangle of order 4, and I have no idea how the lastprintfworks. If anyone can explain it to me, I would be very grateful. ``` #include <stdio.h> #define SIZE (1 << 4) int main() { int x, y, i; for (y = SIZE - 1; y >= 0; y--, putchar('\n')) { fo...
The?is a ternary operator. It evaluates the expression on the left, and if it's non-zero (true) it selects the first value before the colon:and if it's zero (false) it selects the second.
``` typedef struct line { int a; int b; } line; int main() { line *v; int c, d, j; char a; int i; scanf("%d", &n) for (i = 0; i < n; i++) { scanf("%c", &a); v = (line*) malloc(n * sizeof(line)); if (a == '+') { scanf("%d %d", &v[j]->a, &v[j]->b); } } ``` I want to make an arra...
Use&(v[j].a)instead, which is equal to &((v+j)->a). The name of an array is a pointer to the first element. So v[j] is an element of type struct line. In order to get one of its fields you use.a. Also, check your code for some other errors because some variebles are not initialized.
In order to improve the aesthetics of some code, I would like to have a .h file contain some code that sets a #define based on which file the .h file is included from. For example ``` #if (__file__ == "main.c") #define MOUDLE MODULE_MAIN #elif (__file__ == "foo.c") #define MODULE MODULE_FOO #endif ``` Is there any ...
No, you can't do this.#ifcan only do integer expressions. It knows nothing about strings or how to compare them.
I am working on a FUSE and I have a file descriptor to the directory prior to mounting the fuse on top. I want to use that handle to read/write files with state information underneath the FUSE mounted file system, and then to be able to access that data next time I mount it. So I cannot use the normal lstat call sinc...
There is no lstatat() function in POSIX, however, fstatat() takes a flag argument which can be AT_SYMLINK_NOFOLLOW, which may do what you're looking for.
I compile one of my C codes with a Mathematica C header file. Mathematica uses a macro to tell you which version you are using. The format is ``` #define WSMATHVERSION 10.0.0 ``` I'm more familiar with this pattern of version numbering in macros, ``` // BOOST_VERSION % 100 is the patch level // BOOST_VERSION / 10...
In C, preprocessor conditions can only be composed of integers. So, it's unfortunatly impossible to write a preprocessor condition with the WSMATHVERSION macro.
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.Closed2 years ago.Improve this question I have a to create a program where the user should create a username with minimum of 8 ch...
You can usedo-whileto check the input. So it will loop everytime the input is wrong ``` do{ printf("Username : "); //scanf here }while( strlen(your variable) < 8 || strlen(your variable) > 12 ); ``` Everytime the user input username with less than 8 character or more than 12 character, it will ask to input a...
I have seen the following declaration of two dimensional array. ``` int arr[][3] = { {1,2,3}, {4,5,6}}; ``` My question is how can I allocate following multidimensional array in run time based on user input of first dimension? ``` #define M 10 #define N 15 int arr[][M][N] ```
Start by declaring a pointer suitable for accessing the array: ``` int (*array)[M][N]; ``` Then allocate memory for the array based on the user input: ``` array = malloc(P * sizeof(*array)); // P is the value obtained from the user ``` Then use the pointer as if it was a 3D array: ``` array[x][y][z] = 42; ``` ...
Given a preprocessor macro like ``` #define DECLARE(NAME) \ int NAME; \ int NAME_2 ``` Name_2denotes a new identifier. Is it possible to expandName, so that ``` DECLARE(x); ``` becomes ``` int x; int x_2; ```
You can use##glue: ``` #define DECLARE(NAME) \ int NAME; \ int NAME##_2 ```
Good evening. Can someone explain me why the following code runs the message from IF condition? ``` if ((~7 & 0x000f) == 8) printf("Honesty is the best policy\n"); ``` From what I know ~7 = 11111001 and 0x000f= 00001111 Thank you!
-7 (indeed 11111001)is not ~7 (11111000) You are off by 1. ``` 11111000 & 00001111 == 00001000 ``` is true. (This answer follows the questions obvious lead, in using a simplified 8 bit model for the involved values.)
``` #include<stdio.h> int rec(int num) { return(num) ? num % 10 + rec(num / 10) : 0; } int main() { printf("\n%d\n", rec(4567)); } ``` IDE used is visual studio 2017 64 bit.
It looks like it is calculating each number mod 10 (first run is 4567 % 10 = 7). It then runs recursively (rec(num/10)), calling the function on 456, then on 45, then on 4. Since it is adding the number it comes up with to the recursive function (num % 10 + rec(num / 10)), your function is just adding (4567 % 10 + 4...
I have seen the following declaration of two dimensional array. ``` int arr[][3] = { {1,2,3}, {4,5,6}}; ``` My question is how can I allocate following multidimensional array in run time based on user input of first dimension? ``` #define M 10 #define N 15 int arr[][M][N] ```
Start by declaring a pointer suitable for accessing the array: ``` int (*array)[M][N]; ``` Then allocate memory for the array based on the user input: ``` array = malloc(P * sizeof(*array)); // P is the value obtained from the user ``` Then use the pointer as if it was a 3D array: ``` array[x][y][z] = 42; ``` ...
Given a preprocessor macro like ``` #define DECLARE(NAME) \ int NAME; \ int NAME_2 ``` Name_2denotes a new identifier. Is it possible to expandName, so that ``` DECLARE(x); ``` becomes ``` int x; int x_2; ```
You can use##glue: ``` #define DECLARE(NAME) \ int NAME; \ int NAME##_2 ```
Good evening. Can someone explain me why the following code runs the message from IF condition? ``` if ((~7 & 0x000f) == 8) printf("Honesty is the best policy\n"); ``` From what I know ~7 = 11111001 and 0x000f= 00001111 Thank you!
-7 (indeed 11111001)is not ~7 (11111000) You are off by 1. ``` 11111000 & 00001111 == 00001000 ``` is true. (This answer follows the questions obvious lead, in using a simplified 8 bit model for the involved values.)
``` #include<stdio.h> int rec(int num) { return(num) ? num % 10 + rec(num / 10) : 0; } int main() { printf("\n%d\n", rec(4567)); } ``` IDE used is visual studio 2017 64 bit.
It looks like it is calculating each number mod 10 (first run is 4567 % 10 = 7). It then runs recursively (rec(num/10)), calling the function on 456, then on 45, then on 4. Since it is adding the number it comes up with to the recursive function (num % 10 + rec(num / 10)), your function is just adding (4567 % 10 + 4...
Good evening. Can someone explain me why the following code runs the message from IF condition? ``` if ((~7 & 0x000f) == 8) printf("Honesty is the best policy\n"); ``` From what I know ~7 = 11111001 and 0x000f= 00001111 Thank you!
-7 (indeed 11111001)is not ~7 (11111000) You are off by 1. ``` 11111000 & 00001111 == 00001000 ``` is true. (This answer follows the questions obvious lead, in using a simplified 8 bit model for the involved values.)
``` #include<stdio.h> int rec(int num) { return(num) ? num % 10 + rec(num / 10) : 0; } int main() { printf("\n%d\n", rec(4567)); } ``` IDE used is visual studio 2017 64 bit.
It looks like it is calculating each number mod 10 (first run is 4567 % 10 = 7). It then runs recursively (rec(num/10)), calling the function on 456, then on 45, then on 4. Since it is adding the number it comes up with to the recursive function (num % 10 + rec(num / 10)), your function is just adding (4567 % 10 + 4...
I have a server that only compiles when I dogcc server.c -o server -lpthreadbut my makefile does it asgcc -lpthread server.c -o serverand just hands me undefined reference errors. How can I change the-lpthreadposition? Here's the file: ``` CC=gcc CFLAGS=-lpthread all: server server: server.c clean: rm -f serve...
The list of libraries should go toLDLIBS, notCFLAGS. From themanual: LDLIBSLibrary flags or names given to compilers when they are supposed to invoke the linker, ‘ld’. LOADLIBES is a deprecated (but still supported) alternative to LDLIBS. Non-library linker flags, such as -L, should go in the LDFLAGS variable. By us...
I didn't understand what is wrong with my code. Here what I am trying to do is toggle a led when I press button. And I count my button hits withint count;. If the count number is even LED is high and else LED is low. But when I upload this program, LED stays on. And off only while I hold the button. ``` while(1){ int...
There is a problem in your logic. You have two changes while pressing the button. The first change is from 0 to 1 (pressing) and the second change is from 1 to 0 (releasing the button). Try something like: ``` if(lastButtonState == 0 && buttonState == 1) ```
this is how I define struct. ``` struct urlFormat { int port; char *host; char *path; int cat; char *status; }; ``` this is how I initialize strcut and allocate the space for the pointer. ``` struct urlFormat *res; res = malloc(sizeof(struct urlFormat)); ``` when I used memcpy() funct...
res->hostis just a pointer (that is not pointing to anything yet). Untilres->hostis pointing to some valid memory you can'tmemcpyto it. You can eithermallocsome memoryres->host = malloc(len + 1);(+1 for the 0 terminator andsizeof(char)is always 1 so omit it) or in this case just useres->host = strdup(ptr1);
``` FILE * file = fopen( “in.txt”, “r” ); char line[80]; if( NULL != file ) { fgets( line, 40, file ); fclose( file ); } ``` Is there anything dangerous in the above code, what i saw here was it got the maximum length 40 string to the buffer line then close the file.
You may be confusingfgets()andgets(). SeeWhy is the gets function so dangerous that it should not be used? As long as the size param matches the buffer size,fgetsis safe. In your case it would be normal to dofgets( line, sizeof(line), file );Note:fgets()reads at most 1 less than "size" and always 0 terminates.
I need to do such works just like the title means.I need to check continuously where there are pictures under a specified directory,and read them to do some necessarily process. But the same time someone else may copy images into the same directory. What should I do to avoid reading incomplete images? Thanks very muc...
Under Linux, there are the guarantee that moving a file in the same device is an atomic operation. That means that either the file doesn't exist, or the file is complete. More info in theman of rename(2): look at the "EXDEV" error. If you can't make this, I advise to create a special dir in your target dir (nommed "t...
In my code I need to compare 2 variables. One variable is of int data type & another is of varchar2 data type. In order to compare I am using the below code: ``` intVariable == atoi(varcharVariable.arr) ``` The issue is that when the corresponding varchar variable is blank then atoi returns 0 which conflicts with m...
Best Way: ``` intVariable == atoi(varcharVariable.arr) && varcharVariable.arr[0] != 0x00 ```
Hi I just wanted to check this. Say if f(n) = O(g(n)) then is f(n)/g(n) = O(1)? and also if f(n) = theta(g(n)) then is f(n)/g(n) = theta(1) Is both statement true? and could if not could I get some explanations on that?
Correction, you're right. Intuitivelyf(n)=O(g(n))means thatfgrows at most as fast asg, hencef(n)/g(n)is "at most constant". Below I give formal proofs for your claims. More formally,f=O(g)means that for all large enoughnwe havef(n) <= C*g(n)for someC>0. Hence for all large enoughnwe havef(n)/g(n) <= C*g(n)/g(n) <= C....
I am trying to find out the definition ofmaybe_make_export_env()in the C implementation of bash in a github repository just forked from its original repository But I can't find it, seehttps://github.com/timlee1/bash/search?utf8=%E2%9C%93&q=+maybe_make_export_env&type= Is it because I didn't use the search feature of...
At most, search results can show two fragments from the same file, but there may be more results within the file. Source As you can see on your search: ``` variables.c Showing the top two matches Last indexed 2 hours ago ``` I didn't find a way to show all matches, I think github just stop at the first two match...
For example, ``` int a = 6; printf("%p", &a); ``` this would print the address of the pointer of a right? but what if we print without &? ``` int a = 6; printf("%p", a); ``` Can someone please tell me what it prints out?
This is undefined behavior, because%pexpects avoid* ``` printf("%p", a); ``` Adding an explicit conversion is allowed, but the behavior is implementation-defined: ``` printf("%p", (void*)a); ``` "Implementation-defined" means that the compiler is free to do whatever it wants when converting aninttovoid*. Seethis Q...
I tested this code in C++ (doing the correct modifications, e.g. printf to std::cout) and it worked. But in C it doesn't. Why is that? If I remove the default values for my x and y in my typedef struct __POINT everything works fine. ``` #include <stdio.h> #include <stdlib.h> typedef struct __POINT { int x = 0, y =...
C - in contrast to C++ - does not support default values defined within astruct. So your program will simply not compile. If you want to initialise the values to0, you could overcome this by usingcalloc(which initializes the memory with0): ``` Point *x = calloc(1,sizeof(Point)); ```
For example, ``` int a = 6; printf("%p", &a); ``` this would print the address of the pointer of a right? but what if we print without &? ``` int a = 6; printf("%p", a); ``` Can someone please tell me what it prints out?
This is undefined behavior, because%pexpects avoid* ``` printf("%p", a); ``` Adding an explicit conversion is allowed, but the behavior is implementation-defined: ``` printf("%p", (void*)a); ``` "Implementation-defined" means that the compiler is free to do whatever it wants when converting aninttovoid*. Seethis Q...
I tested this code in C++ (doing the correct modifications, e.g. printf to std::cout) and it worked. But in C it doesn't. Why is that? If I remove the default values for my x and y in my typedef struct __POINT everything works fine. ``` #include <stdio.h> #include <stdlib.h> typedef struct __POINT { int x = 0, y =...
C - in contrast to C++ - does not support default values defined within astruct. So your program will simply not compile. If you want to initialise the values to0, you could overcome this by usingcalloc(which initializes the memory with0): ``` Point *x = calloc(1,sizeof(Point)); ```
Its quite embarrassing but I really want to know... So I needed to make a conversion program that converts decimal(base 10) to binary and hex. I used arrays to store values and everything worked out fine, but i declared the array asint arr[1000];because i thought 1000 was just an ok number, not too big, not to small.....
No, theinttype has tipically a 32 bit size, but when you declareint arr[1000];you are reserving space for 1000 integers, i.e. 32'000 bits, while withint arr[32];you can store up to 32 integers.You are practically asking yourself a question like this:if an apple weighs 32 grams, I want to my bag to contain 1000 apples...
I'm wondering if someone know effective approach to calculate bits in specified position along array?
Assuming that OP wants to count active bits ``` size_t countbits(uint8_t *array, int pos, size_t size) { uint8_t mask = 1 << pos; uint32_t result = 0; while(size--) { result += *array++ & mask; } return result >> pos; } ```
Today I wrote a code in c with putchar so I can translate it to assembly, but the last putchar I call doesnt print, if I add a newline after it works. ``` else if(R5 == 0x2B) // PLUS { ..... if(R8 >= 10 || R8 == 0) { R5 = 0; zhnr: if(R8 >= 10) { R8 = R8 - 10; ...
stdoutis typically buffered and only flushed when you output new lines.You can either flush it manually usingfflush(stdout);or disable buffering usingsetbuf(stdout, NULL);
Its quite embarrassing but I really want to know... So I needed to make a conversion program that converts decimal(base 10) to binary and hex. I used arrays to store values and everything worked out fine, but i declared the array asint arr[1000];because i thought 1000 was just an ok number, not too big, not to small.....
No, theinttype has tipically a 32 bit size, but when you declareint arr[1000];you are reserving space for 1000 integers, i.e. 32'000 bits, while withint arr[32];you can store up to 32 integers.You are practically asking yourself a question like this:if an apple weighs 32 grams, I want to my bag to contain 1000 apples...
I'm wondering if someone know effective approach to calculate bits in specified position along array?
Assuming that OP wants to count active bits ``` size_t countbits(uint8_t *array, int pos, size_t size) { uint8_t mask = 1 << pos; uint32_t result = 0; while(size--) { result += *array++ & mask; } return result >> pos; } ```
I need to define atypedef p*to a function where it's argument to bep*to astruct. ``` typedef void (*tFunc_t)(pTask_t); // warning: parameter names (without types) in function declaration typedef struct Task_t { struct Task_t *Next; tFunc_t Task; }Task_t, *pTask_t; ``` Since function is part of astruct, h...
You can use forward declaration of thestructto do that. ``` // Forward declaration of the struct struct Task_t; typedef void (*tFunc_t)(struct Task_t*); ``` You don't need to usepTask_tto define thetypedeffor the function pointer.
``` int num1, num2; ``` double average; ``` average=(double)(num1+num2)/2; printf("average: %d", average); ``` My test printf shows average as: 0 This is maybe too easy, but I can't see it. My inputs are both "int" and the average is "double" but somehow it is not calculating right ?
You're using the wrong format specifier toprintf. The%dformat specifier expects anintargument, but you're passing adouble. Using the wrong format specifier invokesundefined behavior. To print adouble, use%f. ``` printf("average: %f\n", average); ```
This question already has answers here:Return value of printf() function in C(13 answers)Closed5 years ago. ``` #include <stdio.h> void main() { printf("%d", printf("%d",printf("Hello world!\n"))); } ``` Why this gives output as 132 ? hello world is 13 units long.
You may be able to see what's happening more clearly if you split the statement into several statements: ``` int temp1 = printf("Hello world!\n"); int temp2 = printf("%d", temp1); printf("%d", temp2); ``` The firstprintfprintsHello world!\n. Since this is 13 characters, it returns13. The secondprintfprints13. Since...
I believe that sizeof an array is of O(1) complexity. A string is a character array, but I heard that strlen is of O(n) complexity, scanning the string until the terminating null. Why isn't it also O(1)?
sizeofjust gets the size based on the type declaration. It doesn't care about the contents, and it's calculated at compile time. strlen()has to scan the array looking for the null byte, as you said. This isO(n). They give different answers. ``` char s[1000] = "abc"; printf("sizeof = %d strlen = %d\n", sizeof s, str...
I am trying to count occurrences of every word in text. So I have stored all words and counts in binary tree: ``` typedef struct Node{ char* word; int count; struct Node *left; struct Node *right; struct Node *parent; } Node; ``` Now I need to sort tree by number of coun...
Traverse the tree and extract the word and its count into an array of these: ``` struct WordAndCount { char * word; int count; }; ``` Then useqsortto sort the array. You will need a custom compare function that compares WordAndCount.count;
There doesn't seem to be a 'J' suffix (a la printf's %jd). So, is it guaranteed that theLLandULLsuffixes are going to work with intmax_t and uintmax_t types? ``` #include <stdint.h> intmax_t yuuge = 123456789101112131411516LL; ``` or is it possible that there are literals that are too big for theLLsuffix? Say, a ...
No suffix is neededif you just want the value to be faithfully represented. The C language automatically gives integer literals the right type. Suffixes are only needed if you want to force a literal to have higher-rank type than it would naturally have due to its value (e.g.1ULto get the value 1 asunsigned longrather...
I am trying to count occurrences of every word in text. So I have stored all words and counts in binary tree: ``` typedef struct Node{ char* word; int count; struct Node *left; struct Node *right; struct Node *parent; } Node; ``` Now I need to sort tree by number of coun...
Traverse the tree and extract the word and its count into an array of these: ``` struct WordAndCount { char * word; int count; }; ``` Then useqsortto sort the array. You will need a custom compare function that compares WordAndCount.count;
There doesn't seem to be a 'J' suffix (a la printf's %jd). So, is it guaranteed that theLLandULLsuffixes are going to work with intmax_t and uintmax_t types? ``` #include <stdint.h> intmax_t yuuge = 123456789101112131411516LL; ``` or is it possible that there are literals that are too big for theLLsuffix? Say, a ...
No suffix is neededif you just want the value to be faithfully represented. The C language automatically gives integer literals the right type. Suffixes are only needed if you want to force a literal to have higher-rank type than it would naturally have due to its value (e.g.1ULto get the value 1 asunsigned longrather...
I am testing a program "myprog.c" that crashes if it runs with any input parameter: ``` #include <stdlib.h> int main(int argc, char * arg[]){ if (argc > 1 ){ abort(); } } ``` As expected, "./myprog.out abc" crashes. But then I tried to get inputs from a file: "./myprog.out < inputs.txt", where inputs.txt h...
That's because the shell doesn't pass< inputs.txtas arguments. Instead the shell makes it so that the contents ofinputs.txtis to be read fromstdin.
how can I optimize this for loop: ``` for (l = 1; l <= loop; l++) { for (i = 1; i < n; i++) { x[i] = z[i] * (y[i] - x[i - 1]); } } ``` and how can I parallel original and optimized version of it byOpenMp?
Assuming you want to parallelize the inner loop ``` for ( i = 1; i < n; ++i ) { x[i] = z[i] * ( y[i] - x[i - 1] ); } ``` I would suggest pre-computing the part that are not dependent on the previous loop. which is easier to parallelize. ``` double preComps [n]; #pragma omp parallel for for( i = 1; i < n ; ++i )...
Why does case 2 get evaluated twice in this for loop? ``` for (int x = 0; x <4; x++) { switch (x) { case 2: printf("%d", x); case 0: printf("%d", x); default: break; case 3: printf("%d", x); } } ``` edit: I forgot to add that this is not a legitimate piece of code. Just so...
Case 2 doesn't get evaluated twice: it is evaluated exactly once. However, when you don't end a case with thebreakstatement, instead of leaving theswitch, execution continues to the next case. In other words, whenxis 2, execution jumps tocase 2and callprintf("%d", x)with x = 2. Then, execution falls through to case 0...
I am making calculator for physics, but when I was coding the focal length equation I needed to find the reciprocal of the fraction found for the focal length.
``` double eqn_reciprocal= pow(eqn,-1); ``` this would do the trick
I have this expression: ``` const int numPlayers = 2; player players[numPlayers]; ``` This is an array of user-defined type players (using struct). However, I get an error saying thatnumPlayershas to be a constant value. ``` expression must have a constant value ``` What am I doing wrong? I have also initialize...
In C99, the below works fine inside a function. It is avariable length array(VLA). ``` const int numPlayers = 2; player players[numPlayers]; ``` Otherwise use a#definefor a trueconstant. ``` #define numPlayers 2 player players[numPlayers]; ```
I need to find the name of a file using * in a C program. There is exactly 1 file in the specific folder that has the extension .UBX. I can do this in terminal but it doesn't work in C. Can anyone give me example code to do this? ``` //There is exactly 1 file that ends in .UBX #define FILE_TO_SEND "/home/root/l...
This should do the trick: ``` #include <glob.h> #include <stdlib.h> #include <fcntl.h> #define FILE_TO_SEND "/home/root/logs/*.UBX" int main (void) { glob_t globbuf; glob(FILE_TO_SEND, 0, NULL, &globbuf); if (globbuf.gl_pathc > 0) { int fd = open(globbuf.gl_pathv[0], O_RDONLY); //...
I need to read IP addresses into a char array for working on it later. Since IP octets can be as big as 256, I thought it would be good to use unsigned char array to read them. This is how I intend to use it. ``` sprintf(buf,"%d.%d.%d.%d",ip24,ip16,ip8,ip); ``` But it appears that first argument of sprintf should be...
The type ofbufshould bechar*in first place. The fact that an IP octet can be as big as 256 (that is it is a unsigned char) has nothing to do with the fact thatbufis an array ofunsigned char. sprintwants achar*as first argument, so give it a char: Live Demonstration
I get an error "conflicting types for 'abs' in my function. The code is very simple. ``` double abs (double x) { // Returns absolute value if (x<0) return (x*(-1)); else return x; } ``` This is on a C proyect on codeblocks. I already tried casting the returns but the error remains anyway.
My guess is you have<stdlib.h>included becauseabsis already declared there and has the signatureint abs(int), so your definition produces "conflicting types".
If condition inside thefindsetis not giving correct comparison. It is always shows not equal. Where did I make a mistake? ``` #include<stdio.h> struct node { struct node *p; int rank; }; void makeset(struct node x) { x.p = &x; x.rank = 0; } void findset(struct node x) { if (x.p == &x) { printf("It ...
``` void findset(struct node x) { if (x.p == &x) { ``` thatxis a copy of the one passed in... x is always brand new and&xwont match any previous address. Note that this is true not just of structs but all values... ``` int i = 3; void f( int j) { // &j != &i // j == i // j and I have the same ...