question
stringlengths
25
894
answer
stringlengths
4
863
Why doesn't gcc give any warnings about this code? ``` #include <stdio.h> void printDigits(int *arr, int arrsize); int main() { int number[] = { 1, 7, 8, 3, 6, 5, 4, 2 }; size_t arraysize = (sizeof(number) / sizeof(number[0])); printDigits(number, arraysize); return 0; } void printDigits(int *arr, int arrsize) { int i; for (i=0; i<arrsize, i++;) { printf("%d ", arr[i]); } } ``` Specifically about the for loop in printDigits function. It's:for(i=0; i<arrsize, i++;)while it really should befor(i=0; i<arrsize; i++) Gcc didn't give me any warnings and it took me a while to figure out why doesn't the array print out.
There is a warning.i<arrsizeis computed but then discarded, so gcc warns: ``` warning: left-hand operand of comma expression has no effect [-Wunused-value] ``` (Which is enabled by-Wall)
The following code doesn't run. Can I say increment/decrement operators won't work on functions with return type int? ``` int main() { char x[] = {"test"}; int size = strlen(x); //works :) int size2 = --strlen(x); //doesn't work return 0; } ``` Error is: ``` error: lvalue required as decrement operand 9 | int size2 = --strlen(x); //doesn't work | ^~ ```
The prefix decrement operator--decrements the object which is the subject of the operator. The return value of a function is just that, a value and not an object. It's the same as if you tried to do--4. If you want to assign 1 less than the length ofxtosize2, you would do it like this: ``` int size2 = strlen(x) - 1; ```
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.Closed2 years ago.Improve this question I also noticed that multiples of 0.0625 such as 1.25 keep giving zero but I was unable to find an explanation
as per CostantinoGrana "Do you know how IEEE 754 works? The numbers which you say "give 0" are multiples of a not too negative negative power of 2. So when you store them in little endian, the 32 less significant bits, that are all 0, are the first thing you find in memory as int. Your int is 32 bits wide, thus 0."
In SDL, when I destroy a window withSDL_DestroyWindow, do I also need to callSDL_FreeSurfaceto release the surface that is associated with that window? ``` SDL_Window *window = SDL_CreateWindow(/*...*/); SDL_Surface *wsurface = SDL_GetWindowSurface(window); /*...*/ SDL_FreeSurface(wsurface); /* <- do I also need this line? */ SDL_DestroyWindow(window); ``` It isn't clear to me if the surface needs to be manually released or if it gets released automatically when I destroy the window.
It gets released automatically. Here is the relevantdocumentation: A new surface will be created with the optimal format for the window, if necessary. This surface will be freed when the window is destroyed.Do not free this surface.
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.Closed2 years ago.Improve this question ``` main () { int a,b,toplam; float ort; printif("iki sayi girin :"); scanf("%d,%d",%a,%b); toplam=a+b; ort=toplam/2; printif("Ortalama= %f olarak hesaplandı.",ort); } ``` error: expected expression before '%' token scanf("%d,%d",%a,%b); What was my mistake?
Replacescanf("%d,%d",%a,%b);withscanf("%d,%d",&a,&b); Check thisanswerfor more information.
I have 3 different C files that are in the same directory which I want to compile separately from one another using a Makefile. This is my Makefile: ``` program1: program1.o gcc program1.o -o program1 program1.o: program1.c gcc -c program1.c program2: program2.o gcc program2.o -o program2 program2.o: program2.c gcc -c program2.c program3: program3.o gcc program3.o -o program3 program3.o: program3.c gcc -c program3.c clean: rm program1.o program1 program2.o program2 program3.o program3 ``` When I run the Makefile it only makes the file for program1 and this is the output I get when I run the Makefile: ``` make: 'program1' is up to date. ```
makebuilds the first target given no other arguments, Pass an argument to build a particular target, or add a first line making the executables a dependency of a rule to build them all by default. ``` all: program1 program2 program3 ```
Is there any specific data type for Microsoft's compiler for representing floating data points. I seem to find only float, double and long double
No. At time of writing Visual C++ v16 a.k.a Visual C++ 2019, does not support any floating point data types other than those defined in the C and C++ standards. Moreover unlike GCC on Intel x86/x64 targets,doubleandlong doublehave teh same 64-bit representation. This is documented athttps://learn.microsoft.com/en-us/cpp/cpp/fundamental-types-cpp?view=msvc-160 The Intel x86/x64 FPU supports an 80 bit data type in hardware, but it is not directly supported by a data type. GCC on the other has a number of extended typeshttps://gcc.gnu.org/onlinedocs/gcc/Floating-Types.htmlincluding a__float80to match the hardware and a__float128.long doubleis not the same asdoubleon GCC.
Variableiis becoming8at the first entry in loop. Then how the conditioni <= 2satisfied next time? ``` #include <stdio.h> int main() { int i; for (i = 0; i <= 2; i++) { int i = 8; printf("%d", i); } printf("%d", i); return 0; } ```
It prints8three times from the loop with i = 0, i = 1 and i = 2. ``` for(i=0;i<=2;i++) { int i=8; printf("%d",i); } ``` The second variablei(the one declared inside the body of the loop) will not affect the firsti(the one declared outside the loop), because it is declared in a different scope i.e., inside the loop. Final the last 3 comes from because the inner mostiwill be increment on last time before exit the loop. So for: ``` printf("%d",i); ``` the variableiwill take the value 3.
I know as the name says, it triggers when there are missing field initializers. But it didn't trigger any warnings for the following code. ``` #include <stdio.h> struct test { int a, b, c; }; void func(struct test test) { printf("%d, %d, %d\n", test.a, test.b, test.c); } int main() { func((struct test) {12, .a = 1, 12, .a = 13, .b = 13}); return 0; } ``` It compiles with no warnings when I rungcc test.c -Wmissing-field-initializers. And it prints out13, 13, 0. Is this the default behaviour of-Wmissing-field-initializers?
From thedocumentation: This optiondoes not warn about designated initializers try ``` #include <stdio.h> struct test { int a, b, c; }; void func(struct test test) { printf("%d, %d, %d\n", test.a, test.b, test.c); } int main() { func((struct test) {1, 2}); // Now you get a warning return 0; } ```
I wonder where is the reference count stored? As the type is defined as: ``` typedef char GRefString; ``` And all theg_ref_string*…()functions are returning simplygchar *instead of a structure, which could hold the reference count. Is it the trick ofsdslibrary, to hold a metadata header structure right before thechar *pointed memory? I'm afraid that such implementation can backfire at some point, am I right? I.e.: what problems can arise when using such pre-header equipped strings?
The reference counting data is stored before the string. Following the source code, you'll end up ing_rc_box_alloc_full()that has the following relevant line: ``` real_size = private_size + block_size; ``` block_sizeis what you want to allocate in the heap (in theGRefStringcase, the length of the string plus 1) andprivate_sizeissizeof(GArcBox), i.e. the struct containing the refcounting data.
I use GstDateTime API to append time to a file name. To convert time to a string, here is only gst_date_time_to_iso8601_string function that return string with time offset included: ``` 2021-01-23T23:30:59+0100 ``` I used this part of code to strip out time offset from time string: ``` g_autoptr (GstDateTime) date_time = NULL; g_autofree gchar *time = NULL; char *end; date_time = gst_date_time_new_now_local_time (); g_assert (date_time); time = gst_date_time_to_iso8601_string (date_time); /* strip out time offset from time string */ end = strrchr (time, '+'); if (end != NULL) { *end = '\0'; } ``` Is there a more elegant way to do this? Thanks
You can usegst_date_time_to_g_date_time()to get aGDateTimewhich will be much easier to work with. In your case, you can then useg_date_time_format(gdatetime, "%F");to only print out the date in the format you want.
I'm probably just stupid: ``` fileref_t *fref; while (gli_filereflist != NULL) { fref = gli_filereflist; if (fref != NULL) { glk_fileref_destroy(fref); <-------- Use of memory after it is freed fref = NULL; } } ``` This is after I added the NULL check and explicitly set fref to NULL after free(). Xcode 12.3. Original codehere. If this is a false positive, is there a way to silence it? EDIT: gli_filereflist is a linked list, which will point to the next item in the list when the first one is destroyed.
This worked: ``` while (gli_filereflist) { fref = gli_filereflist; gli_filereflist = gli_filereflist->next; glk_fileref_destroy(fref); } ```
I have a string of 200 characters( all of the characters are either 0 or 1) in input. Need a way to convert the characters tointformat and store them in an array or variable. Example:"00101110010..." -> 00101110010... the code snippet below only works for <=20 character string. ``` scanf("%u", &digit_num); //number of digits in input number/string unsigned input_binary[digit_num]; //where the integers will be stored as individual digit unsigned long long temp; //temporary storage char crc[digit_num+1], *ptr=NULL; scanf(" %s", crc); temp=strtoull(crc,&ptr,10); for (unsigned j = 0; j < digit_num; j++) { input_binary[digit_num-j-1]=temp%10; temp/=10; } ```
for (unsigned j = 0; j < digit_num; j++) { input_binary[j]=crc[j]-48; } ASCII of '0' is 48. char('3') - 48 = int(3)
I try to create message queue on linux subsystem in Windows 10. When I try to create message queue using this function: ``` queueId = msgget(*key, IPC_CREAT | IPC_EXCL | 0660); if (queueId == -1) { if (errno == EEXIST) { queueId = msgget(*key, IPC_CREAT | 0660); printf("Messege queue already exists, access acquired\n"); return; } else { printf("Couldn't create message queue. Process ended with error: %d\n", errno); exit(EXIT_FAILURE); } } else { printf("Message queue has been created with id: %d\n", queueId); } ``` I receive an error number 38 which is ENAMETOOLONG. What can I do in this case?
According tothis github issue, WSL does not support SysV message queues. You'll need to switch to WSL2, a Linux instance running in a proper VM, or find a different approach.
I have a struct that contains a field that is an array of 7 cells and I want to define the values of the cells quickly and easily. Is there a way to easily and quickly declare and define an array such as with this manner ? ``` struct my_struct { uint8_t array[7]; } struct my_struct var = {0}; memcpy(var.array, (uint8_t){0,1,2,3,4,5,6}, 7); ``` Or this way ? ``` struct my_struct { uint8_t array[7]; } struct my_struct var = {0}; var.array = (uint8_t)[]{0,1,2,3,4,5,6}; ``` Or I must do this way ? ``` struct my_struct { uint8_t array[7]; } struct my_struct var = {0}; var.array[0] = 0; var.array[1] = 1; var.array[2] = 2; var.array[3] = 3; var.array[4] = 4; var.array[5] = 5; var.array[6] = 6; ``` Thank you ;)
Array and struct initializers can be nested: ``` struct my_struct var = { {0,1,2,3,4,5,6} }; ```
Very basic question here. I am just starting out with C coding using Csound. I am trying to invoke the compiler via instructions from a tutorial book. It says open console window and type this command "cc mysource.c" This is seemingly meant to invoke the compiler but I get this error message ``` C:\Program Files\Csound6_x64\bin>cc mysource.c 'cc' is not recognized as an internal or external command, operable program or batch file. ``` Do I need to download any software to get this to work? Thanks!
cc was a compiler for Unix. It doesn't come with Windows, and you probably want to use gcc instead because it is used much more. You must set up MinGW and add it to PATH. Following this guide will help: youtube.com/watch?v=sXW2VLrQ3Bs You can then compile C usinggcc mysource.c
test.c ``` #include<limits.h> int main() { int a=INT_MAX-1; if(a+100<a) { printf("overflow\n"); return 1; } printf("%i\n",a+100); return 0; } ``` on running this code in GCC compiler using optimisation levels during compilation,why do I get different outputs? ON USINGgcc test.cTHE OUTPUT ISoverflow but on usinggcc -o2 test.cthe output is-2147483550 Can someone please explain why is this happening and I want the compiler to detect the overflow in all cases,what changes should I make in the code
One way to detect it is by compiling with-fsanitize=undefined On your code: ``` $ gcc -Wstrict-overflow k.c -fsanitize=undefined $ ./a.out k.c:6:9: runtime error: signed integer overflow: 2147483646 + 100 cannot be represented in type 'int' overflow ```
I have a small work environment related doubt. I am analyzing a binary in LLDB and sometimes, I need to make some changes in the code and re-compile it. And then re-source the new binary into LLDB for further analysis. Currently, I am doing this Inside LLDB, useshell <shell-command>to compile the code.Usefile <binary>to reload the binary. But in this way, I am losing the breakpoints. So, is there any way I can save breakpoints?
Couple of things. First off, if you are recompiling the binary at the same path you used for your current lldb target, then you don't need to make a new target. lldb will notice the file has changed when you dorunread in the new binary & debug information, reset the breakpoints, etc. But if there are other reasons why you need to make a new target, lldb hasbreakpoint writeandbreakpoint readcommands that allow you to serialize the breakpoints to a file and then read them back into a new target.
I am using Ubuntu in Raspberry Pi 4. I understand that there is an option called -marm in gcc. However, using the option to compile results in an error. gcc error unrecognized command line option '-marm' The development environment was installed through build-essential, and I wonder if additional settings are needed.
You get this error because there is no-marmoption in gcc. There is an-marchoption (arch-> 'architecture' |https://wiki.gentoo.org/wiki/GCC_optimization#-march) and an-moption (https://gcc.gnu.org/onlinedocs/gcc/GNU_002fLinux-Options.html) . As RPi is based on an ARM the gcc has the following options :https://gcc.gnu.org/onlinedocs/gcc/ARM-Options.html#ARM-Options(https://gcc.gnu.org/onlinedocs/gcc/Submodel-Options.html#Submodel-Options3.19 Machine-Dependent Options)
My program seems to be getting stuck in the do while loop. I want it to re-prompt the user if they enter a digit that is not zero or one
What ifx == 0?x != 1will be true, and the whole condition will be true. What ifx == 1?x != 0will be true, and the whole condition will be true. What ifx == 2?x != 0will be true, and the whole condition will be true. So, no matter what, your condition will be true, and you will continue looping. You want the following to be true: ``` (x == 0 || x == 1) && (y == 0 || y == 1) ``` So you want to loop while it's false. ``` do { } while (!((x == 0 || x == 1) && (y == 0 || y == 1))); ``` !(P && Q)is equivalent to!P || !Q, and!(P || Q)is equivalent to!P && !Q This means the following are equivalent to the above: ``` do { } while (!(x == 0 || x == 1) || !(y == 0 || y == 1)); do { } while ((x != 0 && x != 1) || (y != 0 && y != 1)); ```
I am new to C language but I useGitpodfor other languages. I would like to know how to run this simple "hello world" main.c program from the Gitpod interface step by step? ``` #include <studio.h> void main(){ printf("hello") } ``` Many thanks !
After fixing the errors you can compile the code withgcc main.cand run the binarya.out. Errors as already mentioned: studio.h->stdio.h...hello")->...hello");
My program seems to be getting stuck in the do while loop. I want it to re-prompt the user if they enter a digit that is not zero or one
What ifx == 0?x != 1will be true, and the whole condition will be true. What ifx == 1?x != 0will be true, and the whole condition will be true. What ifx == 2?x != 0will be true, and the whole condition will be true. So, no matter what, your condition will be true, and you will continue looping. You want the following to be true: ``` (x == 0 || x == 1) && (y == 0 || y == 1) ``` So you want to loop while it's false. ``` do { } while (!((x == 0 || x == 1) && (y == 0 || y == 1))); ``` !(P && Q)is equivalent to!P || !Q, and!(P || Q)is equivalent to!P && !Q This means the following are equivalent to the above: ``` do { } while (!(x == 0 || x == 1) || !(y == 0 || y == 1)); do { } while ((x != 0 && x != 1) || (y != 0 && y != 1)); ```
I am new to C language but I useGitpodfor other languages. I would like to know how to run this simple "hello world" main.c program from the Gitpod interface step by step? ``` #include <studio.h> void main(){ printf("hello") } ``` Many thanks !
After fixing the errors you can compile the code withgcc main.cand run the binarya.out. Errors as already mentioned: studio.h->stdio.h...hello")->...hello");
Is there a way so simplify the following expression inC? ``` result = (constant & value) ^ value; ``` The use case being: ``` #define ALL_SENSORS = (BIT(0) + BIT(1) + BIT(2) + BIT(19)) # = 524295 static int get_invalid_sensors(int sensor_mask) { return (ALL_SENSORS & sensor_mask) ^ sensor_mask; } ``` Is it possible so simplify the binary operations into one, so I do not need to invokesensor_masktwo times?
How about(~ALL_SENSORS & sensor_mask)?
I have a code snippet where a do while statement is inside switch condition of case0, by default the case value is case1 but it seems executing case0. The output of the program print is 6. How is this possible, can someone explain the flow of code here. Thanks in advance for your answers. ``` int main() { int a = 1, t =0,n=2; switch(a) { case 0: do { t++; case 4:t++; case 3:t++; case 2:t++; case 1:t++; }while(--n>0); printf("%d",t); } return(0); } ```
Since a is 1 in the beginning, case 1 will be executed. Then the loop condition is satisfied, thus it will loop again and executet++;and all other cases until it tests the loop condition again and breaks the loop. To get out of the switch, use the break command before every case.
How do I set the first (least significant) eight bits of any integer type to all zeroes? Essentially do a bitwise AND of any integer type with0x00. What I need is a generic solution that works on any integer size, but not have to create a mask setting all the higher bits to1. In other words: ``` 0xffff & 0x00 = 0xff00 0xaabbccddeeffffff & 0x00 = 0xaabbccddeeffff00 ```
With bit shifts: ``` any_unsigned_integer = any_unsigned_integer >> 8 << 8; ```
I have a small project in C language and I want to implement the program, the program cuts off the WiFi network
You can for example disconnect through a terminal command. e.g. in Windows OS ``` system("netsh wlan disconnect"); ``` example.c ``` #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(void) { system("netsh wlan disconnect"); system("echo Wifi disconnected!"); return 0; } ```
I came across the following statement: A smart compiler can recognize thatx = x + 1can be treated the same as++x. Why is the prefix-operator used here instead of the post-fix operator (or either, if it doesn't matter)? For example, if I had the following loop: ``` while (x < 10) { ... x++; // wouldn't this be the same as doing ++x here? } ``` What would be a case that shows howx = x + 1is equivalent to++xand notx++?
Here's a simple example. Suppose you have something like this: ``` a = (x = x + 1); ``` This would be equivalent to ``` a = ++x; ``` butnotto ``` a = x++; ```
How do I write a C program that allows me to make carriage return for each white space in the Input ? Like for example : Input : "I love programming" Output : ``` I love programming ``` What I did : ``` #include<stdio.h> #include <ctype.h> int main() { int ch; char str[50]; while ((ch = getchar()) != EOF) { putchar(isspace(ch) ? '\r' : ch); } scanf("%s", str); printf("%s", str); return 0; } ```
Read a character. If awhite space, print a'\r' ``` #include <ctype.h> int ch; while ((ch = getchar()) != EOF) { putchar(isspace(ch) ? '\r' : ch); } ``` Or if you want anew line: ``` putchar(isspace(ch) ? '\n' : ch); ```
In the following: ``` float n1= 3.0; double n2 = 3.0; long n3 = 2000000000L; long n4 = 1234567890L; printf("%f %Lf %ld %ld\n", n1, n2, n3, n4); ``` 3.000000 1.200000 2000000000 1234567890 Why is1.2printed for the second value and not3.0? I suppose maybe I'm screwing up thefloatprints -- withfloat,double, andlong double, or what's the reason why the above prints an incorrect result? Is this the correct way to print all decimal-types? ``` float n1= 3.0F; double n2 = 3.0; long double n3 = 3.0L; printf("%f %f %Lf\n", n1, n2, n3); ```
Becaue%Lfisn't the specifier fordouble, it's the specifier forlong double.floatpromotes todoubleautomatically; hence%fcovers bothfloatanddouble. Butlong doubleneeds its own. You kinda got lucky here. On some platforms, the rest of the arguments would be misaligned.
This question already has answers here:Why division is always ZERO? [duplicate](3 answers)Closed2 years ago. I was trying to code a grayscale and have issues with the calculation. Can anyone explain why this returns 27.00000 instead of 27.66667? ``` #include <math.h> #include <stdio.h> int main(void) { float count = ((27 + 28 + 28) / 3); printf("%f\n", count); } ```
You forgot casting: ``` int main() { float count = ((27 + 28 + 28) / (float)3); printf("%f\n", count); return 0; } ``` Or: ``` int main() { float count = ((27 + 28 + 28) / 3.0); printf("%f\n", count); return 0; } ``` https://www.tutorialspoint.com/cprogramming/c_type_casting.htm
How do I write a C program that allows me to make carriage return for each white space in the Input ? Like for example : Input : "I love programming" Output : ``` I love programming ``` What I did : ``` #include<stdio.h> #include <ctype.h> int main() { int ch; char str[50]; while ((ch = getchar()) != EOF) { putchar(isspace(ch) ? '\r' : ch); } scanf("%s", str); printf("%s", str); return 0; } ```
Read a character. If awhite space, print a'\r' ``` #include <ctype.h> int ch; while ((ch = getchar()) != EOF) { putchar(isspace(ch) ? '\r' : ch); } ``` Or if you want anew line: ``` putchar(isspace(ch) ? '\n' : ch); ```
In the following: ``` float n1= 3.0; double n2 = 3.0; long n3 = 2000000000L; long n4 = 1234567890L; printf("%f %Lf %ld %ld\n", n1, n2, n3, n4); ``` 3.000000 1.200000 2000000000 1234567890 Why is1.2printed for the second value and not3.0? I suppose maybe I'm screwing up thefloatprints -- withfloat,double, andlong double, or what's the reason why the above prints an incorrect result? Is this the correct way to print all decimal-types? ``` float n1= 3.0F; double n2 = 3.0; long double n3 = 3.0L; printf("%f %f %Lf\n", n1, n2, n3); ```
Becaue%Lfisn't the specifier fordouble, it's the specifier forlong double.floatpromotes todoubleautomatically; hence%fcovers bothfloatanddouble. Butlong doubleneeds its own. You kinda got lucky here. On some platforms, the rest of the arguments would be misaligned.
This question already has answers here:Why division is always ZERO? [duplicate](3 answers)Closed2 years ago. I was trying to code a grayscale and have issues with the calculation. Can anyone explain why this returns 27.00000 instead of 27.66667? ``` #include <math.h> #include <stdio.h> int main(void) { float count = ((27 + 28 + 28) / 3); printf("%f\n", count); } ```
You forgot casting: ``` int main() { float count = ((27 + 28 + 28) / (float)3); printf("%f\n", count); return 0; } ``` Or: ``` int main() { float count = ((27 + 28 + 28) / 3.0); printf("%f\n", count); return 0; } ``` https://www.tutorialspoint.com/cprogramming/c_type_casting.htm
I have the filesbar.c&foo.cin the same folder. And I have the following makefile: ``` foo: foo.c gcc -o foo foo.c all: clean foo bar bar: bar.c gcc -o bar bar.c clean: rm -rf bar foo ``` The output isfooonly, and the question is why? What's the difference betweenfoo&bar?
I assume you run it asmake. By default make processes first target in the makefile, which is "foo". Place target "all" first, and you'll get both "foo" and "bar". Another way is to explicitly specify target, i.e. runmake allinstead of justmake.
How can I get the length of the array 'source'? I have this so far I was wondering if anyone had any suggestions. Thank you For size I get -2074. I do not know the length of the array, it's a random input. ``` #include <ctype.h> int StrToUpper(char *destination[], const char *source[]) { int size = *(&source + 1) - source; return size; } ```
You can do something like: ``` int StrToUpper(char *destination[], const char *source) { int size = 0; while(source[size] != '\0') size++; return size; } ``` I am assuming that you will be passing string to this function like:StrToUpper("some","somemore")
I came across this syntax:char *seats[14][7];in a c program. I'm a newbie to pointers, can anyone explain why is a 2-D array declared as a pointer and what use does it have?
It's invalid code - a compiler error. Because strictly speaking C doesn't have 2D arrays, it only has arrays of arrays (of arrays...). In this case you have declared an array of incomplete size where, each item is an arrayint* []of incomplete size. The C standard (6.7.6.2) does not allow such an item do be of incomplete type. In case you change the code toint* [x][y]then it is an array of sizexcontainingint* [y]arrays as items, where each such item is an array with sizeyof pointers to integer.
Dear all C programmer: X = 1 << N; (left shift) how to recover N from X ? Thanks
Nin this case is the bit position where you shifted in a1at. Assuming thatXhere only got one bit set. Then to find out what number that bit position corresponds to, you have to iterate through the data and mask with bitwise AND: ``` for(size_t i=0; i<sizeof(X)*8; i++) if(X & (1<<i)) printf("%d", i); ``` If performance is important, then you'd make a look-up table with all possible results instead.
Whenever I create a.hfile, Airline interprets it as acppfile (in the filetype section). How do I set it toc? I couldn't find an answer online, and I don't know in where to change the source code of Airline to do what I want.
Filetype is set by standard Vim ftplugin. To change the default ``` let g:c_syntax_for_h = 1 ``` See:h c.vimfor more options.
I have a problem with understanding the use of pointers in my C-program. The program is designed to print out all elements in the array. The most confusing part is the for-loop that doesnt seem to make sense for me. What is the value of p from the beginning? How does the loop stop if the condition p < a + n always is true? ``` void element(int a[], int n) { for (int *p = a; p < a + n; p++) printf("%d ", *p); } int main() { int f[5] = {1, 2, 3, 4, 5}; element(f, 5); } ```
For your code, p points toa[0], then toa[1], thena[2]and so on. The conditionp < a + nis terminating because when you increment p, it makes the pointer p move froma[0]toa[1]and so on, thus increasing its value anda+nis1+5=6. So when p reaches 5, condition becomes false in next iteration.
I have the followingHdyClampdeclaration in a.uifile.HdyClampis defined in thelibhandyapi.see here ``` ....... <object class="HdyClamp" id="cl"> <property name="visible">True</property> <property name="can-focus">False</property> <child> ....... ``` SinceHdyClampis also aGtkWidget, I thought I should be able to get this object throughGtkBuilderand store it in aGtkWidgetobject. Here is the code. ``` GtkWidget * clamp = GTK_WIDGET(gtk_builder_get_object(builder, "cl")); ``` Wherebuilderis aGtkBuilderobject associated with the.uifile. The result is thatclampisNULLafter that line which meansgtk_builder_get_object()failed to return theHdyClampobject with the given IDcl. I am really not sure why this happens and would greatly appreciate the help.
The issue is fixed, see the comments under the post.
I have a problem with understanding the use of pointers in my C-program. The program is designed to print out all elements in the array. The most confusing part is the for-loop that doesnt seem to make sense for me. What is the value of p from the beginning? How does the loop stop if the condition p < a + n always is true? ``` void element(int a[], int n) { for (int *p = a; p < a + n; p++) printf("%d ", *p); } int main() { int f[5] = {1, 2, 3, 4, 5}; element(f, 5); } ```
For your code, p points toa[0], then toa[1], thena[2]and so on. The conditionp < a + nis terminating because when you increment p, it makes the pointer p move froma[0]toa[1]and so on, thus increasing its value anda+nis1+5=6. So when p reaches 5, condition becomes false in next iteration.
I have the followingHdyClampdeclaration in a.uifile.HdyClampis defined in thelibhandyapi.see here ``` ....... <object class="HdyClamp" id="cl"> <property name="visible">True</property> <property name="can-focus">False</property> <child> ....... ``` SinceHdyClampis also aGtkWidget, I thought I should be able to get this object throughGtkBuilderand store it in aGtkWidgetobject. Here is the code. ``` GtkWidget * clamp = GTK_WIDGET(gtk_builder_get_object(builder, "cl")); ``` Wherebuilderis aGtkBuilderobject associated with the.uifile. The result is thatclampisNULLafter that line which meansgtk_builder_get_object()failed to return theHdyClampobject with the given IDcl. I am really not sure why this happens and would greatly appreciate the help.
The issue is fixed, see the comments under the post.
Let's start with this example: ``` #include <stdio.h> int main() { int x = "string"; printf("%d", x); } ``` Ouput -> "12221232" I know this code example is syntactically correct semantically false. I just don't know what happens here exactly. The text gets converted into an integer, but how? Can someone please explain?
The value you observe is an address where"string"is stored. The literal"string"is actually cast to a pointer of typeconst char *that points to the actual data. This pointer (address of"string"data) is next cast tointwhich you observe as output ofprintf().
Let's start with this example: ``` #include <stdio.h> int main() { int x = "string"; printf("%d", x); } ``` Ouput -> "12221232" I know this code example is syntactically correct semantically false. I just don't know what happens here exactly. The text gets converted into an integer, but how? Can someone please explain?
The value you observe is an address where"string"is stored. The literal"string"is actually cast to a pointer of typeconst char *that points to the actual data. This pointer (address of"string"data) is next cast tointwhich you observe as output ofprintf().
``` // TODO: Calculate number of years until we reach threshold { int years; while (ending_size>=starting_size) starting_size = starting_size + (starting_size/3) - (starting_size/4); years++; } {// TODO: Print number of years printf("Years: %i\n", years); } } ``` When I run my code, it says "use of undeclared identifier "years", and I think it might be due to the way that I formatted my code. Thanks
It looks like you have{…}around the code where years is declared. I think that's your problem. The{and}limit its scope.
I have Lua embedded in a C host. And I have several C functions registered with Lua. Is there any way that when I call Lua and then Lua calls my C function, a value can be passed along from the "outer" C code to the "inner" C code? The specific problem is that I have an HTTP request pointer that I need to access from the callback function, and I'd rather not store it in a global variable due to this potentially being multithreaded code.
When your "outer" C code calls Lua, pass the HTTP request pointer as a light userdata argument. Inside Lua, treat it as an opaque value that you pass to the "inner" C callback as an argument again. Then have your "inner" C code just read it and cast it back to the right type. By the way, Lua itself isn't thread-safe, so be careful of that if your application is multithreaded.
I am using C, in code blocks for reference. My code is as follows: ``` while(1) { char ch; ch = _getch(); MyFunction1(ch); } ``` end of code. So the code waits until there is any input from keyboard, and enters the single character automatic. My problem is, how I make it so if there is no input for 1/4 of a second to run MyFuction2() instead of MyFunction1() .
Please try to do as the following. ``` while (true) { SleepEx((1/4)*1000, true); if (_kbhit()) { MyFunction1(_getch()); } else { MyFunction2(); } } ```
This question already has answers here:C: Passing an array into a function 'on the fly'(3 answers)Closed2 years ago. How can we pass an array directly to a function in C? For example: ``` #include <stdio.h> void function(int arr[]) {}; int main(void) { int nums[] = {3, -11, 0, 122}; function(nums); return 0; } ``` Instead of this, can we just write something likefunction({3, -11, 0, 122});?
You can make use of acompound literal. Something like ``` function((int []){3, -11, 0, 122}); ```
``` int main(){ char a = 5; char *p = &a; // 8 bits int num = 123456789; // 32 bits *p = num; return 0; } ``` Asais 1 byte andnumis 4 bytes, does*p = numtruncate num to 1 byte before assigning it toa? or a 32 bit value gets written to memory and corrupts the stack?
Since you're assigning anintvalue to achar, the value is converted in an implementation-defined way to be in the range of achar(most likely, the low order byte ofnumwill be the value which is assigned). The fact that you're dereferencing achar *to assign to achardoesn't change this. It would be the same as if you dida = num;.
OS - Windows. I'm using a MinGW compiler. When trying to compile a simple program: ``` #include <stdio.h> int main() { printf("Hello, world\n"); } ``` through the console command: ``` gcc.exe -g (filedir) -o (filedir.obj) ``` an error message comes up, saying "no include path in which to find stdio.h". How do I make the compiler find the header and compile the program?
Use the-Ioption to specify additional include paths as part of thegcccommand: ``` gcc -I /include/file/directory ... ``` Having said that, you shouldnotneed to specify an additional include path to findstdio.h(or any other standard library header). Review how you installed MinGW and make sure you followed all the instructions correctly; you may need to uninstall and re-install.
Basically at the most basic level I cant understand why can't I do this: ``` #include <stdio.h> #include <stdlib.h> void mal(char *str){ str = malloc(sizeof(char)); } int main(void) { char *s; mal(s); free(s); return 0; } ```
sgets passed by value to the functionmal. Insidemalthe local parameterstrgets changed by the assignment, butsinmainis kept uninitialized. In C you should pass a pointer tostomalto resolve this problem: ``` #include <stdio.h> #include <stdlib.h> void mal(char **str){ // pointer to pointer *str = malloc(sizeof(char)); // referenced variable behind str changed } int main(void) { char *s; mal(&s); // pointer to s passed free(s); return 0; } ```
``` const char* ch = "text"; ch = "Long text"; ``` Is it OK to write code like this? Is it possible to have buffer overflow? or maybe it can write to address which is not allowed?
This declaration: ``` const char* ch = "text"; ``` Only states that whatchpoints toisconst. It doesn't say thatchitselfitconst. What ischis being initialized with is the address of a string literal, and string literals are read-only. When you then do this: ``` ch = "Long text"; ``` You're assigning tochthe address of adifferentstring literal. So what you're doing is well defined. Had you attempted to do this: ``` ch[0] = 'X'; ``` You would get a compiler error because you're trying to modify something that isconst. Had you left off theconstqualifier and done this, your code would most likely crash because you're attempting to modify a string literal which is read-only.
I have a following line in C: ``` printf("size of sizeof is %d\n", sizeof(printf("lol!\n"))); ``` Am I getting the size of a function pointer here?
Here,sizeofevaluates the return type ofprintf. (Here anint)
I am having a difficult time getting why the answer is 66 bytes to the following question: How much memory gets allocated for the data passed through the pointer in the main functions 2nd parameter(not considering the pointer size) in a 64 bit system, if the app is run with ``` ./program alfa beta gamma ```
The best I could come up with is argv[0]==> 8 bytes for pointer itself + 6 bytes for the data ("./app") ==>14argv[1]==> 8 bytes for pointer itself + 5 bytes for the data ("alfa") ==>13argv[2]==> 8 bytes for pointer itself + 5 bytes for the data ("beta") ==>13argv[3]==> 8 bytes for pointer itself + 6 bytes for the data ("gamma") ==>14argv[4]==> 8 bytes for the pointer (NULL) ==>8 TOTAL: 62 Maybe add 4 bytes forargcfor66bytes??
I was surprised when doing the following that no assembly is produced for theEnums: I thought perhaps it would do something like: ``` Hello: .byte 0 Goodbye: .byte 1 ``` It seems it only adds in the values when assigned to a var: Why is this so? Why don't the 'enum values' get stored when declared (even if I setHello=1)? Example link:https://godbolt.org/z/xxnMvq.
An enum is not a variable, it is a type. The different enum labels are in fact constants. Being a type it requires no space in your final binary. The compiler internally keeps a list of them and replaces every use of them with the constant they represent. These values do however end up in the debugging info, if it is generated, so you can use them in your debugger.
``` int main(){ char a = -5; char b = -6; int c = a+b; return 0; } ``` I'm getting different results for the above code in different architectures, usinggcc. onx86the variablecis properly sign extended and I get-11. On some other architecturescis not sign extended, you get the result ofa+bbit-casted to anintand I get501. Is this undefined behaviour?
charis sometimes an unsigned type. Usesigned charorunsigned charif you need to be explicit about it. Adding a print to your program and compiling under both circumstances shows your behaviour: ``` $ make example && ./example cc example.c -o example -11 ``` You can force GCC to use the unsigned char by default: ``` $ CFLAGS=-funsigned-char make example && ./example cc -funsigned-char example.c -o example 501 ``` I would recommend to always useunsigned charandsigned charin code, unless you use it only for ASCII character storage.
I want to create an array that contains elements of a structure, each element of the struct is a boolean and when accessing each array element I want to modify the value of the structure. Structure is a global variable, when modifying the array element, I want to also modify the global structure. ``` typedef struct { bool bool1; bool bool2; bool bool2; } struct_bool; struct_bool my_struct; bool array_dummy[3] = {my_struct.bool1, my_struct.bool2, my_struct.bool3}; array_dummy[0] = true; array_dummy[1] = true; array_dummy[2] = false; ```
Use pointers: ``` bool *array_dummy[3] = { &my_struct.bool1, &my_struct.bool2, &my_struct.bool3 }; *array_dummy[0] = true; *array_dummy[1] = true; *array_dummy[2] = false; ```
When compiling C(++) code that hasexternfunction declarations to WebAssembly with Clang, it givesundefined referenceerrors rather than importing the symbol. What option will make the linker add those as imports to the WebAssembly module instead of trying to resolve them? ``` #ifdef __cplusplus extern "C" { #endif extern void externalFunction(void); #ifdef __cplusplus } #endif int main() { externalFunction(); return 0; } ```
You can use the import_module and import_name clang attributes to mark the function as imported. e.g.: ``` __attribute__((import_module("env"), import_name("externalFunction"))) void externalFunction(void); ``` Or you can pass --allow-undefined to the linker. Seehttps://lld.llvm.org/WebAssembly.html#imports.
Actually my options are :"C_Cpp.clang_format_fallbackStyle": "{ BreakBeforeBraces: Linux, IndentWidth: 4, ColumnLimit: 80, UseTab: Never, SortIncludes: false, AlignAfterOpenBracket: DontAlign }" I have: ``` for (int i = 0; i < 5; i++) ; ``` I want: ``` for (int i = 0; i < 5; i++); ```
This is a known issue and it make a warning. The only way is to write this: ``` for (int i = 0; i < 5; i++) {} ```
i need some help with a piece of code. I have an array, lets call it array[4]. Now I want to check that at least 3 elements of this array are taller than a threshold. (if statement) E.g. ``` if(2 > ((array[0] > threshold) + (array[1] > threshold) + (array[2] > threshold) + (array[3] > threshold) )) ``` Here Misra is complaining. (Rule 10.1 Unpermitted operand operator "+") Is there another way to code this if statement without checking every possible permutation ? Cheers
How about unpacking the one-liner, possibly to a loop? It could be more readable too: ``` int check = 0; for (int i = 0; i<4; i++) { if (array[i] > threshold) {check++;} } if (check >= 3) ... ``` Your if statement actually appears to be testing something else "at least 3 are taller" vsif (2 > ...)(at most one?).
I'm currently writing a C++ software which have to be compatible with a legacy network service. The encryption/decryption which is used by that service is AES-128-OFB-PKCS#7(yes, it pads the data in OFB mode). Because OFB mode does not require padding OpenSSL does not apply or remove such padding which gives me the troubles. I've been trying to find a way if OpenSSL can be enforced to use padding for modes which do not require it in order to make it compatible with the legacy service. Is that possible on API level? Worst case would be to do the padding myself but if possible I would like to avoid such resolution.
Just wanted to get back to this and notify everyone that there is no way to do that with OpenSSL directly. I've ended up manually adding/removing the padding.
i need to create a postfix calculator using stack. Where user will write operators in words. Like: 9.5 2.3 add = or 5 3 5 sub div = My problem, that i can't understand, what function i should use to scan input. Because it's mix of numbers, words and char (=).
What you want to do is essentially to write aparser. First, usefgetsto read a complete line. Then usestrtokto get tokens separated by whitespace. After that, check if the token is a number or not. You can do that withsscanf. Check the return value if the conversion to a number were successful. If the conversion were not successful, check if the string is equal to "add", "sub", "=" etc. If it's not a number or one of the approved operations, generate an error. You don't have to treat strings of length 1 (aka char) different.
I'm trying to accept a socket non-blockingly: ``` accept4(s, (struct sockaddr *) &peerAddress, &len,SOCK_NONBLOCK); ``` where as s is a fd, peerAddres is an address, and len, is its length. I wish that accept won't block the thread. Though, once I debug, the process is stuck at this line, while no connection is pending. What is my mistake?
SOCK_NONBLOCKjust sets the newly accepted socket to non-blocking. It does not makeacceptitself non-blocking. For this one would need to set the listen socket non-blocking before calling accept.
I want to create an array that contains elements of a structure, each element of the struct is a boolean and when accessing each array element I want to modify the value of the structure. Structure is a global variable, when modifying the array element, I want to also modify the global structure. ``` typedef struct { bool bool1; bool bool2; bool bool2; } struct_bool; struct_bool my_struct; bool array_dummy[3] = {my_struct.bool1, my_struct.bool2, my_struct.bool3}; array_dummy[0] = true; array_dummy[1] = true; array_dummy[2] = false; ```
Use pointers: ``` bool *array_dummy[3] = { &my_struct.bool1, &my_struct.bool2, &my_struct.bool3 }; *array_dummy[0] = true; *array_dummy[1] = true; *array_dummy[2] = false; ```
When compiling C(++) code that hasexternfunction declarations to WebAssembly with Clang, it givesundefined referenceerrors rather than importing the symbol. What option will make the linker add those as imports to the WebAssembly module instead of trying to resolve them? ``` #ifdef __cplusplus extern "C" { #endif extern void externalFunction(void); #ifdef __cplusplus } #endif int main() { externalFunction(); return 0; } ```
You can use the import_module and import_name clang attributes to mark the function as imported. e.g.: ``` __attribute__((import_module("env"), import_name("externalFunction"))) void externalFunction(void); ``` Or you can pass --allow-undefined to the linker. Seehttps://lld.llvm.org/WebAssembly.html#imports.
Actually my options are :"C_Cpp.clang_format_fallbackStyle": "{ BreakBeforeBraces: Linux, IndentWidth: 4, ColumnLimit: 80, UseTab: Never, SortIncludes: false, AlignAfterOpenBracket: DontAlign }" I have: ``` for (int i = 0; i < 5; i++) ; ``` I want: ``` for (int i = 0; i < 5; i++); ```
This is a known issue and it make a warning. The only way is to write this: ``` for (int i = 0; i < 5; i++) {} ```
i need some help with a piece of code. I have an array, lets call it array[4]. Now I want to check that at least 3 elements of this array are taller than a threshold. (if statement) E.g. ``` if(2 > ((array[0] > threshold) + (array[1] > threshold) + (array[2] > threshold) + (array[3] > threshold) )) ``` Here Misra is complaining. (Rule 10.1 Unpermitted operand operator "+") Is there another way to code this if statement without checking every possible permutation ? Cheers
How about unpacking the one-liner, possibly to a loop? It could be more readable too: ``` int check = 0; for (int i = 0; i<4; i++) { if (array[i] > threshold) {check++;} } if (check >= 3) ... ``` Your if statement actually appears to be testing something else "at least 3 are taller" vsif (2 > ...)(at most one?).
I'm currently writing a C++ software which have to be compatible with a legacy network service. The encryption/decryption which is used by that service is AES-128-OFB-PKCS#7(yes, it pads the data in OFB mode). Because OFB mode does not require padding OpenSSL does not apply or remove such padding which gives me the troubles. I've been trying to find a way if OpenSSL can be enforced to use padding for modes which do not require it in order to make it compatible with the legacy service. Is that possible on API level? Worst case would be to do the padding myself but if possible I would like to avoid such resolution.
Just wanted to get back to this and notify everyone that there is no way to do that with OpenSSL directly. I've ended up manually adding/removing the padding.
i need to create a postfix calculator using stack. Where user will write operators in words. Like: 9.5 2.3 add = or 5 3 5 sub div = My problem, that i can't understand, what function i should use to scan input. Because it's mix of numbers, words and char (=).
What you want to do is essentially to write aparser. First, usefgetsto read a complete line. Then usestrtokto get tokens separated by whitespace. After that, check if the token is a number or not. You can do that withsscanf. Check the return value if the conversion to a number were successful. If the conversion were not successful, check if the string is equal to "add", "sub", "=" etc. If it's not a number or one of the approved operations, generate an error. You don't have to treat strings of length 1 (aka char) different.
I'm trying to accept a socket non-blockingly: ``` accept4(s, (struct sockaddr *) &peerAddress, &len,SOCK_NONBLOCK); ``` where as s is a fd, peerAddres is an address, and len, is its length. I wish that accept won't block the thread. Though, once I debug, the process is stuck at this line, while no connection is pending. What is my mistake?
SOCK_NONBLOCKjust sets the newly accepted socket to non-blocking. It does not makeacceptitself non-blocking. For this one would need to set the listen socket non-blocking before calling accept.
``` MES_CRD mesCR; if (pDspMng->reponse_json != NULL && flag == true) { strcpy (reponseJson, (char*)mesCR); SIItrace (7, CV_NIV_GRA_INFO, routine, "Le contenu Json est : %s<", reponseJson); result = json_loads (reponseJson, 0, NULL); } ``` MES_CRD is a structure. i want to copy the content of structure mesCR into reponseJson.
``` if (pDspMng->reponse_json != NULL && flag == true) { memcpy (reponseJson, &mesCR, sizeof mesCR); SIItrace (7, CV_NIV_GRA_INFO, routine, "Le contenu Json est : %s<", reponseJson); result = json_loads (reponseJson, 0, NULL); } ```
I have encountered the following macro definition and I am trying to understand its use and its syntax and logic: ``` #define FOREACH(elem, list, body) {\ for(size_t i = 0; i < size(list); ++i)\ {\ int elem;\ if (get_elem(list, i, &value)) {\ body\ }\ }\ } ``` I have come across macro functions before, however they were simpler and never included this much logic in them. What I did not understand mainly, what thebodyparameter is.Is it possible to pass in certain logic to be added to the function in place of the parameter name? I didn't write this directive so I am not sure whether there are any errors in it.
Yes, you can pass arbitrary logic asbodyparameter. It will be pasted here: ``` if (get_elem(list, i, &value)) {\ body\ }\ ```
I want to declare a global variable inside a main() function... Below is what I want the program to act like ``` #include<stdio.h> int a[6]; int main() { int n; scanf("%d",&n); } ``` I want to create an array of user given size (here n-size) and I want to access that array globally. So instead of creating array of size '6' outside the main() function, I want to create array of 'n' size globally instead of passing array whenever function is called...
You can declare a pointer as global variable and assign buffer to that inmain(). ``` #include<stdio.h> #include<stdlib.h> int *a; int main() { int n; scanf("%d",&n); a = calloc(n, sizeof(*a)); /* calloc() initializes the allocated buffer to zero */ if (a == NULL) { /* calloc() failed, handle error (print error message, exit program, etc.) */ } } ```
I'm new to C and I was asked to make a loop that asks a user to input a number and then check if that number is positive and less than 10. However, I don't know what's wrong with the code below. Any help is much appreciated. ``` int main(){ int a; do{ printf("Enter a positive number: "); scanf("%i", &a); }while((a <= 0) && (a >= 10)); printf("%i is positive and less than 10", a); return 0; } ```
There are two problems that need fixing: You're not checking thatscanf()succeeds. I/O is brittle and can fail.The condition is wrong, both branches of the&&cannot be true at the same time, thus "and" is the wrong operator. You meant||(boolean "or").
This question already has answers here:What are the distinctions between the various symbols (*,&, etc) combined with parameters? [duplicate](5 answers)Closed2 years ago. what is the meaning of the asterisk after a variable, for example here in the function _tempnam ? : _CRTIMP char* __cdecl __MINGW_NOTHROW _tempnam (const char*, const char*); I always see this in function arguments.
_tempnamis a function.That function takes two parameters. The first parameter is a pointer to achar.Anycharreferenced by that pointer cannot be written-to (it isconst). The second parameter is a pointer to achar.Anycharreferenced by that pointer cannot be written-to (it isconst). The return value of the function is a pointer tochar. The rest of the declaration suggests that the function is a C-Runtime-Implementation (CRTIMP), called using the C-calling convention, and does not throw any exceptions.
``` dspList_t *pDspMng = NULL; for(pDspMng = SDSPMNG; pDspMng->mesfct != NULL && strcmp (pDspMng->mesfct, mesfct); pDspMng->prec); ``` ``` INTdspmng.sc: In function 'WebCallback': INTdspmng.sc:216:9: error: statement with no effect [-Werror=unused-value] for(pDspMng = SDSPMNG; pDspMng->mesfct != NULL && strcmp (pDspMng->mesfct, mesfct); pDspMng->prec); ``` This loop is still waiting for a new mesfct for that i make ";" after for, i want an infinite loop
ThepDspMng->precis practically useless. You're computing the value but doing nothing with that value. You may want to store the value in some variable, maybe likepDspMng = pDspMng->prec Also, the;at the end of theforloop looks erroneous.
This question already has answers here:What are the distinctions between the various symbols (*,&, etc) combined with parameters? [duplicate](5 answers)Closed2 years ago. what is the meaning of the asterisk after a variable, for example here in the function _tempnam ? : _CRTIMP char* __cdecl __MINGW_NOTHROW _tempnam (const char*, const char*); I always see this in function arguments.
_tempnamis a function.That function takes two parameters. The first parameter is a pointer to achar.Anycharreferenced by that pointer cannot be written-to (it isconst). The second parameter is a pointer to achar.Anycharreferenced by that pointer cannot be written-to (it isconst). The return value of the function is a pointer tochar. The rest of the declaration suggests that the function is a C-Runtime-Implementation (CRTIMP), called using the C-calling convention, and does not throw any exceptions.
``` dspList_t *pDspMng = NULL; for(pDspMng = SDSPMNG; pDspMng->mesfct != NULL && strcmp (pDspMng->mesfct, mesfct); pDspMng->prec); ``` ``` INTdspmng.sc: In function 'WebCallback': INTdspmng.sc:216:9: error: statement with no effect [-Werror=unused-value] for(pDspMng = SDSPMNG; pDspMng->mesfct != NULL && strcmp (pDspMng->mesfct, mesfct); pDspMng->prec); ``` This loop is still waiting for a new mesfct for that i make ";" after for, i want an infinite loop
ThepDspMng->precis practically useless. You're computing the value but doing nothing with that value. You may want to store the value in some variable, maybe likepDspMng = pDspMng->prec Also, the;at the end of theforloop looks erroneous.
``` dspList_t *pDspMng = NULL; for(pDspMng = SDSPMNG; pDspMng->mesfct != NULL && strcmp (pDspMng->mesfct, mesfct); pDspMng->prec); ``` ``` INTdspmng.sc: In function 'WebCallback': INTdspmng.sc:216:9: error: statement with no effect [-Werror=unused-value] for(pDspMng = SDSPMNG; pDspMng->mesfct != NULL && strcmp (pDspMng->mesfct, mesfct); pDspMng->prec); ``` This loop is still waiting for a new mesfct for that i make ";" after for, i want an infinite loop
ThepDspMng->precis practically useless. You're computing the value but doing nothing with that value. You may want to store the value in some variable, maybe likepDspMng = pDspMng->prec Also, the;at the end of theforloop looks erroneous.
I'm using the following GCC extension to simplifying a big switch statement: ``` case 'a' ... 'z': ... ``` What's the proper/portable way to do this -- i.e., go through all the letters in a big switch -- or for this should a switch not be used.
Remember thatdefaultcan be used for performing a task when none of the cases is true: ``` switch (x) { case 1: case 2: printf("%d\n", x); break; default: if (islower(x)) { puts("alpha"); } break; } ``` Another way using the infamousgoto: ``` if (islower(x)) goto alpha; switch (x) { alpha: printf("alpha\n"); break; case 1: case 2: printf("%d\n", x); break; } ```
On this Makefile:https://github.com/GrapheneOS/platform_frameworks_base/blob/11/Android.mkI found ``` SDK_METADATA_DIR :=$= $(call intermediates-dir-for,PACKAGING,framework-doc-stubs-metadata,,COMMON) ``` What does:=$=means? I found nothing here:What's the difference between := and = in Makefile?neither on the links provided
From the bookthegnumakebook, page 126, The Twilight Zone: It’s possible to take definitions like $( ) and $(\n) and go much further, defining variables with names like =, # or : I think,=is just some other variable. Here,$=implies, expanding the variable=. And:=is used for simple assignment (Evaluated only once).
The task is to reproduce the behavior of the function strcpy in C. I found this code: ``` char *ft_strcpy(char *s1, char *s2) { int i; i = 0; while (s2[i]) { s1[i] = s2[i]; i++; } s1[i] = s2[i]; return (s1); } ``` I don't understand the while condition. Why can I just put "s2[1]" as condition? What does the condtion say in this context?
It checks the value ofs2[i]. The string terminator'\0'has value0. So it will loop until the end of the string. The lines1[i] = s2[i];is added to put the'\0'at the end. By definition, a C-style string is a sequence of chars ended in'\0'. If you forget to put it at the end you probably will get into trouble.
I am debugging a memory issue with gdb. Gdb gives this error info: ``` runtime error: member access within misaligned address 0x0000006d20f4 for type 'struct deque', which requires 8 byte alignment 0x0000006d20f4: note: pointer points here 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ^ ``` Question: How does the displayed address ``` 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ``` corresponds to "0x0000006d20f4"?
As you can read in the message itself, the memory address is0x0000006d20f4and the value you have highlighted are the contents of that memory location.
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed2 years ago.Improve this question I have tried to find it in google, but I couldn't. I am studying C. And now my stage is pointer and function about management memory. But malloc, realloc, calloc...etc are hard to memorize. So I want to know the full context. It will help to remember their meaning. I do not speak English well. So my writing may be weird. Please understand. Thanks for reading.
MemoryAllocation (and reallocation etc...) There is an awful lot to say about these functions but check outthis articlefor a start. And if you can still buy it read "The C Programming Language" by Brian Kernighan and Dennis Richie. AMUSTRead
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.Closed2 years ago.Improve this question I know there is 2 ways to link libraries when we compile a c program: Static: The libraries are "embedded" inside the executableDynamic: The libraries should be present on the file system. The executable depends on this libraries. But is there a way to say when we compile a c program: This librarie should be statically embedded inside the executableThis one should be linked dynamicaly ? Thanks
You can use for example: ``` gcc file1.c file2.c fileN.c ... -lfoo -lbar -lbaz --static -labc -lbcd -lcde ``` In this case, foo,bar,baz are linked dynamically, if available as dynamic libraries, otherwise static. abc,bcd,cde are linked statically.
I have the following code: ``` #include <stdio.h> int main() { char str[100]; int k; scanf("%s", str); scanf("%d", &k); printf("%c", str[k - 1]); return 0; } ``` Why in commandprintfwe have to use%cinstead of%s? I tried replacing%c=%sbut get no result.
In aprintfformat string,%cexpects anintrepresenting a single character.str[k - 1]is achar, which is promoted tointwhen passed to variadic functions such asprintf. %sexpects a non nullcharpointer pointing to a C string. Note that you can print a single non-zero character with this: ``` printf("%.1s", &str[k - 1]); ``` The precision field after the.specifies the maximum number of characters to output, and&str[k - 1]is a pointer to thek-th character of stringstr.
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.Closed2 years ago.Improve this question I know there is 2 ways to link libraries when we compile a c program: Static: The libraries are "embedded" inside the executableDynamic: The libraries should be present on the file system. The executable depends on this libraries. But is there a way to say when we compile a c program: This librarie should be statically embedded inside the executableThis one should be linked dynamicaly ? Thanks
You can use for example: ``` gcc file1.c file2.c fileN.c ... -lfoo -lbar -lbaz --static -labc -lbcd -lcde ``` In this case, foo,bar,baz are linked dynamically, if available as dynamic libraries, otherwise static. abc,bcd,cde are linked statically.
I have the following code: ``` #include <stdio.h> int main() { char str[100]; int k; scanf("%s", str); scanf("%d", &k); printf("%c", str[k - 1]); return 0; } ``` Why in commandprintfwe have to use%cinstead of%s? I tried replacing%c=%sbut get no result.
In aprintfformat string,%cexpects anintrepresenting a single character.str[k - 1]is achar, which is promoted tointwhen passed to variadic functions such asprintf. %sexpects a non nullcharpointer pointing to a C string. Note that you can print a single non-zero character with this: ``` printf("%.1s", &str[k - 1]); ``` The precision field after the.specifies the maximum number of characters to output, and&str[k - 1]is a pointer to thek-th character of stringstr.
I want to print output if OUT is 1. So i think that code. ``` #define OUT 1 void d_printf(char *text){ if(OUT) printf("%s", text); } int main(void){ d_printf("%d\n", 5); return 0; } ``` But my parametre is char*, i can't send %d, 5. How can i solve this?
You can use a simple macro: ``` #include <stdio.h> #define OUT 1 #define d_printf OUT && printf int main(void) { d_printf("%d\n", 5); return 0; } ``` If you get compiler warnings about an unused expression, you can use a more elaborate macro: ``` #include <stdio.h> #define OUT 1 #define d_printf(...) do { if (OUT) printf(__VA_ARGS__); } while(0) int main(void) { d_printf("%d\n", 5); return 0; } ```
We got a program and it holds 6 students we specified them at the beginning. And the problem is i know how to print them in command line. But how to edit them? How to add more so we will have 7 students? I also need to delete that student but teacher told me it would be good if its just empty space or Null. ``` typedef struct Student{ int NrAlbumu; char Imie[20]; char Nazwisko[20]; int RokStudiow; char Plec[20]; char Zaleglosci[20]; }s; ``` Lets say its my struct.
I think that you done something different than the statement. I think you should use a Linked List Data Structure so you need have a struct like this. ``` typedef struct Student{ char name[20]; struct Student *next; }s; ``` In order to make a list of them. You can take a lookhere(it use int as data, so you must use string). Feel free to ask me more!
is there a way to push this line to asm from C from GCC ``` mov ah,1h int 21h ``` I can't find a way to set the AH register to 1h ``` asm("mov %ah,1h"); asm("int 21h"); ```
1hmeans1in hexadecimal number. You can use$0x1to express that. ($is required for integer literals in GCC assembly language and0xis marking the number as hexadecimal). Also note that in GCC assembly language, the destination ofmovinstruction (and other instructions with two operands) should be the 2nd operand. ``` asm("mov $0x1, %ah"); asm("int $0x21"); ``` One more note is that if you want to make sure that%ahis0x1when theintis executed, the two lines should be put into oneasmstatement not to let the compiler put other instructions between them. ``` asm( "mov $0x1, %ah\n\t" "int $0x21" ); ```
``` #define N 5 #define Nv 2 float Cities[N][Nv]={ {0,1}, {3,4}, {1,2}, {5,1} ,{8,9}}; void PrintVec2(float *a, int n) { int i; for (i = 0; i < (n / 2); i++) printf("\n%f %f", a[2 * i], a[2 * i + 1]); printf("\n"); } //somewhere I call this PrintVec2(Cities,N*Nv); ``` New*Nv is a number, integer. How to fix this warning?
The prototype: ``` void PrintVec2(float *a, int n) ``` Does not match the input parameter: ``` PrintVec2(Cities,N*Nv); ``` The function prototype is looking for the address of the array. Change it to send&Cities[0][0]: ``` PrintVec2(&Cities[0][0],N*Nv); ```
Is there a shorthand for returning conditional error code from a function in C? From something like: ``` int e = 0; // Error code. e = do_something() if (e) return e; // ...rest of the code when no error. ``` In Go, you can do like: ``` if err := doSomething(); err != nil { return err; } ```
Why not give it a try: ``` if ((e = do_something()) != 0) return e; // ...rest of the code when no error. ``` This makes it one-lined but not so much clear to read. The operator precedence rule is applied here, so those parenthesis aftereand before0are obviously necessary.
is there a way to push this line to asm from C from GCC ``` mov ah,1h int 21h ``` I can't find a way to set the AH register to 1h ``` asm("mov %ah,1h"); asm("int 21h"); ```
1hmeans1in hexadecimal number. You can use$0x1to express that. ($is required for integer literals in GCC assembly language and0xis marking the number as hexadecimal). Also note that in GCC assembly language, the destination ofmovinstruction (and other instructions with two operands) should be the 2nd operand. ``` asm("mov $0x1, %ah"); asm("int $0x21"); ``` One more note is that if you want to make sure that%ahis0x1when theintis executed, the two lines should be put into oneasmstatement not to let the compiler put other instructions between them. ``` asm( "mov $0x1, %ah\n\t" "int $0x21" ); ```
``` #define N 5 #define Nv 2 float Cities[N][Nv]={ {0,1}, {3,4}, {1,2}, {5,1} ,{8,9}}; void PrintVec2(float *a, int n) { int i; for (i = 0; i < (n / 2); i++) printf("\n%f %f", a[2 * i], a[2 * i + 1]); printf("\n"); } //somewhere I call this PrintVec2(Cities,N*Nv); ``` New*Nv is a number, integer. How to fix this warning?
The prototype: ``` void PrintVec2(float *a, int n) ``` Does not match the input parameter: ``` PrintVec2(Cities,N*Nv); ``` The function prototype is looking for the address of the array. Change it to send&Cities[0][0]: ``` PrintVec2(&Cities[0][0],N*Nv); ```
If I need to copy a string,srcinto the array,dest, usingstrcpyorstrncpy, should I allocate anarbitrarily large sizedarray (likechar dest[1024]for example) or should I calculate the size ofsrcusing something likestrlenand then dynamically allocate a block usingmalloc (strlen(src) * sizeof(char)). The first approach seems "easier" but wouldn't I be consuming more space than I needed? And in some cases it might even fall short. On the other hand, the second approach seems more precise but tedious to do every time and I would have to deallocate the memory everytime. Is this a matter of personal taste or is one of the above preferable over the other?
The simplest way is to use thestrdup() function, which effectively merges thestrlen(),malloc()andstrcpy()calls into one. You will still need to callfree()to release the allocated data in the same way.
I have this two codes Java:public native void savex(int x);C: ``` void Java_com_example_javatest_MainActivity_savex(jint x) { FILE *fp; fp = fopen("/data/data/com.example.javatest/data.txt", "w"); fprintf(fp, "%d\n", (int)x); fclose(fp); } ``` When run the result is always having -1265282592 in data.txt. What's the problem here?
void Java_com_example_javatest_MainActivity_savex(jint x) The function arguments must be: ``` void Java_com_example_javatest_MainActivity_savex(JNIEnv* env, jobject obj,jint x) ```
I have a trenary tree every node got id and name how can I return true when root->id=id and break the recursion ``` BOOLEAN isIdUsed(Trin_Ari *root,int idNumber) { if (root==NULL) return FALSE; if (root->id==idNumber) return TRUE; isIdUsed(root->left,idNumber); isIdUsed(root->middle,idNumber); isIdUsed(root->right,idNumber); return FALSE; } ```
You're ignoring the return values from the recursive calls toisIdUsed. Once you encounter aTRUEthere, you need to propagate it upwards: ``` BOOLEAN isIdUsed(Trin_Ari *root,int idNumber) { if (root==NULL) return FALSE; if (root->id==idNumber) return TRUE; if (isIdUsed(root->left,idNumber)) return TRUE; if (isIdUsed(root->middle,idNumber)) return TRUE; if (isIdUsed(root->right,idNumber)) return TRUE; return FALSE; } ```
Is there an algorithm for finding a day of a week (Sunday, Monday, etc.) with a date (day and month,no year), while using only the starting day of the year (1.1 will be: Sunday, Monday...)?
Is there an algorithm for finding a day of a week ... with a date (day and month,noyear) while using only the starting day of the year ... ** Yes for first 2 months. Hint: begin with(starting_day + 31*(Month==Feb) + day)%7. No, for days March 1st or later. Code needs to know if the year is a leap year.