question
stringlengths
25
894
answer
stringlengths
4
863
I'm a University student and I'm trying to verify different printf output through the following code: ``` #include <stdio.h> int main() { int i=3,j=0; float x=5,y; printf("1: %d\n", i); printf("2: %d\n", i/j); printf("3: %d\n", i*i); printf("4: i = \n"); i=i + j; printf("6: %f\n", x/y); printf("7: x = %f\n"); printf("8: %d\n", i/2); printf("9: %f", x/2) ; return 0; } ``` In the execution phase, after the first outputprintf("1: %d\n", i);, I don't get anything in the terminal. Any idea? (no compiling error)
i / jis3 / 0, and integer division by 0 in C is Undefined Behavior, which means that literally anything can happen. In your case, "literally anything" meant "go back in timeand make the previousprintfnot work, then crash" (this actually happened due to how buffering works, but that's just an implementation detail).
Is there any other way of passing user's parameters into a program other than through ./program argument1 argument2 whereargument1andargument2will be passed on tomain'sargv[]?
Your application could read the values from the standard input, a configuation file or even environnent variables.
I was trying to help a student friend understand his C lesson (talking pointers, adresses, ...) and he asked me why in this picture 'e' has memory adress 5004 why did we increase by 4 ? (what does 4 represent ?) I know string storage can depend on the physical machine arch but I'd like some simple explanation since I'm myslef not that strong in C. the pic is fromhttp://www.mathcs.emory.edu/~cheung/Courses/255/Syl-ARM/2-C-adv-data/string.html
Each character in c takes 1 byte. I am not sure that this diagram is correct since memory is typically byte addressable so the ‘e’ should be one byte away from the ‘h’. Typically, memory addresses are incremented by 4 because that is how many bytes are used to store an integer which is one of the more common data types in c.
My program need to display some unicode strings. If I save the source code using UTF-16LE, everything works fine. However, I was not be able to cross compile in linux using mingw. If I save the source using UTF-8, the source code can be compiled with no problem. But all the const unicode strings were not displayed correctly since they are encoded as UTF-8. How can I properly display unicode string when the source code is saved as UTF-8 encoded? Example Code: ``` #include <Windows.h> int main(int argc, const char *argv[]) { MessageBoxW(NULL, L"你好", L"你好", MB_OK); } ``` Compiled with UTF-16LE source file Compiled with UTF-8 source file
After some testing, it turns out visual studio cannot encode string correctly if the file is encoded to UTF-8 without signature(BOM). Everything works fine after changing encoding scheme to UTF-8 with signature.
Every time we allocate memory for linked list in heap we get an address and this address is linked to the next variable of linked list and head is a pointer which pointer to beginner node of linked list. If we dohead = head + 1than it points to next linked list or it points to random memory of heap or it points to the next memory of beginner list in the heap.
it points to a memory area right after the first element, which you shouldn't be accessing. I think you're confusing the concept of array with linked list. If you use an array, thenhead = head + 1would have given you the next element in the array. But on a linked list every member has a different location in memory, and the only way to get that location is by dereferencing the previous element'snextmember
I was to ask to add the value of a number character into an integer, does anyone know how to do that? ``` #include<stdio.h> int main() { char num[100]; int sum=0,n; printf("Total number: "); scanf("%d",&n); for(int i=0;i<n;i++) { printf("Number %d: ",i+1); scanf("%s",&num); sum=sum+num; } printf("Total = %d",sum); } ```
You need to convert a string into integer using (atoi) the numerical representation to add it. ``` #include<stdio.h> #include<stdlib.h> int main() { char num[100]; int sum=0,n; printf("Total number: "); scanf("%d",&n); for(int i=0;i<n;i++) { printf("Number %d: ",i+1); scanf("%s",&num); sum+=atoi(num); } printf("Total = %d",sum); } ```
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.Closed3 years ago.Improve this question I want to know if the following piece of code will produce a memory leak: ``` m = malloc(5); m = NULL; ```
Yes, there is a memory leak. The 5 allocated bytes are no longer accessible as you don't have a pointer to them. If you save the pointer, you can still use, and free, the resources ``` unsigned char *m = malloc(5); if (m) { unsigned char *p = m; m = NULL; // can no longer access the memory through m p[2] = 1; // but p is ok free(p); // p is ok to free } else { fprintf(stderr, "Problem! malloc failed!\n"); exit(EXIT_FAILURE); } ```
``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main () { char *str; /* Initial memory allocation */ str = (char *) malloc(15); strcpy(str, "tutorialspoint"); printf("String = %s, Address = %u\n", str, str); /* Reallocating memory */ str = (char *) realloc(str, 25); strcat(str, ".com"); printf("String = %s, Address = %u\n", str, str); /* Deallocate allocated memory */ free(str); printf("\n%d",*str); return(0); } ```
Your last print says to print the character pointed to bystras a decimal, which is exactly what it did (for a memory location you just deallocated, making thisundefined behavior).
``` union a { int i; char ch[4]; }; void main() { union a u; u.ch[0]=3; u.ch[1]=2; u.ch[2]=0; u.ch[3]=0; printf("%d %d %d",u.ch[0],u.ch[1], u.i); } ``` Ouput : 3 2 515 Why i get 515 for u.i Can anyone please explain me about this?
Check this, the system will allocate 2 bytes for the union. The statementsu.ch[0]=3,u.ch[1]=2store data in memory as given below. To be more clear ``` u.ch[0]=3; u.ch[1]=2; ``` Now u.i is calculated as ``` (2)(3) in binary form which is equal to 515. (2) --> 00000010; (3) --> 00000011 (2)(3) --> 0000001000000011 --> 515. ``` Hope this will help you.
I am confused on how I should format the for loop. I want to print "Happy Birthday" as many times as the user inputs. ``` #include <stdio.h> int main(){ int age; int bdays; printf("What is your age?"); scanf("%d", age); for(age = 0; **`age ????`**; age++){ printf("Happy Birthday\n"); } } ```
You have to iterate over a loop control variable ``` #include <stdio.h> int main() { int age; int bdays; printf("What is your age?\n"); scanf("%d", &age); for (int i = 0; i < age; i++) { printf("Happy Birthday\n"); } } ``` And do not forget to use pointer inscanf()
I want to convert this hex string into raw binary file using BIGNUM's BN_bn2bin function ``` BN_hex2bn(&asn1hash, "3031300D060960864801650304020105000420BC5F9353CBB9DCAE86B9F8F68C1C95856DB836ACA2E00C9319716CDF4DD0F5BA"); char *buf = (unsigned char *)malloc(BN_num_bytes(asn1hash)); BN_bn2bin(asn1hash, buf); FILE *fp; fp = fopen("ASn1Hash","wb+"); fputs(buf, fp); fclose(fp); ``` But why is it that only "30 31 30 0D 06 09 60 86 48 01 65 03 04 02 01 05" is ever outputted into the file?
thanks fixed the code ``` BN_hex2bn(&asn1hash, "3031300D060960864801650304020105000420BC5F9353CBB9DCAE86B9F8F68C1C95856DB836ACA2E00C9319716CDF4DD0F5BA"); int num_bytes = BN_num_bytes(asn1hash); char *buf = (unsigned char *)malloc(num_bytes); BN_bn2bin(asn1hash, buf); FILE *fp; fp = fopen("ASn1Hash","wb+"); fwrite(buf, 1, num_bytes, fp); fclose(fp); ```
I'm currently developing a piece of software on a Raspberry Pi. Because I have to control motors very precisely i developed a C script, that does that for me. My current problem is, that I didn't found any solid method to transfer a list of signed floats from a Python3 Script to a C script. It is really important, that the method is fast.
You could use a socket to send data from one script to the another.
I'm currently developing a piece of software on a Raspberry Pi. Because I have to control motors very precisely i developed a C script, that does that for me. My current problem is, that I didn't found any solid method to transfer a list of signed floats from a Python3 Script to a C script. It is really important, that the method is fast.
You could use a socket to send data from one script to the another.
Consider this code: ``` char* f(char* str) { return ++str; } int main() { char* str = "test"; str = f(str); //flag return 0; } ``` At 'flag' what happens with the memory address where the first original 't' resides? Will it be free-ed or will it be a 'stack leak'?
``` char *str = "test"; ``` There are 2 objects "in play" here: thestrobject of typechar*(pointer to char) and the unnamed object of typechar[5]. The unnamed array object (with contents{'t', 'e', 's', 't', 0}), when used as initialization value for a pointer get converted to a pointer to its first element and it's that address that gets copied tostr. There is no allocation of memory, so there is no chance of having memory leaking!
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.Closed3 years ago.Improve this question I am new to programming and as well as RISC-V. I have a few questions regarding the RISC-V compilers: Do RISC-V compilers support the C program?From which RISC-V cross compiler can I generate ELF files that accept C program?Can anyone who is familiar with these things please help me in the learning process?
Here is aRISC-V GNU Compiler Toolchain. It is a cross compiler that makes it possible to build ELF files for RISC-V on a standard Linux system. It can be a bit of a challenge to build a toolchain by yourself, but there seems to be good instructions for this one. Often you get a pre-built toolchain from a supplier. If you have that I recommend you to use it instead of building one yourself.
This question already has answers here:printf anomaly after "fork()"(3 answers)Closed3 years ago. ``` #include<stdio.h> #include<Unistd.h> Void main() { Printf("hi"); fork(); Printf("hello"); } ``` Output: hi hello hi hello"But when iam using \n in the printf statements iam getting the output as" ``` Output: hi hello hello ``` [But \n is used for displaying statement in new line but why am i getting this difference] Thank you ...
printfbuffers its output, and when youfork, now the output is in both programs' buffers, so they'll both eventually print it. To fix it, you should force the buffer to be flushed immediately before forking by doingfflush(stdout). You don't see the problem with\nbecause using\nalso flushes the buffer.
This question already has answers here:Is floating point math broken?(33 answers)Closed3 years ago. I have met a strange 9(unexpected) output fromprintfin C. The code is: ``` 1 #include <stdio.h> 2 3 int 4 main(void) { 5 printf("%lf", 3.14 - 1e20 + 1e20); 6 } ``` However, the output is 0.000000. I do not know how it works. Can anyone help?
Thedoubleyou're trying to print has53 bits of precision and 11 bits of exponent.1e20(base 10) is101 0110 1011 1100 0111 0101 1110 0010 1101 0110 0011 0001 0000 0000 0000 0000 0000in binary (56BC75E2D63100000in hex). Your3.14is too small to be represented once added to a number of that magnitude. Change the order of operations if you want to work around that. This code: ``` printf("%f\n", -1e20 + 1e20 + 3.14); ``` Prints3.140000.
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.Closed3 years ago.Improve this question When I write ``` int c = (3+2)*2/5; ``` My programming tool rewrites this as ``` int c = (3 + 2) * 2 / 5; ``` I got some questions. Is it only accepted by compiler to space between number and operator? Typing space between number and operator myself is better than depending on tool's automatic help?
Whitespace between tokens is unneeded in general, and completely irrelevant in your scenario. Exception #1: Whitespace is sometimes needed to denote the end of a token. For example,int foo(int)can't be writtenintfoo(int), anda+++bis equivalent toa++ + brather thana + ++b. Exception #2: Line feeds are sometimes significant. For example, it marks the end of a//command and of a#directive.
``` switch (ch) { case '~' || 177: tile->tileType = TILE_NONE; return true; case '@' || 219: //error here: '@' tile->tileType = TILE_WALL; return true; } ``` The error reads: "case value '1' already used" .....what the hell?? I've tried to clean the solution, restarted, used another PC. I'm "this close" to just reinstalling VS. Any idea what is happening?
You cannot have more than one case divided by||like you would an if statement. You have the case ``` '~' || 177: ``` Which is a boolean expression that evaluates to true,which gets evaluated to1because cases can only be an integral type (int,charandenum), so it must be converted to anint. So you are really saying ``` case 1: ``` The same thing happens in your second case statement, which is evaluated to a secondcase 1:, hence the error Instead do: ``` case '~': case 117: //code ```
``` char myStr[] = "Hello World"; char *p = strchr(myStr, 'W'); *p = '\0'; // Now myStr would be "Hello "; ``` If I do something like this, would this leak memory for "orld" part?
No, because in C, strings are just pre-definedchararrays that are terminated with the'\0'character. All the space for the string of characters is pre-allocated at run time and is inflexible unless you reassign the variable to point to a different section of memory, which is outside of the scope of this question. In your example you initialize achararray to "Hello World" which is 12 bytes counting the \0 character at the end. Those 12 bytes are yours to use until the program finishes and will not be lost by conventional means. Resetting the contents of the string is as simple as writing different values to thechararray. As long as your data does not exceed the limits of the array, you will not run into any issues or memory leaks. Hope this helps.
Is there a way to set default format for debugging variables to HEX? I am using: Eclipse IDE for C/C++ Developers Version: 2019-12 (4.14.0) Build id: 20191212-1212 I've seenthisold post but on my eclipse version there is no option for that.
Unfortunately the option to custom the number format was removed from eclipse preferences and should be returned sometime. From eclipse Bugzilla:bug 373550(status: open with dependency) "Note that with the removal of CDI (Bug 484900), this preference page was removed."
I have a structure: ``` struct options { char *type; char *action; } params; ``` 'type' and 'action' arrive from user input, and this is required parameters. But, i want to geting optional parameters and record it to struct. How can i do this? Is this possible?
C++ Way Depending on the type(s) of the optional parameters, you might want to considerstd::maporstd::unordered_mapwith an appropriate template type (e.g., some sort of polymorphic base reference). C Way This gets a little tricky, but there are some design options. In short, you're going to have to default the optional parameters to some common type (e.g., char-strings), and have a struct pairing them appropriately. For example, ``` typedef struct{ char param[32]; char* val; } ParameterPair; ```
I created array: ``` int main() { int num[3] = {1, 2, 3} return 0; } ``` I want to get element in place 1. Why can not I get the element by this code? ``` printf("%d", *(num + (sizeof(int)*1))); ``` What is the different to this? ``` printf("%d", *(num + 1)); ```
I understand you thought incrementing the pointer usingsizeof(int)will get you to the next member in the array. However, this is not how it works: when you write: ``` printf("%d", *(num + 1)); ``` the pointer advances to the next member in the array (it is an int pointer and therefore when you increment it, it advances sizeof(int) (which is usually 4) bytes). But when you write: ``` printf("%d", *(num + (sizeof(int)*1))); ``` you try to advance the pointer by 4 members (or 4*sizeof(int) bytes), which is out of the boundaries of your array.
To avoid duplication, I want to use__LINE__in the auto-generated variable name. ``` #define ROUTE(path, impl) \ char * k##impl##__LINE__##_route = "{"#path":\""#impl"\"}"; ``` But it always be treated as a normal string__LINE__. Even if I define it as the following, I can not get what I want: ``` #define ROUTE(path, impl) ROUTE_(path, impl, __LINE__) #define ROUTE_(path, impl, line) \ char * k##impl##line##_route = "{"#path":\""#impl"\"}"; ```
You need one more level of nesting: ``` #define ROUTE(path, impl) ROUTE_(path, impl, __LINE__) #define ROUTE_(path, impl, line) ROUTE_1(path, impl, line) #define ROUTE_1(path, impl, line) \ char * k##impl##line##_route = "{"#path":\""#impl"\"}"; ```
The question is to evaluate the Sin(x) series using functions. The code compiles successfully but doesn't work, it doesn't even run. ``` #include <stdio.h> #include <math.h> void sine(int, float *); void factorial(int, int *); int main() { int x, fact; float sol; scanf("%d", &x); sine(x, &sol); printf("Solution of Sin(x) series is %f.", sol); return 0; } void sine(int x, float *sol) { int i; int fact=1; factorial(x, &fact); for (i=3;i>0;i+=2) *sol=x+pow(-1, i)*pow(x, i)/fact; } void factorial(int x, int *fact) { int j; for (j=1;j<=x;j++) *fact*=j; } ```
Theforcycle in yoursinefunction doesn't seem to be right. You're checking fori > 0, yet you initialize it to 3 and increment it in steps of 2. That cycle might only be broken whenioverflows, but that is undefined behavior (seehere).
In the textbook my teacher provided us, there is this C code's sample, which when I try to run gives a Segmentation Fault error: ``` const celula *nulo = NULL; typedef char informacao; typedef celula *noh; typedef celula *arvore; struct celula {informacao info; noh pai; noh fesq; noh idir;}; ... typedef struct celfloresta celfloresta; typedef struct celfloresta *floresta; typedef struct celfloresta *posicfloresta; struct celfloresta {arvore elem; celfloresta *prox;}; ... void FormarListaNohs(){ floresta p = (floresta)malloc(sizeof(celfloresta)); p->elem->info = '3'; } ... ``` Why does the linep->elem->info = '3';give segmentation fault here?
elemis a pointer. You need to allocate memory for it: ``` p->elem = malloc(sizeof(arvore)); ```
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed3 years ago.Improve this question Sorry for inconvenience, I don't know much about C++, i am facing this error while running on LINUX. Two errors in last two lines, and the error is the same. What am i doing wrong? Thanks! ``` #define AOCL_ALIGNMENT 64 void *ptr = NULL; posix_memalign(&ptr, AOCL_ALIGNMENT, 128); free(ptr); ```
You can't call function outside of a scope in C/C++. You have to call them from a function: ``` #define AOCL_ALIGNMENT 64 int main() { void *ptr = NULL; posix_memalign(&ptr, AOCL_ALIGNMENT, 128); free(ptr); } ```
I get the idea of if theif condition is wrongthe if case won't be executed, but thefor loop will still continue. But somehow I'm stucked upon this simple problem. ``` int divisorA[20]={0},indexA=0,a=42; for (int i =1;i<a+1;++i){ if (a % i == 0){ divisorA[indexA] = i; ++indexA; printf("%d %d\n",divisorA[indexA],indexA); } } ``` Output ``` 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 ``` Desired ``` 1 1 2 2 3 3 6 4 7 5 14 6 21 7 42 8 ```
You at first increased the index and only after that you outputted the array element at the index position that will not be yet set. ``` ++indexA; printf("%d %d\n",divisorA[indexA],indexA); ``` Write ``` ++indexA; printf("%d %d\n",divisorA[indexA-1],indexA); ``` Pay attention to that indices in C start from 0.
The return value ofisalpha()is0if the character is not alphabet and non-zero if its an alphabet. This is also the case for many otherctype.hlibrary functions. Is there any meaning of the return type of this function?In other words, why not simply return1for alphabet characters?I googled and did not find any answer.
The return value is not specified, because it might save a few cycles for common implementations tonothave to set it to 1, if it is not zero. For example, the inequality-test could be implemented as subtraction ``` #define NEQ(a,b) (a-b) ``` If you require to have it return1on inequality, you have to do a little more work than only the subtraction. Hence, it might perform better tonotinsist that the functions return 1.
``` #define print(args) printf args print(("Hello")); ``` I got output ``` Hello ``` If I call print it works fine. Could you explain how it works?
This is an example of a macro. When you compile a program, the first step is the preprocessor. The preprocessor finds your macro: ``` #define print(args) printf args ``` This means that if in your program you have something like ``` print(<some text>) ``` Then the value of<some text>will be processed asargsfrom your macro, i.e. code ``` print(<some text>) ``` will be replaced with ``` printf <some text> ``` Now, you have this line of code: ``` print(("Hello")); ``` If you put<some text>=args=("Hello"), then preprocessor will replace ``` print(("Hello")) ``` with ``` printf ("Hello") ``` and the whole line will be: ``` printf ("Hello"); ``` which is legal c code to printHello.
Please tell me if the title is not entirely correct. I first initialize a pointer to array using malloc in the main, then I pass it to a function which receives a pointer to pointer to int like this: ``` void readfile(int**); int main(void) { int (*obsF) = malloc(sizeof(int)*16); readfile(&obsF); free(obsF); } void readfile(int **obsF) { //I can do this without errors: obsF[0][1] = 1; } ``` I don't understand why I have to treat it as a 2D array, because if I doobsF[1] = 1I get an error. Could someone explain me why this happens?
Change your function signature fromvoid readfile(int**)tovoid readfile(int*)and fromvoid readfile(int **obsF)tovoid readfile(int *obsF). When you put the function signature as int**, the compiler treats it as a pointer to a pointer, and thus it is treated as a 2D array, and not a 1D array.
``` #define print(args) printf args print(("Hello")); ``` I got output ``` Hello ``` If I call print it works fine. Could you explain how it works?
This is an example of a macro. When you compile a program, the first step is the preprocessor. The preprocessor finds your macro: ``` #define print(args) printf args ``` This means that if in your program you have something like ``` print(<some text>) ``` Then the value of<some text>will be processed asargsfrom your macro, i.e. code ``` print(<some text>) ``` will be replaced with ``` printf <some text> ``` Now, you have this line of code: ``` print(("Hello")); ``` If you put<some text>=args=("Hello"), then preprocessor will replace ``` print(("Hello")) ``` with ``` printf ("Hello") ``` and the whole line will be: ``` printf ("Hello"); ``` which is legal c code to printHello.
Please tell me if the title is not entirely correct. I first initialize a pointer to array using malloc in the main, then I pass it to a function which receives a pointer to pointer to int like this: ``` void readfile(int**); int main(void) { int (*obsF) = malloc(sizeof(int)*16); readfile(&obsF); free(obsF); } void readfile(int **obsF) { //I can do this without errors: obsF[0][1] = 1; } ``` I don't understand why I have to treat it as a 2D array, because if I doobsF[1] = 1I get an error. Could someone explain me why this happens?
Change your function signature fromvoid readfile(int**)tovoid readfile(int*)and fromvoid readfile(int **obsF)tovoid readfile(int *obsF). When you put the function signature as int**, the compiler treats it as a pointer to a pointer, and thus it is treated as a 2D array, and not a 1D array.
I'm having problem while reading two floating point values for this c code snippet: ``` #include<stdio.h> long double add(long double a, long double b) { return a+b; } int main() { long double a, b; printf("Input two FP values: "); //Here scanf isn't reading the 2nd value. scanf("%lf %lf", &a, &b); printf("%lf", add(a,b)); return 0; } ``` When providing 2 and 4 as input, program is displaying 0.000000 as output.
Learn how to enable warnings in your compiler and don't ignore them. a.c:10:11: warning: format ‘%lf’ expects argument of type ‘double *’, but argument 2 has type ‘long double *’ [-Wformat=]a.c:10:15: warning: format ‘%lf’ expects argument of type ‘double *’, but argument 3 has type ‘long double *’ [-Wformat=]a.c:11:12: warning: format ‘%lf’ expects argument of type ‘double’, but argument 2 hastype ‘long double’ [-Wformat=]
I wrote a program to check the frequency of numbers from 0 to 9 in a given input STRING e.g "abc12af1479" here '0' does not occur, '1' occurs 2 times and so on. The printf statement that i wrote for count is not working is something wrong here or my logic is wrong? ``` int main() { char ch[1000], s[10]={'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; int i, j, count; gets(ch); for(i=0; s[i]<10; i++) { count=0; for(j=0; ch[j] != '\0'; j++) { if(ch[j]==s[i]) { count++; } } printf("%d ", count); } return 0; } ```
The problem is here: ``` for (i = 0; s[i] < 10; i++) ``` In this case,s[0]is thechar'0', which will likely have a value that's greater than10. InASCIIit is48, sos[i] < 10;is always false and the loop never runs. Instead, change this loop to: ``` for (i = 0; i < 10; i++) ```
I'm trying to get value of variableAfrom the void pointerB Casting void pointer tochar *give me wrong unreadable value This is my code ``` #include <stdio.h> int main() { char *A = "1020304050"; void *B = &A; printf("%p -- %p -- %s -- %s", &A, B, A, (char *) B); return 0; } ``` This is my result: 0x7ffc2db2f820 -- 0x7ffc2db2f820 -- 1020304050 -- @ should be 0x7ffc2db2f820 -- 0x7ffc2db2f820 -- 1020304050 -- 1020304050
In theprintfcall you're casting the value ofBtochar *, but that's not what you assigned to it. You assigned&Awhich has typechar **. You need to either assignAtoB: ``` void *B = A; printf("%p -- %p -- %s -- %s", (void *)&A, (void *)B, A, (char *) B); ``` Or castBto achar **and dereference the casted pointer: ``` void *B = &A; printf("%p -- %p -- %s -- %s", (void *)&A, (void *)B, A, *(char **)B); ```
I wrote a program to check the frequency of numbers from 0 to 9 in a given input STRING e.g "abc12af1479" here '0' does not occur, '1' occurs 2 times and so on. The printf statement that i wrote for count is not working is something wrong here or my logic is wrong? ``` int main() { char ch[1000], s[10]={'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; int i, j, count; gets(ch); for(i=0; s[i]<10; i++) { count=0; for(j=0; ch[j] != '\0'; j++) { if(ch[j]==s[i]) { count++; } } printf("%d ", count); } return 0; } ```
The problem is here: ``` for (i = 0; s[i] < 10; i++) ``` In this case,s[0]is thechar'0', which will likely have a value that's greater than10. InASCIIit is48, sos[i] < 10;is always false and the loop never runs. Instead, change this loop to: ``` for (i = 0; i < 10; i++) ```
I'm trying to get value of variableAfrom the void pointerB Casting void pointer tochar *give me wrong unreadable value This is my code ``` #include <stdio.h> int main() { char *A = "1020304050"; void *B = &A; printf("%p -- %p -- %s -- %s", &A, B, A, (char *) B); return 0; } ``` This is my result: 0x7ffc2db2f820 -- 0x7ffc2db2f820 -- 1020304050 -- @ should be 0x7ffc2db2f820 -- 0x7ffc2db2f820 -- 1020304050 -- 1020304050
In theprintfcall you're casting the value ofBtochar *, but that's not what you assigned to it. You assigned&Awhich has typechar **. You need to either assignAtoB: ``` void *B = A; printf("%p -- %p -- %s -- %s", (void *)&A, (void *)B, A, (char *) B); ``` Or castBto achar **and dereference the casted pointer: ``` void *B = &A; printf("%p -- %p -- %s -- %s", (void *)&A, (void *)B, A, *(char **)B); ```
In C, the prototype for the absolute value function (that accepts a float) is ``` float fabsf( float ); ``` Why doesn't this prototype accept a constant value, like this: ``` float fabsf( float const ); ``` fabsf won't change the value of the input, will it? If I have a function that accepts an input and calls fabsf, am I forced to avoid specifying the input as const? What is the appropriate way to handle const correctness in this situation?
C uses pass by value. The value for the parameter of a function is a copy of the argument you give. It is OK to copy both const and non-const floats, and the result is a non-const float. It is similar to assignment: ``` const float f = 5.5f; float g = f; // OK ``` In fact, the language specifies that the value of an expression can never beconst, i.e. when a value is read from a variable, that value is notconsteven if the variable was.
I have read that task manager (windows 10) shows the amount of address space allocated, not the actual amount of memory being used. It's not clear for me how it refers to memory usage of C/C++ application. When I call malloc/new I treat that memory as allocated and being used, so how to explain that difference ?
When your application allocates memory, the OS may not actually allocate it at once (this is the case for Linux at least, unless you change the default allocation policy). Instead, the OS will back the allocation when your applicationactuallyaccesses the memory. That is, when it gets a page fault for an address you have allocated. This is usually a sane strategy, since many programs allocate alotof memory but then only access only a small portion of it.
I'm trying to get current position of file that over 2GB on 32bit OS. I defined LARGEFILE_SOURCE and FILE_OFFSET_BITS=64 options like below.APP_CFLAGS := -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 And if I compile on ndk, It sayserror: use of undeclared identifier 'ftello'; did you mean 'ftell'? How can I solve this?
Ah Now I got it.. To set minSdkVersion in compiler option, I have to do like below.APP_PLATFORM := android-24 Thanks for your advice!
I've been doing some homework on which data structure is best for optimized lookup of IPv4 addresses to implement in C. I don't need key-value, just to check if it's present in a set. I can't have false positives, so no bloom filter. Most of the options recommended (radix tree, y-fast tree) are for key-value storage. I've considered a hash table, but don' t need to store a value, just a key. What's the best way to do this with fast lookups as the foremost concern?
Usually, with very little work you can change the structure to treat the key as the value itself. Such sorted-set, which might be based on a skip-list, will be leaner.
I am learning about the usage of stack and I notice that they are used differently, or apparently so, in C and Java. For example, the code below written in C will not work because it will clobber "name" ``` char* getName(){ char name[32]; scanf( "%s",name); return name; } int main (int argc, char *argv[]){ char *myName = getName(); printf("%s", myName); } ``` However, if I write something similar in Java, it works just fine: ``` public static String getName(){ String name = "A name"; return name ; } static void main(String[] args){ String name = getName(); System.out.print(name); } ``` I want to know why. Why does the stack not clobber in Java but does so in C ?
In Java, the memory for local variables is not allocated on the stack... only the reference is put on the stack. The object itself is put on the heap.
Is it possible to assign a string wirth multiple variable to a char array ? For example : ``` char array[100]; int valeur=5; int score=10; array=("Bravo vous avez gagné %d points (total: %d)",valeur,score); printf("%s\n",array); ``` output :Bravo vous avez gagné 5 points (total: 10)
You want to use sprintf(array, "Bravo vous avez gagne le yoyo et %d points", valeur); You can add any variables like in printf. sprintf(array, "Bravo vous avez gagne %d points et le score est %d", valeur, score);
This question already has answers here:How || and && works [duplicate](5 answers)Closed3 years ago. I am having trouble understanding why the following code: ``` 0 || -1 ``` Evaluates to1? More specifically, I am confused as to what the || and && operators mean when applied to integers.
Every expressionvalue != 0evaluates to1, ifvalueis not equal to zero. (see comment from @MiCo and @M.M.) ||is an or operation with two operands. If the left or the right operand is not zero the or operation evaluates to1. Since-1is not0it evaluates to1,
``` #include <stdio.h> int main() { char a = 'A'; int b = 90000; float c = 6.5; printf("%d ",sizeof(6.5)); printf("%d ",sizeof(90000)); printf("%d ",sizeof('A')); printf("%d ",sizeof(c)); printf("%d ",sizeof(b)); printf("%d",sizeof(a)); return 0; } ``` The output is: ``` 8 4 4 4 4 1 ``` Why is the output different for the same values?
Constants, like variables, have a type of their own: 6.5: A floating point constant of typedouble90000: An integer constant of typeint(ifintis 32 bits) orlong(ifintis 16 bits)'A': A character constant of typeintin C andcharin C++ The sizes that are printed are the sizes of the above types. Also, the result of thesizeofoperator has typesize_t. So when printing the proper format specifier to use is%zu, not%d.
Here's the function I use to add an accelerator (hotkey) to a closure (function) ``` void gtk_accel_group_connect (GtkAccelGroup *accel_group, guint accel_key, GdkModifierType accel_mods, GtkAccelFlags accel_flags, GClosure *closure); ``` accel_keyis the value of the key we want to activate the function, here's we have keys:https://gitlab.gnome.org/GNOME/gtk/blob/master/gdk/gdkkeysyms.h How can I combine keys, for exampleGDK_KEY_Control_LandGDK_KEY_sto set the save function?
You could usegtk_accelerator_parse ``` guint key; GdkModifierType mod; gtk_accelerator_parse("<Ctrl>s", &key, &mod); ``` The returnedkeywill be youraccel_key Side note: the linked header must define all those values asunsigned....
found this code that is responsible for printing out a two-dimensional array ``` for (int i = 0; i < n; i++) for (int j = 0; j < n || !putchar('\n'); j++) printf_s("%4d", A[i][j]); ``` how does boolean expression that causes printing out an escape sequence at the end of each row work?
Because of||, the functionputcharwill only be called whenj < nis false. Now,j < nis false at the end of every line. That's why you get\nat the end of every line.
``` for (int i = 0; i < 3; i++) { int r = rand() % 3; for (int j = 0; j < 3; j++) { int temp = mati[i][j]; mati[i][j] = mati[r][j]; mati[r][j] = temp; } } ``` Here I have a 2d array namedmatiand I want to randomize its elements but I don't know how?
It seems you mean the following ``` for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { int n = rand() % 9; int temp = mati[n / 3][n % 3]; mati[n / 3][n % 3] = mati[i][j]; mati[i][j] = temp; } } ```
I'm currently studying C and I have a question in which I have to guess what values are in the memory. When I say, for examplelong var1[1243] = {10, 1, 0, -1, -10}and define this vector, the first 5 elements of it are already defined, but the allocated bytes that represent the remaining 1238 elements, what are they set as in memory? More specifically, are they 0? Would saying, in assembly, after defining them,.zero <number of remaining bytes in vector>correct?
By having at least some elements initialized{10}C will initialize all the remaining elements in the array the same as a global variable. Either numeric zero or null pointer depending on type, and in the case of arrays of structs, all members of the struct, recursively. In C++ an empty initializer also workslong var1[1243] = {}, but that is not allowed in C.
I'm using Visual Studio in Windows to develop basic C applications. I want to compile my code for Linux, without the need to have Linux installed on my machine. Is that possible ? And how ?
You'll need to have Linux installed somewhere. If you can remote to a linux box, vm, or WSL console, from your Visual Studio machine, you can use VS 2019 to build and debug most applications in any of those environments, via theCross Platform Connection Manager. The following blog and document links are a good place to start. Targeting the Windows Subsystem for Linux from Visual StudioC++ with Visual Studio 2019 and Windows Subsystem for Linux (WSL)EA and Visual Studio’s Linux SupportUsability Improvements for CMake in Visual Studio 2019 version 16.4: Launch Target Selection and Overview Pages Similarly, Visual Studio Code has some support for this as well: Using C++ and WSL in VS Code Sincerely,
I'm getting something like this: ``` if (!file) return; for (int i = 0; i < positions.size(); ++i) positions[i] = m * positions[i]; ``` But I want this: ``` if (!file) return; for (int i = 0; i < positions.size(); ++i) positions[i] = m * positions[i]; ```
Give this command to break that code into separate lines ``` AllowShortIfStatementsOnASingleLine : Never ``` After adding this code to your.clangformatfile output look like this ``` if (!file) return; for (int i = 0; i < positions.size(); ++i) positions[i] = m * positions[i]; ``` Source
Do we also have to initialize\0(NULL) character? Code: ``` char S[N]; for (i = 0; i < N; ++i) { scanf("%c", & S[i]); //Is it a wrong way to initialize char string character by character? } for (i = 0; i < N; ++i) { printf("%d %c", i, S[i]); } ```
This should work, and you don't have to add the NUL (not NULL, it's ASCII) at the end because you're treating it as an array of N distinct characters and not as a string. If you wanted toprintfit with%sor callstrlenon it, then you'd have to add the NUL (and allocate N+1 characters for the array). You should add\nat the end of yourprintfformat string. Note that you will have to type the N characters all on one line. If you press return after the first one, for example, the linefeed will be taken as the second character.
I would like to do something like setting a macro name that activates portions of my code.... g++ -DVERBOSE=1 main.cc during the Bazel build command: bazel build //myproj:main Is it possible?
bazel build //myproj:main --cxxopt=-DVERBOSE=1 Or, use thecoptsattribute incc_*targets. https://docs.bazel.build/versions/master/user-manual.html#flag--cxxopt
Hi im trying to add a library to my C project for a class task but I cant get it to work. When I usegcc -L ../build/lib ./bigint/src -lbigintit shows the error: ``` /usr/bin/ld: ./bigint/src/ can not be found: File format not recognized /usr/bin/ld: -lbigint can not be found collect2: error: ld returned 1 exit status ``` my directories do look like this: ``` root <- here im in the terminal trying, using the command - bigint -- src --- bigint.c --- bigint.h --- bigint.h.gch --- bigint.o --- libbigint.a --- support.h --- support.g.gch -- tst - project.c - project.h ... ```
You need a seperate-Lfor each lib directory. Assuming you really do want./bigint/srcto be a lib directory: ``` gcc -L ../build/lib -L ./bigint/src <C file or object file> -lbigint ```
``` /*source: stralloc.c*/ #include <stdio.h> #include <stdlib.h> int main(void){ char *A; int max=0; //need to add error-checking printf("enter max string length: "); scanf("%d",&max); while ((getchar())!='\n'); A=(char *)malloc(max+1); //room for \0 printf("enter string: "); fgets(A,max,stdin); printf("Third char is: %c\n",*(A+2)); //printf("Third char is: %c\n",A[2])); exit(0); } ``` I got this code from my class, but there is one part I don't understand. What doeswhile ((getchar())!='\n');do in this function? Can anyone explain it to me?
``` while ((getchar())!='\n'); ``` Program execution continues at this line until it receives new line character(i.e Enter)'\n'. 'getchar()' method waits until it receives some input from keyboard. Once input is received it is compared with ('\n') if it is not a '\n' it callsgetchar()again. flowchart
This question already has answers here:Endianness -- why do chars put in an Int16 print backwards?(4 answers)Closed3 years ago. I have following code: ``` int main ( void ) { unsigned int array [] = { 298 , 0 x1A2A3A4A }; unsigned char *p = ( unsigned char *) array ; for (int i = 4; i < 8; i ++) { printf ("% hhX ", p[i]) ; } printf ("\ nThe Answer is %d or %d!\n", p[0] , p [6]) ; return EXIT_SUCCESS ; } ``` I dont understand the output: ``` 4A 3A 2A 1A The Answer is 42 or 42 ```
On a little endian system, the layout of the 8 bytearrayis ``` Position: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 Value (Hex): 2A | 01 | 00 | 00 | 4A | 3A | 2A | 1A ``` Your loop prints the last 4 bytes in the order they appear in the array. Your finalprintfprints the values at the 0 and 6 position, which are both 0x2A, or 42 in decimal.
I'm trying to compile a C function that receives an static matrix and i want to make a header file for it. How should i define it? I tried this but i'm getting conflicting types error. This is my header file nodo* construirArbol(int,int ,float **,nodo *,int); This is the "header" in the .c file nodo* construirArbol(int filas,int columnas,float matriz[][columnas],nodo *n,int iterador){ I've tried this but i don't know if its a correct solution nodo* construirArbol(int,int c,float [][c],nodo *,int);Both of two first arguments are the rows and colums of the matrix All help is welcome
You do not have to use square brackets to represent a matrix as a parameter for the function. On the other hand, when it comes to the matrix manipulations in the function definition feel free to use ones.
I'm actually working on a game using GLUT and C and I would like to display the score on my window, I'm searching for something similar to printf so I can display my text "score" and it value that can change. I've found a function name DrawBitmapText but whith that function I can only display text, I couldn't display a variable. Thanks for your help.
sprintf()will create the text you want in a buffer: ``` char buf[256]; sprintf(buf, "Score: %d", score); DrawBitmapText(..., buf); ```
Is the codeint const*const pointer1=&constantVariable;legal? If it isn't, what is the correct way of specifying it?
It's OK! Inint const*const pointer1=&constantVariable, the firstconstindicates that you couldn't change the value by *pointer1; the secondconstindicates the value of pointer itself(an address) couldn't be changed too. Actually pointer1 can point to a constant integer, even a normal variable.But it can't be set twice.
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.Closed3 years ago.Improve this question How can the code work like this? Which if-else statements are linked with each other? So why is the output like that "$$$$$"? ``` #include <stdio.h> int main() { int x = 11; int y = 9; if(x<10) if(y>10) puts("*****"); else puts("#####"); puts("$$$$$"); return 0; } ```
Save time. Use an auto formatter. Hopefully then "why is the output like that "$$$$$"?" is self apparent. ``` #include <stdio.h> int main() { int x = 11; int y = 9; if (x < 10) if (y > 10) puts("*****"); else puts("#####"); puts("$$$$$"); return 0; } ```
``` #include <stdio.h> int main() { int a = 1; int b = a || (a | a) && a++; printf("%d %d\n", a, b); return 0; } ``` when I ran this code the results were1and1. According to the C language Operator Precedence the operation&&is supposed to happen before the operation||. So shouldn't the result be21? (a = 2, b = 1)
when OR'ing expressions in C, a shortcut is taken, I.E. as soon as an expression is evaluated to TRUE, the rest of the OR'd expressions are not evaluated The first expressionaevaluates to TRUE, so all the rest of the expressions are not evaluated, soais never incremented
In the following code: ``` typedef struct { uint32_t variable_1; }struct_1; typedef struct { uint32_t variable_2; }struct_2; typedef struct { struct_1 struct_1_var; struct_2 struct_2_var; }struct_all; struct_all variable_t[10]; struct_1* struct_1_var; //how to get this to point to an array of struct_1 that's inside variable_t? ``` Basically, I want to get an struct_1[10] or struct_2[10] that that is part of variable_t[10].
You can't, because there isn't an array of eitherstruct_1s orstruct_2s invariable_tto pointto. There is an array of elements,eachof which has astruct_1and astruct_2. If you want an array of just one type of the other of the values invariable_t, you'll need to copy them out one at a time into a new array.
For example such code may be useful: ``` unsigned char ch = 0xf2; printf("%02hhx", ch); ``` However,chis promoted tointwhen passing as a parameter of variadic functionprintf. So when%hhxis used, there is type mismatch. Is any undefined behavior involved here according to C standard? What if it is C++? There are some discussionherebut no answer is given.
C11 standard says: 7.21.6.1/7hhSpecifies that a followingd,i,o,u,x, orXconversion specifier applies to a signed char or unsigned char argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to signed char or unsigned char before printing); or that a following n conversion specifier applies to a pointer to a signed char argument. So no, there is no undefined behavior. The standard is well aware that acharargument to a variadic function would be promoted toint.
I've tried to patch the libc i'm using to never call malloc hook. But this hook is actually initialized with a pointer to this function: ``` malloc_hook_ini (size_t sz, const void *caller) { __malloc_hook = NULL; ptmalloc_init (); return __libc_malloc (sz); } ``` I think this function is responsible for critical initializations in malloc, so it needs to be called at least once. For instance since the free hook is not initialized with a critical function, i can just nop the call instruction
DJ Delorieposted a patchwhich removes the hooks. It requires some porting to the current tree, though. Alternatively, you couldinterpose a different mallocwhich does not have such hooks. If you do this, glibc will use the interposed malloc, so the hooks are never called, either.
When I print a memory address withprintf %pI get address inhexdecimal- something like0x7ffee35f5498. I am wondering why theprintfreturn value is16and not the actual length of string, in this case14? ``` #include <stdio.h> int main(void) { char *s = "Hello World!"; int x; x = printf("%p\n", (void*)&s); printf("%d\n", x); return (0); } ``` output:0x7ffeea6a379016 Address has 14 char but the function returned 16. Documentation say's: printf() : It returns total number of Characters Printed, Or negative value if an output error or an encoding error. ...
You're not just printing the address but also a newline after it. On Linux / MacOS systems a newline is one character (0xA) while on Windows systems it is two characters (0xD 0xA). From your comments, you say you got 15 as your output and that you're on MacOS. So that's 14 for the printed address plus 1 for the newline which is the expected result.
When I print a memory address withprintf %pI get address inhexdecimal- something like0x7ffee35f5498. I am wondering why theprintfreturn value is16and not the actual length of string, in this case14? ``` #include <stdio.h> int main(void) { char *s = "Hello World!"; int x; x = printf("%p\n", (void*)&s); printf("%d\n", x); return (0); } ``` output:0x7ffeea6a379016 Address has 14 char but the function returned 16. Documentation say's: printf() : It returns total number of Characters Printed, Or negative value if an output error or an encoding error. ...
You're not just printing the address but also a newline after it. On Linux / MacOS systems a newline is one character (0xA) while on Windows systems it is two characters (0xD 0xA). From your comments, you say you got 15 as your output and that you're on MacOS. So that's 14 for the printed address plus 1 for the newline which is the expected result.
I want to put spaces instead of 3's and create a plus sign from 1's. Like peg solitaire board. How can I do? ``` #include <stdio.h> int main() { int board[7][7]={{3,3,1,1,1,3,3},{3,3,1,1,1,3,3},{1,1,1,1,1,1,1},{1,1,1,0,1,1,1},{1,1,1,1,1,1,1},{3,3,1,1,1,3,3},{3,3,1,1,1,3,3}}; int i,j; for ( i=0;i<7; i++) { for ( j=0; j<7; j++) { printf(" %d ",board[i][j]); } printf("\n"); } } ```
Onint board[][]it is not possible to assign '+' or '' inplace of 3 or 1 because your defined 2-D array is of type int and you want to replace it with char. Still if you perform the assignment likeboard[3][3]= '+'it will store ascii value of '+'. So either you have to create new 2-D array of type char and replace value when conditions are met. OR You just have to iterate and inplace of 3 and 1 just print '+' and '' when conditions are met.
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed3 years ago.Improve this question I'm reading a text file in C usingfgets(Array[100], 100, File);. Then I need to test if it contains a specific text such as Cow. I need to set Cow to be only the first character [C] and then write it to another file and so on. I triedstrcmp(data, "Cow") == 0but it never goes to the check. I'm new to File I/O. Could you please let me know how I would do that? Also, the file has commas in between.
If you are looking for text contains a specific string then use strstr(data,"Cow") != NULL
``` int *insertZeroPosition(int *pf,int n,int k){ int *ptr=(int *)calloc(n+1,sizeof(int)); int i; ptr[0]=k; for (i=1;i<n+1;i++,pf++){ ptr[i]=*pf; } return ptr; } ``` Why is itptr[i]=*pfinstead of*ptr[i]=*pfeven though ptr is a pointer?
The syntaxp[i]is equivalent to*((p) + (i)). The dereference is still there, even with the array-subscript syntax. C Standard, § 6.5.2.1.2: The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). You can rewrite the code to say*(ptr + i) = *pfif you want; there's no difference.
In a test exam, we were told to find the value of some expressions. All but 1 were clear, which was"20"[1]. I thought it was the 1st index of the number, so0, but testing with a computer it prints48. What exactly does that 'function' do?
It's not a function, it's just indexing an array. "20"here is a character array, and we're taking the value at index 1 - which is'0'- the character'0'. This is the same as ``` char chArr[] = "20"; // using a variable to hold the array printf ("%d", chArr[1]); // use indexing on the variable, decimal value 48 printf ("%c", chArr[1]); // same as above, will print character representation, 0 ``` The decimal value of'0'is48, according toASCII encoding, the most common encoding around these days.
This question already has answers here:How do function pointers in C work?(12 answers)Closed3 years ago. Up to now I use#defineto map functions. Exemple: if I have 2 physical uarts, to mapSendDebugStringto the matching physical uart I use: ``` #define SendDebugString(s) Uart1_SendDebugString(s) // map to uart 1 ``` or ``` #define SendDebugString(s) Uart2_SendDebugString(s) // map to uart 2 ``` How can I do the same using function pointers instead of#define?
Let say the function signature isint sendString(char* s). You can then write: ``` // declare SendDebugString as a pointer to a function // accepting a string as argument and returning an int int (*SendDebugString)(char *s); // assign a function to SendDebugString SendDebugString = Uart1_SendDebugString; // call the function SendDebugString("hello world!"); ```
In a test exam, we were told to find the value of some expressions. All but 1 were clear, which was"20"[1]. I thought it was the 1st index of the number, so0, but testing with a computer it prints48. What exactly does that 'function' do?
It's not a function, it's just indexing an array. "20"here is a character array, and we're taking the value at index 1 - which is'0'- the character'0'. This is the same as ``` char chArr[] = "20"; // using a variable to hold the array printf ("%d", chArr[1]); // use indexing on the variable, decimal value 48 printf ("%c", chArr[1]); // same as above, will print character representation, 0 ``` The decimal value of'0'is48, according toASCII encoding, the most common encoding around these days.
This question already has answers here:How do function pointers in C work?(12 answers)Closed3 years ago. Up to now I use#defineto map functions. Exemple: if I have 2 physical uarts, to mapSendDebugStringto the matching physical uart I use: ``` #define SendDebugString(s) Uart1_SendDebugString(s) // map to uart 1 ``` or ``` #define SendDebugString(s) Uart2_SendDebugString(s) // map to uart 2 ``` How can I do the same using function pointers instead of#define?
Let say the function signature isint sendString(char* s). You can then write: ``` // declare SendDebugString as a pointer to a function // accepting a string as argument and returning an int int (*SendDebugString)(char *s); // assign a function to SendDebugString SendDebugString = Uart1_SendDebugString; // call the function SendDebugString("hello world!"); ```
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.Closed3 years ago.Improve this question Consider the c snippet: ``` #include<stdlib.h> int main() { printf(2+"Roomy"); return 0; } ``` Output given is skipping 1st 2 characters of the string.i.e.,omy So can anyone explain what is going on with the addition?
printf expects a pointer to char. "+2" means shift pointer beyond 2 positions.
When I try to execute this code with size of stringbas size 5, it prints out mangoapple Despite not printing stringa, the output still is mangoapple But if I increase the size of the stringbto 6, it only prints mango ``` int i=0; char a[5]="apple"; char b[5]="mango"; pf("\n%s",b); ```
You gotbuffer overflow. The size of"mango"is 6 char and when you declareb[5]there is no room for null terminator. And when there is no null terminator,printfwith%swill try to print out whatever remain in the stack, in this case happen to be"mangoapple". This is undefined behavior since you don't know really what is there in the stack. Best practice, don't forget the room for null terminator when assigning a string.
This may be a stupid question but I'm confusing myself anyway, when we call a function and that function calls another function does the program return to the parent function to complete any other statements? example: ``` function parent(){ childFunction(); println("run the jewels"); } ``` It's just a generic question but I'm prepared for a slating so have at it...
It prints "run the jewels" only if childFunction() doesn't crash/exit/jump
I am using IAR compiler, and have some Compile switches in the code. When I switch between 2 different #defines does the other code which was not selected still be present in the final Hex file generated?
The preprocessor just does dumb cut'n'paste and it runs before the compiler. Any code (text, really) that it excludes will not be part of the source the compiler sees, so obviously it won't make it into the final object file/library/executable either. In short, the answer to your question is "no". But, if you don't believe me, just check the final generated file.
I'm a little bit confused how does the function pause() works in the sense of calling order. For example: ``` int main(){ printf("Start\n"); pause(); printf("Finish\n"); } ``` I was expecting to get output "Start" before pause, but program just immediately pauses instead. Please, explain why. Thanks in advance.
Your terminal emulator doesn't apparently flush standard output on every newline. You can manually flush it withfflush(stdout)if you want to see the output immediately: ``` int main(){ printf("Start\n"); fflush(stdout); pause(); printf("Finish\n"); } ```
I have been experimenting withgetchar(),putchar()and have been trying to useEOF. Below is the snippet of code I have been experimenting with. ``` #include <stdio.h> int main(void) { int c; c = getchar(); while(c != EOF) { putchar(c); printf("\n"); printf("%d\n", EOF); c = getchar(); } return 0; } ``` Input: -aExpected output: -a//Due to putchar()-1//Value of EOF//Now the cursor should come in next line and wait for next character.Output getting in real time: -a-1-1//Cursor waiting for next character. I am not able to comprehend the reason why the output is showing-1two times.
Your code comment says ``` //Now the cursor should come in next line and wait for next character. ``` But the second loopdoesn't wait. It reads the newline that was already entered, and this is shown by the extra blank line in the output.
I am working with C API of CPLEX. I have a bunch of optional binary variables (which can constitute any percentage of the total number of variables). I tried solving my BIP model both ways: (i) fixing them to 0 and (ii) not having these variables altogether in the model. On average I could not find any significant difference in the computational times. I want to know if there is something wrong or CPLEX works that way. I expected that with fewer variables, the model should have run much faster in the second case.
This is expected behavior. Fixed variables are removed in a first presolve path which is usually very fast. Then CPLEX internally works only on the presolved model, i.e., the same model as the one that did not have those variables in the first place.
This question already has answers here:How to prevent an infinite loop with scanf failure(2 answers)Closed3 years ago. When I try to enter a character (letters in particular), the code results in an infinite loop. May I know why is that and are there any remedies without adding any new libraries? PS. I've only been coding for a month or so. ``` #include <stdio.h> int main () { int n; do { printf("Enter N: "); scanf("%d", &n); } while (n != 0); } ```
Ifscanffails to parse the input, it will leave it in the input buffer. The next iterationscanfwill read the exact same input and again fail. A common way to handle invalid input is to read a whole line into a buffer using e.g.fgetsand then attempt to parse it usingsscanf, remembering to check what itreturns.
I'm learning about C socket programming and I came across this piece of code in a online tutorial Server.c: ``` //some server code up here recv(sock_fd, buf, 2048, 0); //some server code below ``` Client.c: ``` //some client code up here send(cl_sock_fd, buf, 2048, 0); //some client code below ``` Will the server receive all 2048 bytes in a single recv call or can the send be be broken up into multiple receive calls?
TCP is a streaming protocol, with no message boundaries of packets. A singlesendmight need multiplerecvcalls, or multiplesendcalls could be combined into a singlerecvcall. You need to callrecvin a loop until all data have been received.
This question already has answers here:Variable sized padding in printf(5 answers)Closed3 years ago. I need to add 0's to some values. For example if the number is 14, i want to print out 00014. but I can't just use %05d because the number of padding I want is stored in a variable. If the variable is equal to 6, I want to print 000014. If it is equal to 3, I want to print out 014 and so on.. Any quick way to do it? ``` int length = 5; int someValue = 14; printf("%0%d%d",length,someValue); ``` This also doesn't work. Thank you.
You can use an asterisk*in the format to tellprintfto get the field width from an argument: ``` printf("%0*d", length, someValue); ``` You can also use it for precision. See e.g.thisprintfreferencefor details.
I'm puzzled over this function. ``` int i; for(i = 1; i<10; i++){ int arr[i]; printf("%d\n",sizeof(arr)); } return 0; ``` How can the space grow in a bounded (by ESP) stack memory? Is there a sort of compilation trick? EDIT for explanation: Shouldn't the stack be something like that? ``` 0 ---> val of i uninitialized -4 ---> arr[0] uninitialized ``` and after the first loop ``` 0 ---> val of i uninitialized -4 ---> arr[1] uninitialized -8 ---> arr[0] uninitialized ``` I'm tempted to say: is ESP moving below each iteration of the loop?
How can the space grow in a bounded size stack memory? You refer to the space ofchar arr- its space does not grow. It's a local variable inside the scope of theforloop. So everytime the loop has a newiit's a brand newchar arr.
I am trying to implement a server-client communication. I am executing a sql statement (SQLITE3) ``` "UPDATE users SET status=1 WHERE username='%s' AND password='%s';",user,pass); ``` usingqlite3_prepare_v2 I know how to write to client, but I don't know how to CHECK if the 'status' has been set to 1 where username is user and password is pass AND how to send a reply to client: "Yes, the 'status' has been set to 1, you are now logged in"
int sqlite3_changes(sqlite3*);returns the number of rows modified, inserted or deleted by the most recently completed INSERT, UPDATE or DELETE statement. After your query, check if one row was modified. Source:https://www.sqlite.org/c3ref/changes.html
I want to solve the following problem: assume that we have twoint64_tnumbersaandb. And we want to finda * bif the product fitsint64_tdata type and lowest 64 bits of multiplication result in other way. How can I resolve this ? I know the solution of the similar problem foruint64_tdata type using long multiplication, can we apply it here ?
By a sheer act of computational devilry,int64_tanduint64_tmultiplication have the same bit pattern. Therefore you can compute1ULL * a * band assign that to auint64_t: the coefficient is there to force type conversion ofaandb. Note that if a compiler supportsint64_tthen it is required to supportuint64_tas well. Then it's a matter of comparing the size of this product cf.aandbto see if it will fit into anint64_t. Wrap-around will have taken place if the product is smaller (in the unsigned sense) than eitheraandb.
This question already has answers here:Comparison operation on unsigned and signed integers(7 answers)Closed3 years ago. I want to know that why it only executes the else statement The code is Given below: ``` #include<stdio.h> int main() { unsigned int a = 100; int b = -100; if(a > b) { print("Obviously 100 is Bigger than -100!\n"); } else print("Something Unexpected has Happened\n"); } ```
This statement ``` if(a>b) ``` involves operation (comparison) between a signed and an unsigned integer, and as per the promotion rules, the signed integer will be promoted to unsigned integer and produce a huge unsigned value: for example, in an environment with 32-bit integer, the value would be 4294967196 (232- 100). Thereby, the condition will look like ``` if (100 > 4294967196) ``` and will evaluate to false, making sure the code in theelseblock is executed.
When I try to execute sql statement in Firebird C Api, I can only use char* sql statements and I can not execute wide characters. How can I use execute() or prepare() with wide characters? ``` const char* updstr = "UPDATE Tablo SET TABLOADI='Türkçe karakterler ğüşıç'"; //const wchar_t* updstr = L"UPDATE Tablo SET TABLOADI='Türkçe karakterler ğüşıç'"; // attach employee db att = prov->attachDatabase(&status, "employee", 0, NULL); // start transaction tra = att->startTransaction(&status, 0, NULL); // prepare statement stmt = att->prepare(&status, tra, 0, updstr, SAMPLES_DIALECT, 0); ```
Problem solved. When I look at my data in database with Flamerobin, connection and database collation is not set to Utf8, so I saw corrupted characters. I set everywhere to utf8, and it works.
The following small program is calling a C lib: ``` from ctypes import * ini_file="/home/pi/pyYASDI/yasdi.ini" yasdiMaster_lib="/usr/local/lib/libyasdimaster.so" masterlib = cdll.LoadLibrary(yasdiMaster_lib) DriverCount=c_ulong(10) pDriverCount=byref(DriverCount) print("Init: ",masterlib.yasdiMasterInitialize(ini_file,pDriverCount)) ``` In Python 2.7 the C lib call is working fine, in Python 3.5 it's returning a different value. Unfortunately I am unable to debug the C lib. What is changing from 2.7 to 3.5 in that small code? Will there be a change handing over the arguments to the C lib? The arguments of theyasdiMasterInitializecall arechar * cIniFileName, DWORD * pDriverCount).
Thanks for the hint! It is the Unicode change of Python 3.5! I changed only one line now: ``` ini_file="/home/pi/pyYASDI/yasdi.ini".encode('ascii') ```
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.Closed3 years ago.Improve this question our teacher told us that we can make a dynamic array in C (not in C++) using the code below : ``` int main() { int n; scanf("%d" , &n); float* x =new float[n]; return 0; } ```
Either your teacher is incorrect or you misunderstood - that is not valid C code. As of the 1999 version of C, you can create avariable-length arrayas such: ``` int n; scanf( “%d”, &n ); float x[n]; ``` or you can dynamically allocate memory usingmalloc,calloc, orrealloc: ``` int n; scanf( “%d”, &n); float *x = malloc( n * sizeof *x ); ``` but there is nonewoperator in C.
This question already has answers here:Writing to pointer out of bounds after malloc() not causing error(7 answers)Undefined, unspecified and implementation-defined behavior(9 answers)Closed3 years ago. I am performing sprintf on a char array of size 1 and the code works fine. i.e strlen returns 1 even though it may not be null terminated. To my understanding sprintf will do null termination, however in this case it does not have enough space. Can someone explain the reason it works? ``` #include <stdio.h> #include <string.h> #define STATUS "1" int main(void){ char *data = malloc(1); sprintf(data, "%s", STATUS); printf(">%s<\n", data); printf(">%d<\n", strlen(data)); } ``` Output ``` >1< >1< ```
The program has undefined behavior. It works because in general malloc allocates memory chunks multiple by the paragraph size equal to 16 or some other implementation defined value.
Can you please tell me why is the output not same, ``` #include <stdio.h> int main(int ac, char **av, char **env) { printf("Address of the array of environment variables: %p\n", (void *)env); printf("Address of the first environment variable: %p\n", (void *)(env[0])); return 0; } ``` Is not env and env[0] pointing to the same address. Output: ``` Address of the array of environment variables: 0x7ffcd47f6288 Address of the first environment variable: 0x7ffcd47f7312 ```
They are not the same thing.envis the array of pointers to strings, which exists somewhere in memory.env[0]is the address of the first string, just likeenv[1]is the address of the second string, which is different to the address of the array where those addresses are stored.
I have created a pointer variable to point to an active variable. I have two variables, I want to toggle the active variable between these two variables. Managed to do this inside the main. Now I want to extend this to another function ``` int main() { int x = 0; int y = 0; int *active=&y; if(active == &x) active = &y; else active = &x; } ``` I dont want to swap the values of the variables, x, y. x, y are coordinates of a cartesian plane.
You can pass the reference of the pointer variable to the function, and in the formal parameter list create a pointer which holds the memory address of the pointer variable ``` void flip(int **act, int *x, int *y){ if(*act == x){ *act = y; }else{ *act = x; } } int main() { int x = 0; int y = 0; int *active=&y; flip(&active, &x, &y); } ```
What is wrong with the following code? It generates a Segmentation fault. ``` #include <stdio.h> #include <stdlib.h> typedef struct{ int ** access; }item; int main() { int access[5][5]; for(int i = 0; i < 5; i++){ for(int j = 0; j<5; j++){ access[i][j] = 5; } } item * p = malloc(sizeof(item)); p->access = access; for(int i = 0; i < 5; i++){ for(int j = 0; j<5; j++){ printf("%d",p->access[i][j]); } } return 0; } ``` I want to create a struct that contains the value of a double array created in the main function. What is wrong with it?
You can have array of pointer in your struct like int *[5]. But you have to assign address of each row in 2D array to struct data member. Also free your memory allocated in malloc.
Lets say i want to close program after x seconds (not #define) My program is running a recursive function (recursive tree) What can I do to make the running time of the program available from everywhere no matter the recursion depth, my first idea was to use a pointer as function parameter but I got confused real fast. Thanks for you help.
Just store the start time in a global variable, and find the difference between the current time and that time in your recursive function. ``` #include <time.h> static time_t start_time; static void f(void) { // ... time_t current_time = time(NULL); int diff = current_time - start_time; // ... } int main(void) { start_time = time(NULL); f(); return 0; } ``` You could pass the start time as a parameter, but there's no point to passing the same value to each recursive call. It just eats up your available stack space for nothing.
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.Closed3 years ago.Improve this question This is the code: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int appar(char c[], char x); int main() { char c[] = "hello everyone!"; int b = appar(c, 'h'); printf("nbr of h is %d ", b); return 0; } int appar(char c[], char x) { int i = 0, cmpt = 0; int q = strlen(c); for (i; i < q; i++) { if (c[i] == 'x') cmpt++; } return cmpt; } ``` I run and compile the program, but I receive "nbr of h is 0". What's the wrong in this code?
Changec[i]=='x'toc[i]==x You want to compare with the variable x, not the character constant 'x'
I need to find all suffix starting with a character X. For example,for int suffix (char str [], char c)when the word isababcdand the letterbit should return: ``` babcd bcd ``` and the number 2. This is my code: ``` #include <stdio.h> #include <string.h> int main() { char c; char str[128]; int counter=0; printf ("Please enter charachter and a string \n"); scanf("%c %s",&c,str); counter = my_suffix(str,c); printf("The string has %d suffix \n",counter); return 0; } int my_suffix(char str[],char c) { int counter = 0; for (int i=0; i < strlen(str); i++) { if (str[i] == c) { puts(str+i); counter++; } } return counter; } ``` I couldn't find why it's not running, Thanks!
Your code is fine you should just written following method aboveint main() ``` int my_suffix(char str[],char c){...} ```
I'd like to use a fewforloops in C and use common index for these. I want to use pointer, because I will be able to free it later.I thought about something like: ``` uint8_t *p = malloc(sizeof(uint8_t)); for (*p = 0; *p < 255; *p++) { // Instructions... } // A few loops... free(p); ``` But this code doesn't work as I want. How can I fix it? PS I'm a beginner in C's pointers.
By this line: ``` uint8_t *p = malloc(sizeof(uint8_t)); ``` You're allocating memory that is suitable to hold ONEuint8_t. You shouldn't touch any other addresses after p because you didn't allocate them. You may need to do the following: ``` uint8_t *p = malloc(255 * sizeof(uint8_t)); ``` The previous line allocates memory that can hold 255uint8_tinstead of just one. That way, you can access addresses fromptop + 254.
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.Closed3 years ago.Improve this question our teacher told us that we can make a dynamic array in C (not in C++) using the code below : ``` int main() { int n; scanf("%d" , &n); float* x =new float[n]; return 0; } ```
Either your teacher is incorrect or you misunderstood - that is not valid C code. As of the 1999 version of C, you can create avariable-length arrayas such: ``` int n; scanf( “%d”, &n ); float x[n]; ``` or you can dynamically allocate memory usingmalloc,calloc, orrealloc: ``` int n; scanf( “%d”, &n); float *x = malloc( n * sizeof *x ); ``` but there is nonewoperator in C.