question
stringlengths
25
894
answer
stringlengths
4
863
This question already has answers here:Multiple printf in the For-loop as part of the initialization, condition and update(2 answers)Closed1 year ago. ``` #include <stdio.h> int main(){ for (printf ("3"); printf("2"); printf("1")) break; return 0; } ``` Can anyone explain how this works? Why does it print 32? When I remove brake it's infinite loop and it prints 12?
First,printf ("3")is executed, so it prints3. Thenprintf("2")is executed, print2. Becauseprintf()'s return value is the number of character it prints, which in this case, is1, and because1is a nonzero value, the loop continues in the body. The first statement in the body isbreak, meaning to exit out the loop. So the loop terminates. So the result on the screen is32
I'm trying to figure out what is the equivalent paths of these in Linux. I downloaded theopensslpackagesudo apt-get install libssl-dev ``` //#cgo windows CFLAGS: "-IC:/Program Files/OpenSSL-Win64/include" //#cgo windows LDFLAGS: "-LC:/Program Files/OpenSSL-Win64/lib" -llibcrypto ```
Assuming you want to find flags needed to build using that installed package, thenpkg-config: ``` ]$ pkg-config --cflags openssl ]$ pkg-config --libs openssl -lssl -lcrypto ``` So you don't need any special-Inor-Lflags, because the includes and libraries are already in the system paths, you only need-lflags. If that's not what you want, then you can just query the content of the package and see where the files are: ``` ]$ dpkg-query -L libssl-dev /. /usr /usr/include /usr/include/openssl /usr/include/openssl/aes.h /usr/include/openssl/asn1.h ... ``` and do with that information whatever you need.
I want generate, under Linux, a complete splint report file including also the date and the split tool version. I tried with ">" to redirect the stdio split output to a file but inside the file I found only the split messages To better explain, I run splint on main.c and on stdio the messages are : ``` **Splint 3.1.2 --- 20 Feb 2018 main.c: (in function main) main.c:7:8: Variable c declared but not used A variable is declared but never used. Use /*@unused@*/ in front of declaration to suppress message. (Use -varuse to inhibit warning) Finished checking --- 1 code warning** ``` now I run again the splint tool : splint main.c > report.txt in the report.txt file I don't found "Splint 3.1.2 --- 20 Feb 2018" and "Finished checking --- 1 code warning" but only the specifi splint messages. How can redirect whole splint output into a file ? Thanks
Since these lines are output viastderr, redirect that into your log file, too.
(inLinux) The methods I found all usesignal. Is there no other way? Is there anything I can do to make the terminal put it into the input buffer?
In order to "read CTL+C as input" instead of having it generate aSIGINTit is necessaryto usetcsetattr()to either clearcc_c[VINTR]or clear theISIGflag as described in the manual page that I linked to, here. You will need to usetcgetattr, first, to read the current terminal settings, adjust them accordingly, thentcsetattrto set them. You should make sure that the terminal settings get reset to their original defaults when your program terminates, it is not a given that the shell will reset them to default, for you.
I know that c works in two's complement but still i can't undrstand how the program below gives me 2147483647 as output. ``` #include<stdio.h> int main(){ int a=-2147483648; a-=1; printf("%d",a); } ```
Becuase anintcan't contains the value-2147483648 - 1, so it result in an integer overflow, which leads to undefined behaviour. Undefined behaviour can result in anything.
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.Closed1 year ago.Improve this question This is used heredo {....} while(ch!=?.?);what doesch!=?.?mean here can anybody please help with it.
It's a syntax error with both clang and gcc. @JonathanLeffler is usually right and I think he nailed the root cause. I used to see this when text was being copied from Microsoft Word to the web (lack of transcode from a Windows code page to ascii/utf8?).
Is it possible to have a macro expanded only once? In the following example,MYCONCATis expanded tofunc_1(10). I want it to expand tofunc_BAR(10). ``` #define BAR 1 // included from a file I cannot change #define FOO BAR #define MYCONCAT2(c) func_ ## c #define MYCONCAT(c, x) MYCONCAT2(c)(x) MYCONCAT(FOO, 10) // is 'func_1(10)', but I want it to be 'func_BAR(10)' ```
Is it possible to have a macro expanded only once? No, it is not possible to partially expand a macro.
I am working with this code that computes the sum of array when I got an idea how to exclude the elements of array that are below 80. the statement ( if (a[x] < 80) ) is not working Below is the code ``` #include<stdio.h> #include<conio.h> #define p printf main() { clrscr(); int a[10], x, sum=0; p("\nEnter 10 numbers greater than 80: "); for(x=0; x<10; x++) scanf("%d", &a[x]); for(x=0; x<10; x++) sum=sum+a[x]; p("The sum is %d", sum); getch(); return 0; } ```
you should change your code into this: ``` for(x=0; x<10; x++){ if( a[x] > 80){ sum=sum+a[x]; } } printf("The sum is %d", sum); ```
The error is marked in the #define, but I'm unsure where is the problem or how to fix it. This is probably filled with mistakes, so any feedback is welcome. ``` #include <stdio.h> #include <time.h> #include <stdlib.h> #define N 6 void fil_array(int* A,int const N); void print_array(int* A,int const N); int main() { int i,A[N]; srand(time(NULL)); fil_array(A, N); print_array(A, N); return 0; } void fil_array(int* A, int const N) { int i; for (i=0; i<N; i++) A[i]=rand%21; } void print_array(int* A, int const N) { int i; for (i=0; i<N; i++) printf("A[%d]=%d\n", i,A[i]); } ```
There is naming conflict in your code. Macro name#define N 6andint const Nthis 2 name are conflicted. Use different name to solve this. There is one more things I want to share. In this lineA[i]=rand%21;rand should be a function name. The correct way isA[i]=rand()%21;
I rotate the box around X axis those are images taken when running my code: example1 example2 example3 a plane has lost I usedglEnable(GL_DEPTH_TEST), andglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)before drawing. why?
Your window (default framebuffer) doesn't have a depth buffer at all. You have to setup a OpenGL window with a depth buffer by using thesf::ContextSettingsclass. SeeUsing OpenGL in a SFML window: ``` ContextSettings settings; settings.depthBits = 24; ```
``` #include <stdio.h> [Result Screenshot Attached ] int main(){ int a; printf("Enter a number %d\n", a); scanf("%d", &a); (a < 5) ? printf("A is less than 5") : printf("A is Greater than 5"); return 0; ``` } Result is given below also:- PS D:\Leaning C language> cd "d:\Leaning C language" ; if ($?) { gcc ternary.c -o ternary } ; if ($?) { .\ternary } Enter a number 12914124
Before taking input you have printed 'a' so it is throwing the garbage value. Try this code : ``` #include <stdio.h> int main(){ int a; printf("Enter a number :"); scanf("%d", &a); (a < 5) ? printf("A is less than 5") : printf("A is Greater than 5"); return 0; } ```
``` (gdb) print inputInfo $8 = (SObjectRecInput *) 0x7fffffffced0 ``` For example, when I want to check the value of inputInfo, it prints out: ``` 0x7fffffffced0 ``` And its type is 'SObjectRecInput'. How to actually print out its value?
inputInfoappears to have a pointer type, so dereference it: ``` (gdb) print *inputInfo ```
``` #include<stdio.h> void func(int a[10]); int main(void) { int arr[10]; func(arr); return 0; } void func(int a[10]) { int b[10], x=5; a =&x; b =&x; //error: assignment to expression with array type } ``` In this C code mentioned herewith, there is an error withb=&xsince assignment to expression with array type but why not witha=&xafter allais an array tofunc?
Becauseais not an array (despite the superficially similar declaration), it is a pointer. You can't declare arguments to functions as arrays in C, and if you do, the compiler silently changes them into pointers for you.
This is my code, here I am takingcharinput each time loop runs. I am giving 5 inputs but it is only responding to 2 of them. ``` #include <stdio.h> int main() { int t; scanf("%d",&t); while (t--) { char c; scanf("%c",&c); if(c =='b' || c== 'B') printf("BattleShip\n"); else if(c=='c' || c=='C') printf("Cruiser\n"); else if(c == 'd' || c=='D') printf("Destroyer\n"); else if(c=='f' || c=='F') printf("Frigate\n"); } } ``` ``` Input: 5 b f c b f Output: BattleShip Frigate ```
The problem is your "scanf"-function in the loop. The char %c identifier reads \n as input if you use:scanf("%c", &c)If you write it as follows:scanf(" %c", &c)your problem is solved.
I've the functionsystem(cmd)that executes a command which returns two numbers to the terminal: ``` 977190 977190 ``` How can I assign one of these numbers to a variable to use in the program? It doesn't matter if it is a char or an int variable.
Ifposixis an option, you can switch fromsystemtopopen ``` #include <stdio.h> #include <stdlib.h> FILE *popen(const char *, const char *); int pclose(FILE *); int main(void) { FILE *cmd; cmd = popen("echo 123", "r"); if (cmd == NULL) { perror("popen"); exit(EXIT_FAILURE); } char result[1024]; long number = 0; if (fgets(result, sizeof(result), cmd)) { number = strtol(result, NULL, 10); } pclose(cmd); printf("%ld\n", number); return 0; } ``` Output: ``` 123 ```
This question already has answers here:Why are C character literals ints instead of chars?(11 answers)Closed1 year ago. I know that C and C++ are different languages. Code - C ``` #include <stdio.h> int main() { printf("%zu",sizeof('a')); return 0; } ``` Output ``` 4 ``` Code- C++ ``` #include <iostream> int main() { std::cout<<sizeof('a'); return 0; } ``` Output ``` 1 ``` https://stackoverflow.com/a/14822074/11862989in this answer userKerrek SB(438k Rep.)telling about types in C++ nor mentionscharneitherintbut just integral. is char in C++ is integral type or strict char type ?
is char in C++ is integral type or strict char type ? Character types, such aschar, are integral types in C++. The type of narrow character constant in C isint, while the type of narrow character literal in C++ ischar.
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.Closed1 year ago.Improve this question I am trying to scan and my method just prints and exits. It won't scan. ``` int main() { char *one = (char*)malloc(34* sizeof(char)); char *two = (char*)malloc(16* sizeof(char)); char test ; printf("please enter a Q \n"); scanf("%c", test); printf("%c\n", test); return 0; } ```
``` scanf("%c", test); ``` should be: ``` scanf("%c", &test); ```
enter image description here sorry , my eng very bad ok , i want fwrite then fread file , but i can't do it , can you help me ``` #include"stdio.h" #include"stdlib.h" int main(){ FILE *f; f = fopen("trungbinh","wb"); if(f==NULL){ printf("Error"); exit(0); } float a,b,c; printf("Nhap 3 so a b c : "); scanf("%f",&a); scanf("%f",&b); scanf("%f",&c); float x= (a+b+c)/3; printf("Trung binh con cua 3 so la %.3f",x); fwrite(&x,sizeof(float),1,f); fclose(f); } ```
In your second programvidu2.exe(the one which has not been posted into the question, but is only visible in the image), the line ``` if(f=NULL){ ``` is wrong. It should be: ``` if(f==NULL){ ``` This is causing yourfreadfunction call to fail.
So I havevoid *ptrand I want to view the first 4 bytes, which is some integer. Initially I thought I should do: ``` void *return_val = *(int *)ptr; ``` Is this right? I know how to move my pointer using sizeof after I view the metadata but I am not 100% sure on how to assign that integer in the metadata to a variable.
Ifptrdid not originally point to anintobject then attempting to reinterpret the bytes in this manner is a strict aliasing violation. The proper way to do this would be to usememcpyto copy the bytes into anint: ``` int val; memcpy(&val, ptr, sizeof val); ```
How can I declare a double pointer and assign its value directly from a normal variable? ``` int a = 5; int* b = &a; int** c = &b; int** d = &&a;//This does not work int** e = &(&a);//This does not work ```
How can I declare a double pointer and assign its value directly from a normal variable You cannot. "double pointer" is not a special construct in C. It is a short name for a pointer-to-pointer. A pointer always points to a variable, i.e., something with a memory location.&ais an "rvalue", not a variable. It has no memory location and, therefore, you cannot point to it.
This question already has answers here:Array of variable length in a structure(3 answers)Closed1 year ago. I am begginer in C programming. Can you tell me why I can't use one field in struct in another field? ``` struct example{ int length; int array[length]; } ``` Can you tell me what's the scope struct has? I know that is just struct tag not real struct variable,but please explain to me.
lengthis not a variable, it's a structure member. It can only be used along with a variable that contains that structure type, e.g. ``` struct example myvar; myvar.length = 10; ``` Since the size of the array member has to be known when the variable is declared, it's not possible for it to be dependent on the value of another member of the same structure. If the size of the array varies, you can use aflexible array member. SeeWhat's the need of array with zero elements?
This question already has answers here:Array of variable length in a structure(3 answers)Closed1 year ago. I am begginer in C programming. Can you tell me why I can't use one field in struct in another field? ``` struct example{ int length; int array[length]; } ``` Can you tell me what's the scope struct has? I know that is just struct tag not real struct variable,but please explain to me.
lengthis not a variable, it's a structure member. It can only be used along with a variable that contains that structure type, e.g. ``` struct example myvar; myvar.length = 10; ``` Since the size of the array member has to be known when the variable is declared, it's not possible for it to be dependent on the value of another member of the same structure. If the size of the array varies, you can use aflexible array member. SeeWhat's the need of array with zero elements?
I have this code ``` char *c="hello"; char *x=malloc(sizeof(char)*5+1); memcpy(x,(char[2])c,sizeof("hello")+1); x[5]='\0'; printf("%s\n",x); ``` it gives error that cast specifies array type. why is that? what's the reason behind this error. Does this meanI can't cast like with array type meaning:I can cast to pointer like (char *) but I can't cast to array type like (char[2]) or (char[])Am I missing anything? What I need to do in my code to resolve the error cast specified array type error at ``` 10 | memcpy(x,(char[2])c,sizeof("hello")+1); ```
Arrays do not have the assignment operator. You may not write for example ``` char *c="hello"; char s[6]; s = c; ``` As a result such a casting like ``` ( char[6] )c ``` is not allowed.
Saw thispVarparameter definition in a demo program, does this means it is constant pointer value and constant pointer address? ``` void myfunc(mystruct_t * const * pVar) { // ... } ```
It means thatpVaris a (non-const) pointer to a const pointer to a (non-const) mystruct_t object. General rule for reading and understanding C declarations -- start from the name (pVar here) and read out from there. When there are both prefix and suffix things, the suffix things are higher precedence, so come first, unless there are parens to get the prefix things first.
For finite valuesv0,v1and valuerin[0, 1]range, will the valuev, computed as below, always belong to[v0, v1]range, or can it be (slightly) outside due to round off errors? ``` double v0; // Finite double v1; // Finite double r; // In [0, 1] double v = v0 * r + v1 * (1.0 - r); if (v0 <= v1) assert(v0 <= v && v <= v1); else assert(v1 <= v && v <= v0); ```
Yes, it can be. Here's an example: ``` #include <assert.h> int main() { double v0 = 2.670088631008241e-307; double v1 = 2.6700889402193536e-307; double r = 0.9999999999232185; double v = v0 * r + v1 * (1.0 - r); if (v0 <= v1) assert(v0 <= v && v <= v1); else assert(v1 <= v && v <= v0); return 0; } ``` This produces: ``` Assertion failed: (v0 <= v && v <= v1), function main, file b.cpp, line 12. ``` The value ofvcomputed in this case is: ``` 2.67009e-307 ```
I'm a C beginner, and I came across this code while trying to implement a linked list. ``` struct Node *ptr = malloc(sizeof(*ptr)); ``` The Node struct looks like this: ``` struct Node { int data; struct Node *next; }; ``` I'm trying to understand the first line. It seems as ifmalloc(sizeof(*ptr))already knows the contents ofptr. What exactly is happening on the left side and is it happening before malloc is called?
It seems as ifmalloc(sizeof(*ptr))already knows the contents ofptr. Actually, it doesn't. Thesizeofoperator doesn't actually evaluate its operand (unless it's a variable length array), it just looks at its type. This means thatptrisn't actually dereferenced and is therefore a safe operation.
I'm trying to create a makefile for my program (a very simple one). My files arelab.candlab.h. I need to create object file oflab.cand with a different name (matlib.o), and compile without linkage. This is my attempt: ``` matlib: matlib.o lab.o gcc -c matlib.o matlib.o: lab.c lab.h gcc -c lab.c ``` However, I'm getting this error: ``` No rule to make target 'matlib.o', needed by 'matlib'. Stop. ``` What am I doing wrong?
You should tell gcc to output the object file in a different name with-oflag. The correct recipe is ``` matlib: matlib.o lab.o gcc matlib.o -o matlib matlib.o: lab.c lab.h gcc -c lab.c -o matlib.o ```
I'm a C beginner, and I came across this code while trying to implement a linked list. ``` struct Node *ptr = malloc(sizeof(*ptr)); ``` The Node struct looks like this: ``` struct Node { int data; struct Node *next; }; ``` I'm trying to understand the first line. It seems as ifmalloc(sizeof(*ptr))already knows the contents ofptr. What exactly is happening on the left side and is it happening before malloc is called?
It seems as ifmalloc(sizeof(*ptr))already knows the contents ofptr. Actually, it doesn't. Thesizeofoperator doesn't actually evaluate its operand (unless it's a variable length array), it just looks at its type. This means thatptrisn't actually dereferenced and is therefore a safe operation.
I'm trying to create a makefile for my program (a very simple one). My files arelab.candlab.h. I need to create object file oflab.cand with a different name (matlib.o), and compile without linkage. This is my attempt: ``` matlib: matlib.o lab.o gcc -c matlib.o matlib.o: lab.c lab.h gcc -c lab.c ``` However, I'm getting this error: ``` No rule to make target 'matlib.o', needed by 'matlib'. Stop. ``` What am I doing wrong?
You should tell gcc to output the object file in a different name with-oflag. The correct recipe is ``` matlib: matlib.o lab.o gcc matlib.o -o matlib matlib.o: lab.c lab.h gcc -c lab.c -o matlib.o ```
Here's the code: ``` #include <stdio.h> #include <stdlib.h> int main() { int age; printf("Enter your age: "); scanf("%d",&age); printf("You are %d years old!",age); return 0; } ``` When I run the code I get this in the output: ``` [Running] cd "c:\Users\kathh\Documents\Code\C\" && gcc test.c -o test && "c:\Users\kathh\Documents\Code\C\"test ``` And when I force stop it I get this in the output: ``` [Done] exited with code=1 in 6.412 seconds ``` What should I do?
Try addingfflush(stdout);immediately after each line that callsprintf.
I am writing a simple program that takes an input and adds it to a sum and then prints it, but then asks for another input and also adds that to the sum. However when 0 is in the input, the program should stop. That part is not working, here is what I have tried. ``` #include <stdio.h> int main(){ int n, summa, t; summa = 0; t=1; do{ scanf("%d", &n); if(n==0){t=0; } summa = n + summa; printf("%d\n", summa); } while(t == 0);{return 0;} return 0;} ```
I believe you intended your conditional to bet != 0. Here's a reformatted version of your code with the new conditional, see if that functions as you expected. ``` #include <stdio.h> int main() { int n, summa, t; summa = 0; t = 1; do { scanf("%d", &n); if (n == 0) { t = 0; } summa = n + summa; printf("%d\n", summa); } while(t != 0); return 0; } ```
I'm using OpenSSL (openssl/sha.h) to calculate SHA256 hashes in a performance critical application, written in C. I'm wondering if OpenSSL really uses theSHA256 CPU instructionsor if it just calculates SHA256 hash by itself? Is there a way, to find which way OpenSSL is doing this calculation?
The easiest way is to see the port source code as it is open (nomen omen) For x86-064 you can see: ``` sha256rnds2 $CDGH0,$ABEF0 ``` which indicates that the library uses sha instructions. https://github.com/openssl
Objective : Get a list of all the available functions in a header file.Get a man-page like information of any function. For example, I want a list of available functions in<time.h>and after that I want information of the functiontime() I don't want to have to google the information of all these header files. With python I can just use thedir()andhelp()functions.
Due to python nature (being interactive) you can use function like dir() and help() but there no such thing in c (since it would not even make sense). to get an explanation about a function or a library: since this is about the standard library take a look at: the standard specificationask the manual withman <function>orman <header>if your on Unix/Linux go seehere for the unix standard specification
How can I check if a file exists in APPDATA without using the full path ? ``` #include <stdio.h> #include <unistd.h> #include <windows.h> int main(void) { if (access("%APPDATA%\\changzhi_leidianmac.data", F_OK) != -1) { printf("File Found......"); } else { printf("File not found !!!!"); } return 0; } ```
You can usegetenv ``` #include <stdlib.h> int main(void) { char *appdata = getenv("APPDATA"); ... ... } ``` And later usesnprintf.
Why does this result in stack smashing? Is it not possible to modify the memory location using pointer? ``` int result; reverseDigits2(123, &results); printf("reverseDigits2(): %d\n", result); void reverseDigits2(int num, int *result) { while (num > 0) { *result = num % 10; num /= 10; printf("%p %d\n", result, *result); result++; } } ``` output: ``` 0x7ffe3ac450c4 3 0x7ffe3ac450c8 2 0x7ffe3ac450cc 1 reverseDigits3(): 3 *** stack smashing detected ***: terminated ```
result++will increment the memory location. If you called your function like this: ``` int bar; reverseDigits2(234, &bar); ``` then some memory outside of the memory allocated for bar will be written, as it is shown in your output.
I am busy making a spell checker and when I compare the wordI'mto the dictionary versionimit returns false. I usedstrcasecmpto compare them case insensitively but the apostrophe is still a problem. How can I compare the two (punctuation insensitively) and get true as the output?
Write your own routine to skip punctuation: ``` #include <stdio.h> #include <ctype.h> int insenistive_strcmp(char const* s1, char const* s2) { unsigned char const* p1 = (unsigned char const*)s1; unsigned char const* p2 = (unsigned char const*)s2; for (;; ++p1, ++p2) { while (ispunct(*p1)) ++p1; while (ispunct(*p2)) ++p2; int ch1 = toupper(*p1); int ch2 = toupper(*p2); if (!ch1 || !ch2 || ch1 != ch2) return ch1 - ch2; } } int main() { printf("%d\n", insenistive_strcmp("I'm", "im")); } ```
I am trying to write a C function that compares tho strings not as pointer equality but content equality. But I get an error error: invalid type argument of unary ‘*’ (have ‘int’) This is my code: ``` #include <stdio.h> #include <stdlib.h> int stringcompare(char * str1, char * str2, int strSize){ char * word1 = str1; char * word2 = str2; for (int i = 0; i < strSize; i++) { if (*word1[i] != *word2[i]) { printf("The strings are DIFFERENT!"); return 1; } } printf("The strings are a MATCH!"); return 0; } int main(void){ char * str1 = "Hello World!"; char * str2 = "Hello World!"; stringcompare(str1, str2, 13); } ```
For an array, pointed to by*ptr, an element at positioniis dereferenced by*(ptr + i), which is the equivalent ofptr[i]and not*ptr[i].
When I am running the following program it executes just fine: ``` int *a, i=3; int **arr; a = &i; arr = malloc(sizeof(int*)); arr[0] = a; ``` However, malloc returns a void* pointer so it would be prettier to type cast it. I tried(int*)malloc(sizeof(int*))but I am getting a warning: assignment from incompatible pointer type pointing at the line of typecasting (specifically at the equals sign). What is the correct type for the specific case? Thank you in advance!
The type should be the same as the pointer you're assigning to. Since you're assigning toint **arr, you should cast toint **. ``` arr = (int **)malloc(sizeof(int*)); ``` However, it's generally not recommended to cast the result ofmalloc()in C. SeeDo I cast the result of malloc?for reasons.
``` #include <stdio.h> int main(){ float fever ; printf("do you have fever? Enter Y or N: "); scanf("%f", &fever); if(fever =='y') { printf("you have symptom\n"); } else { printf("you dont have symptom\n"); } return 0; } ```
The type of fever is not correct. It should becharas per your input. ``` #include <stdio.h> int main(){ char fever ; printf("do you have fever? Enter Y or N: "); scanf("%c", &fever); if(fever =='y' || fever == 'Y') { printf("you have symptom\n"); } else { printf("you dont have symptom\n"); } return 0; } ```
I'm trying to understand what is this condition mean. Does it mean after shifting the value it will be equal to 1? I mean does it mean --> if (c >> a is 1) Note:c >> a & 1same as(c >> a) & 1.
Bitwise AND operate onbits, so the possibilities are : ``` 1101 & 0001 => 0001 0001 & 0001 => 0001 1010 & 0001 => 0000 0000 & 0001 => 0000 ``` Now, on C, anything that's not a zero is treated astrue, so the statement means "if after shifting the least significant bit is 1", or perhaps "if after shifting the value is odd" if you're dealing with odd-even operation.
So I tried to write a program to tell me the circumference and area of a circle when I input the radius but it don't want to work ( I am following instructions from a book (Beginning C by Ivor Horton's)) so here is the program ; ``` #include <stdio.h> void main() { float radius= 0.0f; float circu= 0.0f; float area= 0.0f; float PI= 3.14159f; printf("Input the radius of the circle:"); scanf("%f" , &radius); circu = 2.0f * PI * radius; area= PI*radius*radius; printf("\nThe circonferance is %f" , circu); printf("\nThe area is %f" , area); } ```
seem that works good ``` gcc t.c -Wall t.c:3:6: warning: return type of ‘main’ is not ‘int’ [-Wmain] 3 | void main() | ^~~~ a@zalman:~/Dokumenty/temp$ ./a.out Input the radius of the circle:2.0 The circonferance is 12.566360 The area is 12.566360 ```
``` #include <stdio.h> int main() { int x,y,add,subtraction,multiplication,division; printf("Write x:"); scanf("%d",&x); printf("Write y:"); scanf("%d",&y); add = x+y; printf("Add=%d\n",add); subtraction = x-y; printf("subtraction = %d\n",subtraction); multiplication = x*y; printf("multiplication = %d\n",multiplication); division = x/y; if (y == 0) printf("Operation not permitted"); else printf("division = %d\n",division); return 0; } ``` So When i'm printing y=0 nothing happens No "Operation not permitted" or answer of division What should i do?
Just place this statement ``` division = x/y; ``` inside the if statement like ``` if (y == 0) { printf("Operation not permitted"); } else { division = x/y; printf("division = %d\n",division); } return 0; ```
I am using Windows-11, 64-bit, and Dev-C++ (Bloodshed v5.11); the following is the simple code snippet:- ``` #include<stdio.h> int main() { return -1; } ``` I am getting the following output in the console:- Process exited after 0.2015 seconds with return value 4294967295 Press any key to continue . . . In the output, I do recognize that 4294967295 (2^32 - 1) is the max value of the unsigned 4-byte integer, but I cannot understand why this value is returned instead of "-1".
-1in two's complement signed number format (assuming 4 bytes long integers) is0xffffffffwhich is the maximum unsigned value that can be stored in the 4 bytes. Two's complement format is used by almost all computers used nowadays (including your PC, Mac and any mobile phone) Your shell is displaying the program return value asunsigned integer. The decimal representation of the0xffffffffhex number is4294967295
Using#ifdef <macro> <statement> #endifallows one to have verbose messages displayed only during development and is quite handy. I wonder if something like the code below is possible, becoming even shorter: ``` // pseudo-code: #define IN_DEV #define DEBUG_ONLY(statement) (#ifdef IN_DEV (statement) #endif) int main(void) { DEBUG_ONLY(printf("hello from debug mode\n");) //... } ``` This would only cost me a very readable one-liner which can be turned on or off. Is something like this / close to this possible?
You could change the meaning ofDEBUG_ONLYdependent on ifIN_DEVis defined: ``` // pseudo-code: #ifdef IN_DEV #define DEBUG_ONLY(statement) {statement} #else #define DEBUG_ONLY(statement) // Nothing #endif int main(void) { DEBUG_ONLY(printf("hello from debug mode\n");) //... } ``` Running example:Link
This question already has answers here:What does a colon in a struct declaration mean, such as :1, :7, :16, or :32?(3 answers)Closed1 year ago. I'm reading about structs in C and I came across some interesting declaration that I don't know what does is mean. The declaration goes as follows: ``` typedef struct name{ int x :1; }name; ``` what does line 'int x :1;' mean ? is 1 the default value of x? Would appreciate help! Thanks
It specifies the number of bits to use for that field. It is called "bit field". Check this:https://en.cppreference.com/w/cpp/language/bit_field
Suppose we have ``` int x = 4; int *ptr = &x; ``` I was hoping thatptr[0]would beptr,ptr[1]would beptr + 1, etc. However, something completely different happens. I ran ``` #include <stdio.h> int main() { int x = 4; int* ptr; ptr = &x; //ptr vs ptr[0] printf("ptr: %p\n\n", ptr); printf("ptr[0]: %p\n\n", ptr[0]); //ptr + 1 vs ptr[1] printf("ptr + 1: %p\n\n", ptr + 1); printf("ptr[1]: %p\n\n", ptr[1]); //ptr + 5 vs ptr[5] printf("ptr + 5: %p\n\n", ptr + 5); printf("ptr[5]: %p\n\n", ptr[5]); } ``` The result was ``` ptr: 0115FBF4 ptr[0]: 00000004 ptr + 1: 0115FBF8 ptr[1]: CCCCCCCC ptr + 5: 0115FC08 ptr[5]: 00000001 ```
ptr[0]is*(ptr + 0),ptr[1]is*(ptr + 1), etc. Indexing computes the offsetand dereferences. You should have gotten a warning about using%pto print something that isn't a pointer.
I am trying to figire out how to not have garbage values in dynamically allocated char* str. ``` char* str = (char*)malloc(10*sizeof(char)); ``` since I want to use this char* to concatenate strings after, so I want to know how to not to have garbage value like below, ``` printf("str looks like this %s\n",str); ``` then output is ``` 譁�蟄怜 ``` Also, this happens when I am using Ubuntu, but does not happen with mac. How do I make sure that it does not have garbage values so that I can concatenate nicely later?
The most expensive way is to usecallocfunction. ``` char* str = calloc(10, sizeof(*str)); ``` The fastest way: ``` char* str = malloc(10 * sizeof(*str)); *str = 0; ```
I have a function that just prints thread id it is called from. I want 2 threads call this functiontaking turnsn times. I had implemented this functionality in pthreads with a condition variable but it is too verbose. What I want program to print as follows: ``` id: 0 id: 1 id: 0 id: 1 id: 0 id: 1 ... ``` In the end, "id: 0" and "id: 1" should be printed n times. What is the idiomatic way of doing this OpenMP?
You can check the thread number against your iteration count and implement the handoff with a barrier. ``` #include <omp.h> #include <cstdio> int main() { /* note that it is not pragma omp parallel for, just a parallel block */ # pragma omp parallel num_threads(2) for(int i = 0; i < 10; ++i) { if((i & 1) == (omp_get_thread_num() & 1)) std::printf("%d: thread %d\n", i, omp_get_thread_num()); # pragma omp barrier } } ```
This question already has answers here:Printing leading 0's in C(11 answers)Closed1 year ago. Hi I want to printf the dateApp function For example I expected : 19:04 But the result is : 19:4 How to modify the function, so the function always return 2 digits, Thankyou! ``` void dateApp(){ char line[500] = "\xb3"; time_t currentTime; time(&currentTime); struct tm *myTime = localtime(&currentTime); printf("Date : %i/%i/%i \xb3 Time : %i:%i %44s", myTime ->tm_mday, myTime->tm_mon + 1, myTime->tm_year + 1900, myTime->tm_hour, myTime->tm_min, line ); } ```
You need to add a field width of 2 to each%iif you want it to always print at least 2 characters, along with the0flag to tell it to pad with zeros on the left. ``` printf("Date : %02i/%02i/%i \xb3 Time : %i:%02i %44s", ... ```
What is the header file forvsnprintfin the kernel? Can anyone please tell me this, I have kernel 5.14 and I am not sure what headers are default on my system. I have a number of different kernel headers installed, these are: ``` linux-headers-5.11.0-25 linux-headers-5.11.0-40 linux-headers-5.11.0-25-generic linux-headers-5.11.0-40-generic linux-headers-5.11.0-38 linux-headers-5.11.0-38-generic ``` Which one should be the default? But i like to ask what is the header file for functionvsnprintf?
Taking a look at the source code for Linux v5.11, the correct header seems to belinux/kernel.h. It's the same file for Linux v5.14. To check which headers you should use for your currently running kernel use the commanduname -rwhich should tell you the correct version. You can then compile using those and an appropriateMakefile: seethe documentationfor more info.
``` int board[4][8] = { {0, 1, 2, 3, 4, 5, 6, 7}, {1, 2, 3, 4, 5, 6, 7, 8}, {2, 3, 4, 5, 6, 7, 8, 9}, {3, 4, 5, 6, 7, 8, 9, 10}, }; int secondRow[8] = board[1]; // <-- error: invalid initializer for (int i = 0; i < 8; i++) { if (someCondition(secondRow[i])) { // ... } } ``` How do I assign the second element inboard(the{1, 2, ..., 7, 8}array) tosecondRow? Do I declaresecondRowas a pointer of some sorts instead? If so, can I still use it in the same way in the loop below (or how should I change it)?
You cannot. You must eithercopyit orreferenceit. You probably want the latter: ``` int * secondRow = board[1]; for (int i = 0; i < 8; i++) { if (someCondition(secondRow[i])) ... } ``` Arrays are not first class citizens in C and C++.
May I ask what I'm doing wrong here? I'm trying to calculate for the opposite side, given the angle and hypotenuse. I feel like I'm using sine the wrong way. Need some clarification on why my code isn't working. ``` #include <stdio.h> #include <math.h> int main () { double fAngle, fHyp; printf("Angle: "); scanf("%lf", &fAngle); printf("Hypotenuse: "); scanf("%lf", &fHyp); printf("The opposite side is %lf", sin(fAngle) * fHyp); return 0; } ```
You most likely are entering input in degree angles, while your code expects radian angles. You can easily convert to radians like this : ``` double fAngle; printf("Angle: "); scanf("%lf", &fAngle); fAngle = fAngle * 2.0 * M_PI / 360.0 ``` π radians are equal to 180°
I have the following code: ``` int* foo(){ int x = 15; return &x; } ``` Which I understand why not to do since the local variable address gets erased from the stack after the function finishes and it becomes a dangling pointer. The question is, how do I not make it a dangling variable without making x a static variable
The blessed ways are: return a value and not an addressint foo(){ int x = 15; return x; }have the caller to provide an addressint *foo(int *x) { *x = 15; return x; }orvoid foo(int *x) { *x = 15; }Return dynamic (allocated) memory:int *foo() { int *x = malloc(sizeof(*x)); // should test valid allocation but omitted for brievety *x = 15; return x; }Beware, the caller will takeownershipor the allocated memory and is responsable to free it later.
I wanted to run an Hello World program as I am starting in C : ``` #include <stdio.h> int main(){ printf("Hello World\n"); return 0; } ``` I compile it with this command :gcc h4.c -o h4 It create the executable h4 and when I click on it the command prompt pop and get shut down directly its like its running but to quick for me to see before it shut down.
use the command./h4in your command prompt to run the program but keep the prompt open. Clicking on the executable also does "runs" the program, but it closes the window after the execution is finished. Seems like you are on Windows. In this case, you don't need the prefix./,just simplyh4.exe. Or, if you really want to, you can use.\.
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.Closed1 year ago.Improve this question When I input a negative integer the output will not result to it's cube value. I'm confused what should I do? here is my code: ``` #include <stdio.h> int main() { int n, i, cube; printf("Enter an integer: "); scanf("%d",&n); while (i<=n) { cube = i*i*i; i++; } printf("The cube of %d = %d\n ", n, cube); return 0; } ```
I would assume you'd want to compute the cube of a number by using a loop that iterates 3 times. ``` int n, cube, i; printf("Enter an integer: "); scanf("%d",&n); cube = 1; i = 0; while (i < 3) { cube = cube * n; i++; } printf("%d\n", cube); ```
Theunionkeyword in C confuses me. From what I have read, unions are used to store different types of data at the same memory address. How can one memory address store different amounts of data. For example, ``` union Data { int i; float f; char str[20]; }; ``` The memory occupied from this struct is 20 bytes. How can theint,floatandchararray hold values all at once in the same memory address?
How can unions store mutliple values in one memory address in C? They cannot and they don't. Only one of the union members is stored at any one time. Example: ``` union Data d = {.i = 42}; // d contains only i printf("%d\n", d.i); d.f = 3.145f; // d contains only f printf("%f\n", d.f); ```
I have an array of int pointers ``` int * arr[3]; ``` If I want to define a pointer toarr, I can do the following: ``` int * (*p)[] = &arr; ``` However, in my code, I need to first declare that pointer: ``` int *(*p)[]; ``` My question is, how to assign&arrto it after it has been declared. I have tried(*p)[] = &arr;but that didn't work.
You can simply dop = &arr. Tryhere.
I have a task that is to writemy_free()andmy_malloc()function. But how do we create epilogue and prologue to properly misalign header and footer? Supposedly we usesbrk()requries4096 bytesfrom the heap. Do I do ``` void* my_malloc(size_t size) { void* heapspace = sbrk(); heapspace += 8 // ?? Do i do this to create epilogue? } ```
``` heapspace += 8; ``` will not align anything. If you need 8 bytes alignment, and you add 8 to the unaligned address, the result will be the same unaligned. You need to: ``` void *align(void *ptr, unsigned alignment) { uintptr_t addr = (uintptr_t)ptr; if(addr % alignment) { addr = ((addr / alignment) + 1) * alignment; } return (void *)addr; } ``` ``` void* my_malloc(size_t size) { char* heapspace = sbrk(); heapspace += sizeof(size); //example header size heapspace = align(heapspace, 8); } ```
This question already has answers here:try to make a factorial program in C(2 answers)Closed1 year ago. Why does my code work correctly only when 12>=a ?? ``` int main() { int a ,x = 1; scanf("%d", &a); while (1 < a){ x = a * x; a = (a - 1); printf("\n %d", x); }; printf("\n %d", x); return 0; } ``` what i did is asking the pc to print the result of a*(a-1) in every line then it prints the final factorial result. And yes , the result is correct but not in all cases (from 13 and above it becomes wrong)
It is because factorial of 13 is greater than the holding capacity of int. So it cannot hold this value. try to use long variable here
I'm new to cmake and I was wondering how to create a static library. In gcc, it can be done by: ``` ar rsv ``` Well, how do you do it using CMake? ``` add_library(mylib STATIC file1.cpp file2.cpp) add_executable(myexe main.cpp) target_link_libraries(myexe mylib) ``` This generates a static library (.a file) but how do you compile it without adding an executable? if I remove add_executable(myexe main.cpp), it gives me an error. I only want this file: ``` mylib.a ``` and NOT ``` myexe.exe mylib.a ```
add_librarycan be used by itself, without usingadd_executableat all. Simply remove line 2 to get rid of the executable. The error is most likely caused by line 3, which needsmyexeto function. Line 3 should also be removed, because you are only building the library and not linking it.
regexpandsrcare both strings, andcountis a pointer to a counter used to scroll the string. It should get out as soon as']'is found inregexp, but it doesn't seem to be working. ``` int inParent(char *src, char *regexp, int *count) { int check = 0; printf("%d", *count); for (*count = 0; *(regexp + *count) != ']'; *count + 1) { if (*(regexp + *count) == *src) check = 1; } if (check == 1) return 1; return 0; } ```
Your count is not incrementing. ``` int inParent(char *src, char *regexp, int *count) { int check = 0; printf("%d", *count); for (*count = 0; *(regexp + (*count)) != '\0'; *count += 1) { if (*(regexp + (*count)) == *src) check = 1; } if (check == 1) return 1; return 0; } ```
I see that you can free char * pointers within struct but how do you free char[N] inside a struct ``` typedef struct Edge { char number[13]; int numOfCalls; struct Edge *next; } Edge; ``` When I do this i get an error ``` Edge *edge = malloc(sizeof(Edge)); edge->next = NULL; strcpy(edge->number,numberOne); // numberOne is also a char[13]; free(edge->number); free(edge); ```
If you use char array (char number[13]) in struct, you don't have tomallocorfreethe array. Once you domallocfor struct Edge, there is also space for number in memory. In summary, if you use char pointer as a member ofstruct Edge, you need tomallocorfreememory space for char pointer, but you don't have to do that in your case. Therefore, deletefree(edge->number)line.
I tried getting rid of spaces and newline characters but to no avail, it still asks for input twice. ``` #include <stdio.h> #include <math.h> int main() { double a = 0; double b = 0; double c = 0; //controls wether a is a number int controllo1 = 1; while (controllo1 = 1) { printf("insert x^2"); scanf("%lf", &a); getchar(); if (scanf("%lf", &a)) { getchar(); printf("input is a number\n"); controllo1 = 0; break; } else printf("input is not a number\n"); } } ```
The problem is that there are two scanf functions in the program, which understandably asks for input twice. Removing the one in line 12 will solve the issue.
This question already has answers here:Can a const variable be used to declare the size of an array in C?(5 answers)Closed1 year ago. ``` #include <stdio.h> const int TAILLE_MAX = 10; int iTableau[TAILLE_MAX]={3,6,0,8,97,0,5,6,0,8}; ```
const int TAILLE_MAX = 10;is not a compile-time expression in C, so it cannot be used as a compile-time array size. Replace the expression with a macro:#define TAILLE_MAX 10 See alsothis StackOverflow question.
I recently switched fromKeilµVisionto my own Makefile. I have an issue compiling a fileport.c, The function in the file: ``` __asm void vPortSVCHandler( void ) { PRESERVE8 /* Get the location of the current TCB. */ ldr r3, =pxCurrentTCB ldr r1, [r3] ldr r0, [r1] /* Pop the core registers. */ ldmia r0!, {r4-r11, r14} msr psp, r0 isb mov r0, #0 msr basepri, r0 bx r14 } ``` When compiling I get these errors: ``` ../port.c:52:7: error: expected '(' before 'void' 52 | __asm void vPortSVCHandler( void ) | ^~~~ | ( ../port.c:64:13: error: stray '#' in program 64 | mov r0, #0 ``` Am I missing an include or a compiler option?
You usegccand gcc does not have "asm" functions. You need to write it in the assembler or write the inline assembly.__asmis also not validgcckeyword. https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html
I tried getting rid of spaces and newline characters but to no avail, it still asks for input twice. ``` #include <stdio.h> #include <math.h> int main() { double a = 0; double b = 0; double c = 0; //controls wether a is a number int controllo1 = 1; while (controllo1 = 1) { printf("insert x^2"); scanf("%lf", &a); getchar(); if (scanf("%lf", &a)) { getchar(); printf("input is a number\n"); controllo1 = 0; break; } else printf("input is not a number\n"); } } ```
The problem is that there are two scanf functions in the program, which understandably asks for input twice. Removing the one in line 12 will solve the issue.
This question already has answers here:Can a const variable be used to declare the size of an array in C?(5 answers)Closed1 year ago. ``` #include <stdio.h> const int TAILLE_MAX = 10; int iTableau[TAILLE_MAX]={3,6,0,8,97,0,5,6,0,8}; ```
const int TAILLE_MAX = 10;is not a compile-time expression in C, so it cannot be used as a compile-time array size. Replace the expression with a macro:#define TAILLE_MAX 10 See alsothis StackOverflow question.
I recently switched fromKeilµVisionto my own Makefile. I have an issue compiling a fileport.c, The function in the file: ``` __asm void vPortSVCHandler( void ) { PRESERVE8 /* Get the location of the current TCB. */ ldr r3, =pxCurrentTCB ldr r1, [r3] ldr r0, [r1] /* Pop the core registers. */ ldmia r0!, {r4-r11, r14} msr psp, r0 isb mov r0, #0 msr basepri, r0 bx r14 } ``` When compiling I get these errors: ``` ../port.c:52:7: error: expected '(' before 'void' 52 | __asm void vPortSVCHandler( void ) | ^~~~ | ( ../port.c:64:13: error: stray '#' in program 64 | mov r0, #0 ``` Am I missing an include or a compiler option?
You usegccand gcc does not have "asm" functions. You need to write it in the assembler or write the inline assembly.__asmis also not validgcckeyword. https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html
``` `stuct` apple { int a; char c; }; struct b { int count; `stuct` apple a[10]; }; ``` How can implement these structures to a message field inprotobuffC. I am looking for a alternative method to write struct apple a[10] other than writing 10 times onprotobuff. Can you help me? Thanks!
Finally i get it. ``` message b { message apple { int32 a; string c; } int32 count; repeated apple a; } ``` This is the prototype message. Use vector implementation of dynamic arrays to use it.It will help to crate N no.of objects of a structure.
I am writing program that takes command line arguments but the first one is necessary and it is without a hyphen ("-"). Executing of application have to be: ``` ./program <server> [-d] [-n] ``` I tried to makeargv[1](in this case isserver) to be server but problem happens when server is somehow forgotten then it saves the option into server. How can I handle this or what should myoptstringlook like when first argument without a hyphen is needed?
If your argument is not preceded by '-' then getopt won't recognize it. You should handle the first argument by yourself doing something like this: ``` if (!(argc >= 2 && argv[1][0] != '-')) errx(1, "Usage: ./program <server> [-d] [-n]"); ``` And then you could use getopt as it will search for options that begin with '-' independently from the other values. If you want to handle-dand-noptions that do not take any value, your optstring should look like"dn".
``` #include <stdio.h> int main (int argc, char **argv) { FILE* file; char scratch[1024]; char filename[1024] = argv[1]; file = fopen( filename, "r" ); if( file != NULL ){ if( fgets( scratch, 1024, file ) != NULL ){ fprintf( stdout, "read line: %s", scratch ); } fclose(file); return 0; } } ``` Essentially if the user was to run ./nameOfTheProgram nameOfTheTextFile it should return the first line of the Text File I'm getting the following error: error: invalid initializer char filename[1024] = argv[1];
``` #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { ... your variables char *filename; if (argc>1) { filename = argv[1]; } else { fprintf(stderr, "need a filename\n"); exit(1); } ... your code return 0; } ```
``` #include <stdio.h> int main (int argc, char **argv) { FILE* file; char scratch[1024]; char filename[1024] = argv[1]; file = fopen( filename, "r" ); if( file != NULL ){ if( fgets( scratch, 1024, file ) != NULL ){ fprintf( stdout, "read line: %s", scratch ); } fclose(file); return 0; } } ``` Essentially if the user was to run ./nameOfTheProgram nameOfTheTextFile it should return the first line of the Text File I'm getting the following error: error: invalid initializer char filename[1024] = argv[1];
``` #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { ... your variables char *filename; if (argc>1) { filename = argv[1]; } else { fprintf(stderr, "need a filename\n"); exit(1); } ... your code return 0; } ```
Here's the lines of code in C: ``` void func_g(undefined4 pmt1) { int amt, elmt1; uint elmt3[3]; amt = __isoc99_sscanf(pmt1, "%d %d", elmt1, &elmt3); return; } ``` What __isoc99_sscanf trying to do?
isoc99_sscanf(and other related functions) were introduced in 2007 for compliance with theC99standard. As part of the introduction of the C99 support,"sscanf"is redirected to"__isoc99_sscanf".it is compiler specific syntax gcc uses it. This function return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.
In my compute, the function rand(); in C language outputs a 32-bit number. Is the following code will generate a random uint_8 number? Or it can be platform-dependent? ``` uint8_t var=(uint8_t) rand(); ``` I don't want to use modulo operation, due to time complexity of calculating modulo.
This code will indeed convert the return value ofrandto a value of typeuint8_t. The conversion happens by essentially truncating all but the lowest order 8 bits. As far as using the modulo operator, most compilers are smart enough to convert modulo by2nto a bitwise AND with a value with thenlower order bits set. Note that for simple uses this is fine, however if you want to generate random numbers suitable for cryptographic purposes, or if you want to ensure better random distribution, you should use a crypto library such as OpenSSL instead of therandfunction.
In my compute, the function rand(); in C language outputs a 32-bit number. Is the following code will generate a random uint_8 number? Or it can be platform-dependent? ``` uint8_t var=(uint8_t) rand(); ``` I don't want to use modulo operation, due to time complexity of calculating modulo.
This code will indeed convert the return value ofrandto a value of typeuint8_t. The conversion happens by essentially truncating all but the lowest order 8 bits. As far as using the modulo operator, most compilers are smart enough to convert modulo by2nto a bitwise AND with a value with thenlower order bits set. Note that for simple uses this is fine, however if you want to generate random numbers suitable for cryptographic purposes, or if you want to ensure better random distribution, you should use a crypto library such as OpenSSL instead of therandfunction.
How to convert anshorttounsigned char *bufin C ? I read my data ``` short read_raw_data(int addr) { short high_byte, low_byte, value; high_byte = wiringPiI2CReadReg8(fd, addr); low_byte = wiringPiI2CReadReg8(fd, addr + 1); value = (high_byte << 8) | low_byte; return value; } ``` and want to send it with ``` lws_write(struct lws *wsi, unsigned char *buf, size_t len, enum lws_write_protocol protocol); ``` like ``` m = lws_write(wsi, myShortConvertedToUnsignedChar + LWS_PRE, 32, LWS_WRITE_TEXT); ``` How to do this ?
Just use a cast to convert a pointer tovaluetounsigned char: ``` short value = ...; lws_write(wsi, (unsigned char*)&value, sizeof value, LWS_WRITE_TEXT); ```
I stumbled into this while solving an exercise: ``` void ft_striteri(char *s, void (*f)(unsigned int, char*)) { unsigned int i; if (!s || !f) return ; i = 0; while (s[i++]) f(i, s + i); } ``` Why doesn't the post increment in the while work while if i do this: ``` void ft_striteri(char *s, void (*f)(unsigned int, char*)) { unsigned int i; if (!s || !f) return ; i = -1; while (s[++i]) f(i, s + i); } ``` It works? I'm new and still very confused to the whole pointer concept is there any nuance here that I don't know about?
The problem is the match between the comparison and the function call.Consider the first iteration. In the first snippet it would be: ``` if(!s[0]) break; f(1, s + 1); ``` In the second snippet it would be: ``` if(!s[0]) break; f(0, s + 0); ```
I need a macro that takes input as MACRO(x, y, z, ...) and expands to arr[0] == x && arr[1] == y && arr[2] == z ... Any ideas? arr is char[], and macro args are single chars
Using boost preprocessor: ``` #include <boost/preprocessor.hpp> #define MACRO_AND(Z, N_, ARGS_) \ BOOST_PP_EXPR_IF(N_, &&) \ arr[N_] == BOOST_PP_TUPLE_ELEM(N_, ARGS_) #define MACRO(...) \ BOOST_PP_REPEAT( \ BOOST_PP_VARIADIC_SIZE(__VA_ARGS__), \ MACRO_AND, \ (__VA_ARGS__)) ``` This usesBOOST_PP_REPEATto iterate the variadic arguments, feeding them in as a tuple via the data parameter.BOOST_PP_EXPR_IFprefixes the&&for all but the 0th argument. Boost preprocessor is a header only library and can be used with C. Demo (on coliru)here. FYI, be very careful... I'm not sure how you're going to use this for generic string inputs (e.g. if the NUL terminator comes up during the comparison).
I have this annoying warning when I go to compile my code. I'm trying to take achar *and convert it to lower case before I run it through a test. My code compiles just fine but I want to learn how to get rid of this warning. Other posts with this same error don't provide me with what I need to change to remove this error. ``` //convert to lower case char *c = "WORD TO LOWER"; char *s[testWordLen]; for (int i = 0; i < testWordLen; i++) { s[i] = tolower((unsigned char) c[i]); } ``` An explanation of what I'm doing wrong would be great too.
You are creating a two-dimensional array usingchar *s[testWordLen];; that is, a pointer to an array of chars. When you dereference it like this:s[i] = tolower((unsigned char) c[i]);, you assign a single character to an array. The fix is this: declare the variable aschar s[testWordLen];
Im trying to use sizeof() to find the size of the value a void pointer is pointing at, I want to use it to print the value. this code ``` int num = 5; void *voidPtr; voidPtr = &num; printf("%d", sizeof(*voidPtr)); ``` Prints, 1. How can i get it to print 4? If theres any other way to print the value of the void pointer, please let me know Thanks in advance.
The value of pointer merely conveys the starting address of an object, not any information about its size. The type of a pointer inherently conveys information about the size of the object it points to, if it is a complete type. However,voidis incomplete, and avoid *provides no information about the size of the object it originated from (except possibly by extensions to standard C and by debugging features). Generally, if your program needs to know the size of what avoid *points to, it must track that information itself.
In a C program:1 || 0 && 0results in1. I thought this behavior as the OR operator has short-circuited rest of the right side (0 && 0) because of1on the left side. But0 && 0 || 1also results in1. I am confused why0on the left side of AND operator has not short circuited0 || 1and the answer is not0. Please guide me!
This has to do withoperator precedence. The logical AND operator has higher precedence than the logical OR operator ||. So this: ``` 1 || 0 && 0 ``` Parses as: ``` 1 || (0 && 0) ``` And this: ``` 0 && 0 || 1 ``` Parses as: ``` (0 && 0) || 1 ``` So in the latter case, first0 && 0is evaluated. This results in the value 0, so now you have0 || 1. The left side of the OR is false so this causes the right side to be evaluated, causing the||operator to result in 1.
I am currently studying C language. I was studying Datatypes, please tell me, why characters are called integral constants?
You may perform integer operations with objects of the typechar. For example you may decrease or increase a value stored in an object of the type char, or add or subtract a value. For example if an object of the type char contains a symbol that represents a digit as for example ``` char c = '5'; ``` then you can get the digit as a number the following way ``` int digit = c - '0'; ``` The variable digit will contain the number5. Pay attention to that the typecharcan behave either as the typesigned charorunsigned chardependent on compiler options. In C opposite to C++ integer character constants have the typeint.
I'm trying to compile the sample bpf program in Linux source code. So I downloaded the current kernel source code and enteredsamples/bpffolder ``` apt source linux cd linux-*/samples/bpf ``` Then I tried to compile a sample program with gcc: ``` # gcc sock_example.c sock_example.c:29:10: fatal error: bpf/bpf.h: No such file or directory 29 | #include <bpf/bpf.h> | ^~~~~~~~~~~ compilation terminated. ``` And I'm unable to findbpf/bpf.hwithapt-file ``` # apt-file find bpf/bpf.h (no output) ``` What was wrong?
You need to installlibbpf: ``` git clone --depth 1 https://github.com/libbpf/libbpf cd src sudo make install ```
C++ has a neat feature where you can create an object at a specific memory address asshown here. This is particularly useful withmmaplike so: ``` void *ptr = mmap(0, length, prot, flags, fd, offset); A *ptrA = new (ptr) A; ``` What is the correct way to replicate this with just C-style structs? Would it just be this? ``` void *ptr = mmap(0, sizeof(A), prot, flags, fd, offset); A *ptrA = (A*) ptr; ```
This is valid because no memory usage constraints are enforced in C. ``` void *ptr = mmap(0, sizeof(A), prot, flags, fd, offset); A *ptrA = (A*) ptr; ```
if i input "1k"(or any number followed by letters) into scanf at this configuration i still get a true (non 0) returned from the function, is there any way to explicitly return false if anything but integers are present? basically i wanna know if my string is only numbers or not p.s. legal switch checks if my input is one of a few given options ``` void clearBuffer() { while (getchar() != '\n') {} } int getChoice(){ int choice = 0; //clearBuffer(); while (scanf("%d",&choice)!=0 ||!legalSwitch(choice)) { clearBuffer(); printf("\nWrong choice, please choose an integer between 1 to 3: "); } } ```
You may want to read an entire line usingfgets(always check the return value), then useif (sscanf(line, "%d%n", &choice, &size) >= 1 && size == strlen(line))(see alsosscanf). Alternatively, instead ofsscanfyou can usestrtoulorstrtoull.
How do i get this snippet of code to break the while loop with both "a" and "A"? I can't get the OR function right. Thanks in advance for the help. while((product = getchar()) !='a')
If you want to break the loop whenproductisaorA, you need to check ifproductis notaandnotAin your loop condition: ``` while((product = getchar()) !='a' && product != 'A') ```
Using this meson file, ``` project('mytest', 'c') cc = meson.get_compiler('c') deps = [] deps += dependency('sdl2', required: true, static: true, method: 'pkg-config') executable('demo', 'src/main.c', dependencies : deps, gui_app: true) ``` I get the following error ``` error LNK2019: unresolved external symbol WinMain referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ) ``` This seems to be related to theSDLmain.lib(I'm sure it exist).How would you force the linker to link to this library? I'm on windows 10, using the MSVC compiler.
You're building a gui app, not a terminal app. With MSVC, when you setgui_app : true(or in more recent versions of mesonwin_subsystem : 'windows') you don't provide amainfunction, you provideWinMainfunction instead. See the MSDN documentation Under the hood this option is passing/SUBSYSTEM:WINDOWSto the compiler
I came across code similar to this in theARM CMSIS-NN library: ``` int32_t val, shift; // code that initializes val and shift int32_t result = val * (1 << shift); ``` which aims to multiplyvalby some power of two valuex, withshiftbeing the exponent, i.e.x=pow(2,shift). Why are they not simply shifting? Like so ``` int32_t result = val << shift; ``` Is there something special that I am missing? Can the compiler optimize the former operation in some special way? EDIT: What confuses me is that they are using "simple shifts" throughout the code. Additionally, the code should be highly optimized. But I guess modern compilers will figure out by themselves, that shifting is the way to go (instead of multiplying)?
It is always sign correct and forces the use of the proper FPU instructions and works with any type of data.
When I compile the extension I've got, I'm getting ``` error: ‘work_mem’ undeclared (first use in this function) 17 | Tuplestorestate *tupstore = tuplestore_begin_heap(true, false, work_mem); ``` What header includeswork_mem?
Thework_memsymbol is provided bymisadmin.hyou will have to add that header into your.cfile. ``` #include "miscadmin.h" ```
Using this meson file, ``` project('mytest', 'c') cc = meson.get_compiler('c') deps = [] deps += dependency('sdl2', required: true, static: true, method: 'pkg-config') executable('demo', 'src/main.c', dependencies : deps, gui_app: true) ``` I get the following error ``` error LNK2019: unresolved external symbol WinMain referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ) ``` This seems to be related to theSDLmain.lib(I'm sure it exist).How would you force the linker to link to this library? I'm on windows 10, using the MSVC compiler.
You're building a gui app, not a terminal app. With MSVC, when you setgui_app : true(or in more recent versions of mesonwin_subsystem : 'windows') you don't provide amainfunction, you provideWinMainfunction instead. See the MSDN documentation Under the hood this option is passing/SUBSYSTEM:WINDOWSto the compiler
I came across code similar to this in theARM CMSIS-NN library: ``` int32_t val, shift; // code that initializes val and shift int32_t result = val * (1 << shift); ``` which aims to multiplyvalby some power of two valuex, withshiftbeing the exponent, i.e.x=pow(2,shift). Why are they not simply shifting? Like so ``` int32_t result = val << shift; ``` Is there something special that I am missing? Can the compiler optimize the former operation in some special way? EDIT: What confuses me is that they are using "simple shifts" throughout the code. Additionally, the code should be highly optimized. But I guess modern compilers will figure out by themselves, that shifting is the way to go (instead of multiplying)?
It is always sign correct and forces the use of the proper FPU instructions and works with any type of data.
When I compile the extension I've got, I'm getting ``` error: ‘work_mem’ undeclared (first use in this function) 17 | Tuplestorestate *tupstore = tuplestore_begin_heap(true, false, work_mem); ``` What header includeswork_mem?
Thework_memsymbol is provided bymisadmin.hyou will have to add that header into your.cfile. ``` #include "miscadmin.h" ```
I made a web service in LPC 1768 and I also have 2Mb Flash storage in my board (IC is AT45db160),which, I used it for saving variables. Now I want to return all variables in Flash as an Excel file. I used a SD card for my FTP unit. compiler is KEIL (implemented by RL-ARM). board designed by my company which includes a USB device, Ethernet port, Flash IC and SD card slot.
you can have a storage in RAM or FLASH . for more information read upitand after that I can make a file in FLASH for creating report file.
Why this code doesn't printА? ``` int main() { char str[] = {0x0, 0x4, 0x1, 0x0}; write(1, str, 4); } ``` Instead ofAit just print nothing and exit. This is strange because hexadecimal value ofAisU+0410.
Follow this answerhttps://stackoverflow.com/a/6240184/14926026, you will see that the cyrillic A is not{0x0, 0x4, 0x1, 0x0}, but actually{ 0xd0, 0x90 } ``` int main() { char str[] = { 0xd0, 0x90 }; write(1, str, 2); } ```
Say you call spin_lock(&key) and key is having some type of operation being performed on it in a different thread at the same time. Is the other thread being paused/interrupted? What happens to the other thread that's in the middle of altering or using key? Such as if the thread was calling copy_to_user(key), copy_from_user(key) or kmallocing/kfreeing key?
Don't know specifically aboutLinux kernelspin_lock(), but in practically all programming environments,mutex locking isadvisory. That means, locking a lock never preventsanythingexcept, it prevents other threads from locking the same lock at the same time. If you want to use a lock to protect some variable or data structure, then it's entirely the programmer's responsibility to ensure that no code anywhere in the system ever accesses the data except when the lock is locked.
enter image description here how can I do this using scanf funtion ranging form -1000 to 1000 ? just %d numbers
Try dooing a loop with ascanfand aprintfinside, like this: ``` int num = 0; for(int i = 0; i < 5; i++){ scanf("%d", &num); printf("%d", num); } ``` You just need to change the5to the number of iterations you need.
Say you call spin_lock(&key) and key is having some type of operation being performed on it in a different thread at the same time. Is the other thread being paused/interrupted? What happens to the other thread that's in the middle of altering or using key? Such as if the thread was calling copy_to_user(key), copy_from_user(key) or kmallocing/kfreeing key?
Don't know specifically aboutLinux kernelspin_lock(), but in practically all programming environments,mutex locking isadvisory. That means, locking a lock never preventsanythingexcept, it prevents other threads from locking the same lock at the same time. If you want to use a lock to protect some variable or data structure, then it's entirely the programmer's responsibility to ensure that no code anywhere in the system ever accesses the data except when the lock is locked.
enter image description here how can I do this using scanf funtion ranging form -1000 to 1000 ? just %d numbers
Try dooing a loop with ascanfand aprintfinside, like this: ``` int num = 0; for(int i = 0; i < 5; i++){ scanf("%d", &num); printf("%d", num); } ``` You just need to change the5to the number of iterations you need.
I have file filled with rows of data: each row contains:'char' space 'double'. e.g: ``` a 17.322\n c 9.45\n ``` I want to 'eat' the \n and the char, and read only the double number. what is the best way to do it. thanks, and sorry if I have English mistakes
I think simplefscanfcan do the job ``` #include <stdio.h> int main() { FILE* f = fopen("test", "r"); float n; while(fscanf(f, "%*[a-z]%f ", &n) == 1) printf("%f, ", n); return 0; } ``` "%*"ignores everything it reads"[a-z]"reads characters from range 'a' to 'z'"%f"reads a single precision floating point number (in other wordsfloat)" "ignores allwhitespace charactersfscanfreturnsEOFin case of reading error (ex. end of file) ornumber of read valueswhich in our case is 1
On Linux, I have to callwait()afterfork()on the parent process, otherwise the child process will stay zombie after completion until the parent process completes. I wonder whether I must follow similar steps on Windows,i.e. whether ImustcallWaitForSingleObject()after callingCreateProcess(). I know that Windows'CreateProcess()is different from Linux'sfork()and it seems that 'zombie' is a UNIX/Linux concept that does not exist on Windows. But maybe I still must callWaitForSingleObject()to free some OS resources allocated forCreateProcess(), similar to the Linux case.
IfCreateProcesssucceeds you must close the two handles inPROCESS_INFORMATIONbut you don't have to wait for the child process first, the handles can be closed at any point if you don't need them. A open handle to a process will keep the process object alive in a zombie state after it has finished running.