question
stringlengths
24
425
answer
stringlengths
5
405
``` printf("%f %.3f %.2f %.1f", 4.5678, 4.5678, 4.5678, 4.5678); ``` I tried putting \n at the end of the series of floats to separate the line ``` printf("%f %.3f %.2f %.1f", 4.5678, 4.5678, 4.5678, 4.5678)\n; ```
That \n should be inside the strings of printf not after it ``` printf("%f %.3f %.2f %.1f \n", 4.5678, 4.5678, 4.5678, 4.5678); ```
I am usingntdll.libfunctions in my code to set the system timer to a higher resolution. But when I build my project I get this error: ``` ... .../bin/ld.exe: ... undefined reference to `__imp_NtSetTimerResolution' collect2.exe: error: ld returned 1 exit status ... ``` How do I tell the linker to link withntdll.libin my CMake?
This worked for me: ``` if (WIN32) target_link_libraries(executable ntdll) endif() ```
There are two floating point numbers 23.54 and 33.22 have to make a program to add them with just left side integral value like 23+33=56. Here's the code that I tried:
``` int sum; sum=(int)num1+(int)num2; printf("%d",sum); ``` or ``` printf("%d",(int)num1+(int)num2); ``` The datatype of num1 is float and I'm using (int) to typecast to integer type.Since we typecast the datatype this is called explicit typecasting!
There are two floating point numbers 23.54 and 33.22 have to make a program to add them with just left side integral value like 23+33=56. Here's the code that I tried:
``` int sum; sum=(int)num1+(int)num2; printf("%d",sum); ``` or ``` printf("%d",(int)num1+(int)num2); ``` The datatype of num1 is float and I'm using (int) to typecast to integer type.Since we typecast the datatype this is called explicit typecasting!
when I run the command ``` pidof lh ``` for lh program, I get two values. what are they. I was looking of pid oflhrunning program so I can increase the number of open files limithttps://unix.stackexchange.com/a/422732/211761 Why i am getting two values, if one is pid then what is the other OUTPUT ``` 37354 7968 ``` which one above is pid and what is the other number. please tell
Both. You have two lh processes running.
From thispostand thiscodebase, I know that there are pointers for Youngest childYoungest siblingOldest sibling. So withOldest child, how do I get? I am thinking of access "children" pointer (current->children) and traverse to the end of that doubly linked list.
Get the oldest sibling of the youngest child: ``` current->p_cptr->p_osptr ```
I have a code that uses std=c++20. I want to use a C library that was build with old gcc version. Should I recompile the C library using the same compiler ? If no, how could you judge that the 2 ABIs are compatible?
There should be no problem using the library as it is. Don't forget to addextern "C"around the function prototypes. More info:Using C Libraries for C++ Programs
From thispostand thiscodebase, I know that there are pointers for Youngest childYoungest siblingOldest sibling. So withOldest child, how do I get? I am thinking of access "children" pointer (current->children) and traverse to the end of that doubly linked list.
Get the oldest sibling of the youngest child: ``` current->p_cptr->p_osptr ```
I have a code that uses std=c++20. I want to use a C library that was build with old gcc version. Should I recompile the C library using the same compiler ? If no, how could you judge that the 2 ABIs are compatible?
There should be no problem using the library as it is. Don't forget to addextern "C"around the function prototypes. More info:Using C Libraries for C++ Programs
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 I want to know how can I see the functions and the contents of a library in C language?
isnm libconfig.a | c++filtwhat you are looking for?
I am programming a microcontroller (PSoC5), which doesn't have a system time. What is the best way to generate a seed to initializesrand? TIA
If the chip has ADCs, one option is to take advantage of noise picked up on the ADCs. Basically, you can take a few reads of the ADCs, then bitwise AND to keep the least significant bit. Then use the all of the least significant bits sampled to generate your seed.
I'm doing a shell from scratch. If I store all tokens in an arraychar**, what I supposed to put in a string of arraychar**when quote is empty? Example: ``` input>echo "" "" "" | cat -e output>(space)(space)(space)$ ```
If you're mimicking POSIX shells then each""would tokenize to an empty string. The pipeline as a whole should tokenize to: ``` char *tokens[] = {"echo", "", "", "", "|", "cat", "-e"}; ```
This question already has answers here:Splitting string into two integers(4 answers)Closed2 years ago. ``` string input = 1999-12-05 int year=1999 int month=12 int day=05 ``` I want to split input to new three variable.Thank you.
You can usesscanf: ``` char* input = "1999-12-05"; int year; int month; int day; sscanf(input, "%d-%d-%d", &year, &month, &day); printf("year: %d, month: %d, day: %d\n", year, month, day); ``` demo
I want to read the source code of winsock, but I only see header which is winsock.h. where is winsock.c located I need to read the source code implementation so bad.
As to my knowledge Microsoft never released source code for that library. The best you can do is use Ida pro or simillar software to decompileWs2_32.dllorWs2_32.lib. That is the closest you will get to the source code, but it will be in pseudo C.
``` union one { int *ui; int u; } yoo; void main() { printf("%d\m", sizeof(yoo)) } ``` Why is the sizeof union not 8 bytes but 4 bytes even if I am using pointer in my union? I am using a 64 bit machine.
Its because you have compiled it as 32-bit executable.
I want to do something similar to the code below but usingptr[i] ``` printf("%s\t%d\n", (ptr + i)->subject, (ptr + i)->marks); ```
ptr->xis the same as(*ptr).x. *(ptr + i)is the same asptr[i]. Thus, by the transitive property,(ptr + i)->xis the same as: ``` ptr[i].x ```
I want to do something similar to the code below but usingptr[i] ``` printf("%s\t%d\n", (ptr + i)->subject, (ptr + i)->marks); ```
ptr->xis the same as(*ptr).x. *(ptr + i)is the same asptr[i]. Thus, by the transitive property,(ptr + i)->xis the same as: ``` ptr[i].x ```
I am wondering what happens for variables & their content after STM32 mcu enters low power mode or exit from it? for example in sleep mode or standby. do their content remove or survived? best!
You can preserve or not - it is usually (depending on the mode) up to the programmer. Memory consumes power so very often it is more energy efficient to reinitialize RAM after wake up (I do it sometimes in my projects) Example: STM32L476:
I'm working with a C-functionfoo(FILE* file)that outputs some text to a file. Rather than write to a .txt file, I'd likefooto write to the console. Is there a way to pass 'the console' as a FILE*? (And if so, how) ? (foois part of a library and I can't edit the source code directly)
There's a special file object calledstdoutthat will write to the console (assuming the shell didn't redirect anything). ``` foo(stdout); ```
I'm working with a C-functionfoo(FILE* file)that outputs some text to a file. Rather than write to a .txt file, I'd likefooto write to the console. Is there a way to pass 'the console' as a FILE*? (And if so, how) ? (foois part of a library and I can't edit the source code directly)
There's a special file object calledstdoutthat will write to the console (assuming the shell didn't redirect anything). ``` foo(stdout); ```
My Code:- ``` #include<stdio.h> struct Demo{ int value; }; int main(){ struct Demo *l; l->value=4; } ``` Getting Segmentation fault (core dumped)
because L object doesn't point something. use this : ``` #include <iostream> using namespace std; struct Demo { int val; }; int main() { Demo* a = new Demo(); a->val = 10; cout<<a->val; } ```
why my code is not printing all values of the array? ``` #include<stdio.h> #include<conio.h> int main() { int arr[5]={1,2,3,4,5}; int *a; a=&arr[0]; int i=0; for(i=arr[i];i<5;i++){ printf("%d",*a); a=a+1; } } ```
I guess this is homework, correct? Check the index of your loop. What you want to do is that yourforloops five times, regardless of the content of your array.
Why 10.5 become 10.0 after swap ? ``` #define swap(a,b) {int aux; aux=a; a=b; b=aux;} float x=10.5, y=3.75; swap(x,y); // x=3.75, y=10.0; ```
auxis of typeint, which will drop the decimal part of the argumentapassed toswap. In this case,swap(x, y)drops the decimal part ofxbefore it is assigned toyat the end.
Why 10.5 become 10.0 after swap ? ``` #define swap(a,b) {int aux; aux=a; a=b; b=aux;} float x=10.5, y=3.75; swap(x,y); // x=3.75, y=10.0; ```
auxis of typeint, which will drop the decimal part of the argumentapassed toswap. In this case,swap(x, y)drops the decimal part ofxbefore it is assigned toyat the end.
Let's imagine I have ``` String x = "hello there"; ``` So I can print it from index e.g. 1 as: ``` Serial.println(x.substring(1)); ``` ello there I wanna do the same with ``` char x[] = "hello there"; ``` Any ideas?(Except using loops to print char by char)
You can use the & operator to get the string after the desired index like this: ``` Serial.println(&x[1]); ```
For debugging purposes, when there are many make file inclusions, it's useful to print the full path of the makefile where a particular variable in the current makefile was first defined. Is there a way to do that?
Just runmake -p. Make will print its internal database including all targets and variables that were seen along with the filename and linenumber where they were set.
given that ``` int w = 1; int x = 6; int y = 5; int z = 0; z = !z || !x && !y; printf("%d\n", z); z = x-- == y + 1; printf("%d\n", z); ``` Could someone explain how the line below would evaluate to 1 if x-- is 5 and y+1 is 6? ``` z = x-- == y + 1; ```
The expressionx--evaluated to the value ofxbeforebeing decremented. Sox-- == y + 1is the same as6 == 5 + 1which is true, then the value 1 is assigned toz.
given that ``` int w = 1; int x = 6; int y = 5; int z = 0; z = !z || !x && !y; printf("%d\n", z); z = x-- == y + 1; printf("%d\n", z); ``` Could someone explain how the line below would evaluate to 1 if x-- is 5 and y+1 is 6? ``` z = x-- == y + 1; ```
The expressionx--evaluated to the value ofxbeforebeing decremented. Sox-- == y + 1is the same as6 == 5 + 1which is true, then the value 1 is assigned toz.
I am a bit rusty in programming, so I came here to ask what's the meaning of this line? ``` int (*f)(int, int) ```
Usehttps://cdecl.org/to translate thigs like that. int (*f)(int, int)=> declare f as pointer to function (int, int) returning int.
If I put an inline function in a .h file, then include that in the bridging header, can I invoke it in Swift? (Answer: Yes) But will it still be inline when invoked in Swift?
The compiler will do what it wants but generally the answer isyes. This is part of why the atomics libraries and math shims that go down to C use header only inlined modules. So at least in release builds it can be fully optimized. Seethisfor example.
Using clang or clang++ the command ofclang -S -emit-llvm ./source.cwill create a llvm ir document. However debugging information is missing. So when you test and compile things you lose debugging information. How does one can make clang emit human readable llvm ir document with debug information ?
The standard option to add debug info is-g. So, runningclang -g -S -emit-llvm source.cwill emit necessary information
Using clang or clang++ the command ofclang -S -emit-llvm ./source.cwill create a llvm ir document. However debugging information is missing. So when you test and compile things you lose debugging information. How does one can make clang emit human readable llvm ir document with debug information ?
The standard option to add debug info is-g. So, runningclang -g -S -emit-llvm source.cwill emit necessary information
Imagine I havefile1.c,file2.c. First I compile one file withgcc -c file1.c -o file1.o. Is it OK to compile them together withgcc file1.o file2.c -o prog? I tried it and no errors are shown, but should I compilefile2.ofirst? Is it correct to mix.cand.ofiles?
Yes, you can dogcc file1.o file2.c -o prog. You can also dogcc file1.c file2.c -o prog. GCC will handle compiling file2.c behind the scenes.
I'm getting the following error message from Clang 10: ``` error: expected value in expression #if FOOBAR ^ 1 error generated. ``` No further info. What could be the cause for this?
What could be the cause for this? When the macro is defined to nothing ``` #define FOOBAR ``` then ``` #if FOOBAR ``` expands to just: ``` #if ``` And compiler prints an error -ifneeds an expression#if something-here.
if I write data to the middle of the allocated address space, will the file size increase. just likefseekdoes ? or it will write to the beginning of the file ?
The answer is no. writeto mmap will not grow the file or create sparse file. I have to allocate the file manually.
In my rooted Android device, ``` jint fd = open("/dev/ashmem",O_RDWR); ``` gives -1 and fopen results in error 13. I've tried changing the permissions as well with chmod 777, but to no avail. Any ideas? Thank you for your help.
Apps targeting Android 10 cannot directly use ashmem (/dev/ashmem) and must instead access shared memory via the NDK’s ASharedMemory class
In my rooted Android device, ``` jint fd = open("/dev/ashmem",O_RDWR); ``` gives -1 and fopen results in error 13. I've tried changing the permissions as well with chmod 777, but to no avail. Any ideas? Thank you for your help.
Apps targeting Android 10 cannot directly use ashmem (/dev/ashmem) and must instead access shared memory via the NDK’s ASharedMemory class
I have a problem when comparing wchar_t with hex value. ``` wchar_t c; FILE *f = fopen("input1.txt", "r"); fwscanf(f, L"%lc", &c); // c is 'ệ' printf("%d", c == L'\0x1ec7'); ``` 'ệ' is 0x1ec7 hex. But the result is 0. And how to compare wchar_t with hex value?
The correct notation isL'\x1ec7', notL'\0x1ec7': ``` #include <stdio.h> int main() { wchar_t const c = L'ệ'; printf("%d", c == L'\x1ec7'); // prints 1 } ```
Like ``` pri ntf("hi"); ``` I can use \ in macro but I think that doesn't work here :'(
You can use\ ``` pri\ ntf("hi"); ``` Demo From draft N1570 of the C standard, section 5.1.1.2 Translation phases: Each instance of a backslash character ( \ ) immediately followed by a new-line character is deleted, splicing physical source lines to form logical source lines.
I need to create a matrix with 2 columns and unknown number of rows. I know I have to use malloc but I can't find how to declare such matrix. it should hold integers in the first column and doubles in the second. How do I do that?
``` struct item { int i; double d; }; struct item matrix = malloc(sizeof(struct item) * number_of_rows) matrix[0].i = 544343; matrix[0].d = 0.3434343; ``` Is that the code you are looking for?
I need a macro that puts "**" before and after the string value, it should work someway like this: ``` #define M(x) <something> puts(M("abc")) ``` Output: ``` **abc** ``` I've tried things like ``` #define M(x) "**x**" ``` but it doesn't work :/Thanks in advance! :)
Try ``` #define M(x) "**" x "**" ``` It uses a feature that C compiler concatenates sequence of string literals.
if I have two header files a.handb.h can I include "a.h" in b.h and also include "b.h" in "a.h" ?
You can, but it's not a very good idea. If you really must, you can prevent recursion with the use of include guards (which are a good idea regardless). Ina.h: ``` #ifndef A_H #define A_H #include "b.h" #endif ``` andb.h ``` #ifndef B_H #define B_H #include "a.h" #endif ```
How to call an executable C in script shell ? I did echoname_of_executable_filebut it didnt works
You call it like this: ``` /path/to/name_of_executable_file ``` Or if it's in the current directory, like this: ``` ./name_of_executable_file ```
How to get RI pin status of serial port on a windows platform? I want to read the current state (ON or OFF) , when i get a call on a modem I can set the DTR pin with : EscapeCommFunction(hSerial,SETRTS); But cant find an answer online on how to check the RI pin STATUS
You have to useGetCommModemStatusfunction.
How to get RI pin status of serial port on a windows platform? I want to read the current state (ON or OFF) , when i get a call on a modem I can set the DTR pin with : EscapeCommFunction(hSerial,SETRTS); But cant find an answer online on how to check the RI pin STATUS
You have to useGetCommModemStatusfunction.
``` float lgt = light.read(); if(isnan(lgt)){ printf("Failed to read light!"); } else{ printf("%f\n",lgt); } ``` Second printf always print '%f' in the console instead of 'lgt' value. Why could this happen? I'm using Mbed Studio.
Why floating point formats in Mbed Studio don't work? Because you are compiling your program with newlib nano version that does not support floating point format inprintffamily.
``` float lgt = light.read(); if(isnan(lgt)){ printf("Failed to read light!"); } else{ printf("%f\n",lgt); } ``` Second printf always print '%f' in the console instead of 'lgt' value. Why could this happen? I'm using Mbed Studio.
Why floating point formats in Mbed Studio don't work? Because you are compiling your program with newlib nano version that does not support floating point format inprintffamily.
I use C language and I have problem with malloc ``` double** matrix = malloc(matrixSize * sizeof(double*)); for (size_t i = 0; i < matrixSize; i++) { matrix[i] = malloc(matrixSize * sizeof(double)); } return matrix; }` ```
malloc returns a void-pointer void*malloc(size_t size); so you will have to typecast this to double** ``` double** matrix = (double**)malloc(matrixSize * sizeof(double*)); ```
As mentioned by the title, I would like to achieve something like this: ``` void my_exit(int status) { #ifdef _GCOV __gcov_flush(); #endif _exit(status); } ``` But I do not know if there is a_GCOV(or something similar) defined when compiling with--coverage. Any idea will be appreciated!
Doesn't seem to be: ``` $ true | gcc -E - -dM > no-coverage.h $ true | gcc -E - -dM --coverage > coverage.h $ diff no-coverage.h coverage.h ```
``` void Setup() { gameover = false; dir = STOP; x = width / 2; y = height / 2; fruitX = rand() % width; //display fruit in a random place fruitY = rand() % height; score = 0; } ```
Please use#include <stdlib.h>at the top of c code.
We have the variablea, that is the typechar*, that storeschars in an array. How are*(a + 2)anda[1]related? a[1]points to the second element in the array and*(a + 2)points to the second element following the element pointed at to bya. So would the values of these two be the same?
These arenotthe same. The syntaxE1[E2]is exactly equivalent to*((E1) + (E2)). So*(a + 2)is the same asa[2]. It should now be clear that this is not the same asa[1].
We have the variablea, that is the typechar*, that storeschars in an array. How are*(a + 2)anda[1]related? a[1]points to the second element in the array and*(a + 2)points to the second element following the element pointed at to bya. So would the values of these two be the same?
These arenotthe same. The syntaxE1[E2]is exactly equivalent to*((E1) + (E2)). So*(a + 2)is the same asa[2]. It should now be clear that this is not the same asa[1].
I am using windows 10 and MinGW-x64 gcc 8.1.0. I was trying to take a long double as input using scanf. Here is the code: ``` #include<stdio.h> #include<stdlib.h> int main(int argc, char const *argv[]) { long double a; scanf("%Lf",&a); printf("%Lf",a); return 0; } ``` the output on the console is 0.000000. Why is that so? Is it a windows issue?
i guess in c mingw does not support long double datatype
I need to save a user input into a 2D array in a way where the user inputs something like '123456789' and I save that input into an array so that array[0][0] == 1, array[1][2] == 6 etc. Is there something like getchar() that I could use, but for numbers?
You can use getchar() itself, and convert it to integer using: ``` char c = getchar(); int arr[3][3]; arr[0][0] = c - '0'; ``` Referthisstackoverflow answer.
I know that a pointer points to a memory address, but is it possible to just use the&symbol instead of a pointer?
&vwill get you the address of the variablev, but&vis an r-value, not an l-value. In order to have an l-value containing the address of a variable you would have to use the*syntax, as inT *p = &v;.
I want to calculate a number to the powerp, gotSegmentation faultas a result. This code is supposed to work: ``` #include <stdio.h> int my_power(int nb, int p) { if (nb != 0){ return nb*my_power(nb, p-1); } return 1; } int main(int argc, char argv[]){ printf("%d\n", my_power(5, 3)); return 0; } ```
In your code, your recursion never ends. Change the base case topb<=0and it will work.
I am trying to deep copy from one structure to another structure However structure has many pointers,how do I copy it in single statement? Do I have to manually copy each structure pointer member?
You have to manually copy everything if you want a deep copy.
Follow-up question forthisanswer. Is there any hosted C implementations (__STDC_HOSTED__is 1) which haveCHAR_BIT > 8? If so, then which ones? UPD. Fix typo: before:__STDC_HOSTED__is0, after:__STDC_HOSTED__is1.
I don't know if there was ever a post-standardisation version, but various Cray 64-bit vector supercomputers had a C compiler in whichsizeof(long) == sizeof(double) == 1, a.k.a.everything is 64 bits wide.
``` #include <stdio.h> int main() { if (~0 == 1) printf("yes\n"); else printf("no\n"); } ``` why is theifstatement false? can anyone explain?
~Binary One's Complement Operator is unary and has the effect of 'flipping' bits. So when you do~0 == 1it will check for-1 == 1which is false
I'm trying to format a string like this: ``` printf("%d%c", buffer[i], i == num_ints-1? '': ','); ``` So that the numbers print like this: ``` 123,929,345 ``` Yet doing''is invalid. Is it possible to simulate a 'nothing-char' or just not do anything in the ternary?
You can't have an empty char, but you can have empty strings. So use%s. ``` printf("%d%s", buffer[i], i == num_ints-1? "": ","); ```
I see that when I use that code: ``` char c,d; scanf("%s",&c); scanf("%s",&d); printf("%c%c",c,d); ``` seems fix the problem of save ENTER character indvariable. It's a good way or compiler add the string terminator in the memory address next tocvariable (equals fordvariable)?
No, because it will also want to null-terminate the string. In other words, write to*(d + 1)(at least!), and that's undefined behavior (namely, overflow).
i am trying to find out how the Number of expected bytes is calculated with Function Code 2 in Modbus RTU. I am querying registers from 0 to 71, but as a response i am getting expected bytes as 9 Below is the Query and response. query : 33 02 00 00 00 47 3C 2A resp : 33 020900 08 00 FE FF FF FF FF 03 FA 68
You queried for 71 bits, the response has 9 bytes containing 8 bits per byte, any excess bits are ignored.
i am trying to find out how the Number of expected bytes is calculated with Function Code 2 in Modbus RTU. I am querying registers from 0 to 71, but as a response i am getting expected bytes as 9 Below is the Query and response. query : 33 02 00 00 00 47 3C 2A resp : 33 020900 08 00 FE FF FF FF FF 03 FA 68
You queried for 71 bits, the response has 9 bytes containing 8 bits per byte, any excess bits are ignored.
This is the algorithm to retrieve values from a2D array, what will be thetime complexityof this algorithm? ``` for(i=0;i<n;i++){ for(j=0;j<2;j++){ x = arr[i][j] } } ``` So thetime complexityof this algorithm would beO(2n)orO(n^2)? What is thereason?
Outer loop is iterating n times, but inner loop is iterating only two times, So time complexity will be O(2n) and not O(n^2). And ``` O(2n) = O(n) ```
This is the algorithm to retrieve values from a2D array, what will be thetime complexityof this algorithm? ``` for(i=0;i<n;i++){ for(j=0;j<2;j++){ x = arr[i][j] } } ``` So thetime complexityof this algorithm would beO(2n)orO(n^2)? What is thereason?
Outer loop is iterating n times, but inner loop is iterating only two times, So time complexity will be O(2n) and not O(n^2). And ``` O(2n) = O(n) ```
Can we add two numbers using pointers but without using any variable like a,b? I mean, generally, we take two variables and store it in pointer... but is it possible to the numbers without taking variable or can we take pointer variable?
Simple answer : ``` int *a = (int *)malloc(sizeof(int)); *a = 10; int *b = (int *)malloc(sizeof(int)); *b = 20; printf("%ld + %ld = %ld\n", *a , *b , *a + *b); ```
Can we add two numbers using pointers but without using any variable like a,b? I mean, generally, we take two variables and store it in pointer... but is it possible to the numbers without taking variable or can we take pointer variable?
Simple answer : ``` int *a = (int *)malloc(sizeof(int)); *a = 10; int *b = (int *)malloc(sizeof(int)); *b = 20; printf("%ld + %ld = %ld\n", *a , *b , *a + *b); ```
Instead of writingif(exp[i] =='*' || exp[i] =='/' || exp[i] =='+')can i write something like thisif(exp[i] == {'*','/','+'}).But writing this throws me an error, So is there any simple way of doing this ?
You can use thestrchr()function together with acompound literal: ``` if( strchr( (char[]){'*','/','+','\0'}, exp[i] ) ) ``` Or if you prefer, the far more readable string literal version: ``` if( strchr("*/+", exp[i]) ) ```
When compiling withgccI usedtimeto get compile time. ``` time gcc main.c && ./a.out ``` when trying to do the similar thing inclangI can't get the result ``` clang -time main.c && ./a.out ``` gives me a waring: clang: warning: argument unused during compilation: '-time' probably my approach is false, so please help me find compile time using clang
Tryclang main.c -ftime-report
This question already has answers here:Algorithm to find nth root of a number(5 answers)Closed2 years ago. C hassqrt()andcbrt(), but those are only the second and third roots. What if the root is an arbitrary number? What if I need the 57nth root?
Use thepowfunction, taking advantage of the fact that getting the 57 root is the same as raising to the power of 1 / 57. More generically, to get theyroot ofx: ``` double result = pow(x, 1.0 / y); ```
How can I format fscanf to format the input{'name surname', 'username', points}to strings which do not contain apostrophes ``` fscanf(fp,"{%s %s %d}",name,username,username1); ```
This should work: ``` fscanf(fp,"{'%[a-zA-Z ]', '%[a-zA-Z ]', %d}",name,username,username1); ```
How can I format fscanf to format the input{'name surname', 'username', points}to strings which do not contain apostrophes ``` fscanf(fp,"{%s %s %d}",name,username,username1); ```
This should work: ``` fscanf(fp,"{'%[a-zA-Z ]', '%[a-zA-Z ]', %d}",name,username,username1); ```
``` char str[] = "a"; char ch = 'a'; ``` speaking of the difference between the two, we all knowstrpoint to a memory space which stored [a, \0], but I want to ask whether there is a difference betweenstr[0]andch?
but I want to ask whether there is a difference betweenstr[0]andch? No. str[0]andch, both are of typechar, and hold the value'a'. From this aspect (type and value), there is no difference.
I can add include paths in Visual Studio easily but I couldn't find a way to do it in GCC? Any helps please?
Use the-Icommand-line argument: ``` gcc -Ipath ```
I would like to convert an int to a byte in C. In Java, I'd write: ``` int num = 167; byte b = num.toByte(); // -89 ``` In C: ``` int num = 167; ??? ```
You can simply cast to a byte: ``` unsigned char b=(unsigned char)num; ``` Note that ifnumis more than 255 or less than 0 C won't crash and simply give the wrong result.
How do I convert this array with ASCII numbers to text, so every number get's a letter. So "72" gets H, 101 gets E and so on. int a[] = {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100};
You can iterate over the array, and use the%cformating parameter to print the ascii characters of the int value ``` for (int i = 0 ; i < 11; i ++){ printf("%c", a[i]); } ```
I'm trying to learn C programming right now but I'm a bit stumbled upon the concept of declaring an array of pointers to functions. The statement is right here: ``` int (*menu_option[10])(char *title); ``` What exactly is happening here?
from thespiral rulehere menu_optionis an array of 10function pointersthey takechar*as an argument and return anint usehttps://cdecl.org/to parse C gibberish to English
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");
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");
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; } ```
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 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)
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++) {} ```
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 want to initialize a value of all array members to their index. ``` int main() { int i; int arr[10]; for (i = 0; i <= 9; i++) arr[i] = i; } ``` Should I consider the sequence point in this case?Isarr[i] = ilegal and portable?
You need to consider sequence points if you modify something more than once in one place,orif you both read and modify something in one place. You're not doing any of that, so your code is fine.
I have an array that I want to have in global scope. Its size however is determined during runtime, so I can't initialize it where I define it. How can I declare it in global scope and assign its size in themainfunction?
``` #include <stdlib.h> // for malloc int *globalarray; int main() { ... globalarray = malloc(thesizeyouwant * sizeof(*globalarray)); ... globalarray[0] = foo; ... free(globalarray); } ```
I have an array that I want to have in global scope. Its size however is determined during runtime, so I can't initialize it where I define it. How can I declare it in global scope and assign its size in themainfunction?
``` #include <stdlib.h> // for malloc int *globalarray; int main() { ... globalarray = malloc(thesizeyouwant * sizeof(*globalarray)); ... globalarray[0] = foo; ... free(globalarray); } ```
I have a C++ project, and the main file with the main function is a.c, but when I include my.hthat is supposed to be C++, I think I am getting errors because it thinks it is C. How can I tell it that my header should be C++ and not C, like my main?
You cannot#includeC++ header in a C source file. A header is not compiled separately. All that#includedoes - it makes the compiler work as if the header was a part of the file.
How could I write it in C language? I tried many things, but it seems that I cannot understand the exp and sin functions.
A direct implementation could be: ``` double y = exp(pow(sin(x),3)) + pow(x,6) - 2*pow(x,4) - pow(x,3) - 1.0; ```
I would like to convert a double into character string and I findgcvt()and_gcvt(). I just wondering what is the difference between them. Both return withchar*and both need value, number of digits and buffer as a given parameters
As per thegoogle search result The_gcvt()function is identical togcvt(). Use_gcvt()for ANSI/ISO naming conventions.
Why doesthis functionin the Linux kernel take avoid *unusedparameter that serves no purpose in the body of the function?
Because it is a callback. The prototype of all callbacks used in this context must be equal, sometimes may have an unused parameter. kthread_runresquires a function like this in the first parameter: ``` int cb(void *param); ```
The function was written to free a list i created earlier... ``` rekord *felszab(rekord *el) { rekord *temp; for(rekord *mozgo=eleje;mozgo=!NULL;mozgo=temp) { temp=mozgo->kov; free(mozgo); } return el; } ```
You call it without the prototype. Compiler assumes int as parameter and return value. Then it sees the definition having other types. Thus conflicting types
The function was written to free a list i created earlier... ``` rekord *felszab(rekord *el) { rekord *temp; for(rekord *mozgo=eleje;mozgo=!NULL;mozgo=temp) { temp=mozgo->kov; free(mozgo); } return el; } ```
You call it without the prototype. Compiler assumes int as parameter and return value. Then it sees the definition having other types. Thus conflicting types
``` printf("%i\n",2&2==2); ``` This should print out a 1 but I get a 0, why is this? ``` int ans=2&2; printf("%i\n",ans==2); ``` This prints a 1, how come the first way does not work? This is the case with if statements as well
The order of operations is different than you think it is. A correct way to write it in a single line would be: ``` printf("%i\n", (2 & 2) == 2); // Prints 1 ```
``` int main() { x=5; printf("%d",x+3); } ``` xcould be either5or8after this example (I know that the output on the screen would be 8.)
The value at the address ofxremains unchanged in this example. Inside theprintf, we first get the value at the address ofxand then add it to 3 and output it to the screen. This is why we use statements likex=x+3to change the value.
I've use cURL command-line tool with --libcurl and a url of mine(the url works in normal C), however I get the error "curl.h" does not exist, although it is in the same directory. I can't figure out how to include headers in emscripten. All of the supposed documentation on this usually ends up being about something else entirely.
I figured it out, I was being dumb
If I have the following lines of code, why is b-a = 2? ``` int a[] = {1,2,3,4,5}; int *b = &(a[2]); ```
To elaborate slightly on Eugene's answer,ais a pointer to the beginning of the array, anda[2]is the same as*(a+2). So you could say that the&"cancels" the*as you dereference the pointer and then look at the address of the element that it points to. So*b = &(a[2]) = &(*(a+2)) = a+2. Thereforeb-a=2
I can use GCC to convert assembly code files into reallocatable files. ``` gcc -c source.S -o object.o -O2 ``` Is the optimization option effective? Can I expect GCC to optimize my assembly code?
No. GCC passes your assembly source through the preprocessor and then to the assembler. At no time are any optimisations performed.
My input is: 1 + 2 I found that the value stored inargv[2][1]andoparen't the same, I just want to see if they are both the "+" operand.opstores the ascii value of "+" whileargv[2][1]stores some random value. How would I compare them? *I don't want to use "strcmp"
Array indexes start at0, so you need to use[0]to compare the first character of the argument. ``` if (argv[2][0] != c) { ```
``` unsigned int file = open(argv[1], O_RDONLY); printf("%u\n", file); printf("%u\n", elf.offset); lseek(file, elf.offset, SEEK_SET); printf("%u", file); ``` OutPut: ``` 3 52 3 ``` Shouldn'tfilebe set to52?
Upon successful completion, the resulting offset, as measured in bytes from the beginning of the file, shall be returned. try thisprintf("lseek_offset: %d\n", lseek(file, elf.offset, SEEK_SET));