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; pr...
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'...
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 typ...
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...
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 th...
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, ...
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); ...
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...
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...
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]...
``` #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); strc...
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) --> 00000010000000...
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); ...
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("ASn1Ha...
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, tha...
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, tha...
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 t...
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-...
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. I...
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" ``` O...
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 d...
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 op...
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...
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 signi...
``` 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, restar...
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 `...
``` 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 y...
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 opti...
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 adva...
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(pat...
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); pr...
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 celf...
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 inconvenie...
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; ...
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 s...
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 mor...
``` #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 ...
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); ...
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 ...
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); ...
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"...
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:1...
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', '...
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 resul...
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: ``` ...
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', '...
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 resul...
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: ``` ...
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 fa...
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 o...
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 h...
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 thi...
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 storag...
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 *myN...
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...
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 thesi...
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, GCl...
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 se...
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[...
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 ...
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 t...
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 statu...
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 i...
``` 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 ++) { pr...
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 0...
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* construirArbo...
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...
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 ...
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? ...
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 ...
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 som...
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 f...
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 responsibl...
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...
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 new...
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...
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 new...
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++...
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 valu...
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 f...
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 ...
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 `...
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...
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 ...
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 `...
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...
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"); r...
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...
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 gener...
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 b...
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 i...
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); ...
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 dif...
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 ...
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 ```...
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...
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 --...
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...
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, ca...
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 ...
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) { pri...
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- ...
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...
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...
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...
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 = ma...
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 ...
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 an...
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 ...
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; ...
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; } } 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 fa...
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 ma...
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...
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=...
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 wor...
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 alloca...
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...
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 = ma...