question
stringlengths
25
894
answer
stringlengths
4
863
Im very new in the coding world, so maybe my suggestion to this function is not the best. But how I see it it should work, but it obviously doesn't. What do I do wrong? ``` //to do checksum int sum = 0; for (int i = 2; i <= d; i++ ) { sum = sum + ((int) (number / pow (10, i - 1)) % 10) * 2; number = number / 10; } printf("%i", sum ); ```
``` #include <stdio.h> int main() { int sum = 0; int num = 4532199; while (num) { num /= 10; sum += num % 10; num /= 10; } printf("sum=%d\n", sum); } ```
I'm building a binary structure that has to include a certainstringcharacter sequence. To set the character sequence, I'm using ``` struct { char preamble[6]; uint8_t check; } msg; strncpy(msg.preamble, "abcdef", 6); ``` This gives me a warning: ``` src\main.cpp:41:9: warning: 'char* strncpy(char*, const char*, size_t)' output truncated before terminating nul copying 6 bytes from a string of the same length [-Wstringop-truncation] ``` I'd like to keep the build log free of warnings, so that I can see actual issues quicker. How can I fix/suppress this warning?
If what you have isn't a string, don't treat it as such, i.e. don't usestrncpy. Usememcpyinstead. ``` memcpy(msg.preamble, "abcdef", 6); ```
I'm doing an University proyect where professors give us some base code supposedly in C. But inside this C files just see C++ functions like cout instead of printf, vectors from STL, inheritance? This is an example of file_reader.cc: ``` void read (const char *nombre_archivo_pse, vector <float> &vertices, vector <int> &caras){ unsigned num_vertices = 0, num_caras = 0; ifstream src; string na = nombre_archivo_pse; if (na.substr (na.find_last_of (".") + 1) != "ply") na += ".ply"; abrir_archivo (na, src); leer_cabecera (src, num_vertices, num_caras, true); leer_vertices (num_vertices, vertices, src); leer_caras (num_vertices, num_caras, caras, src); cout << "archivo ply leido." << endl << flush; } ``` This shouldn't be file_reader.cpp or file_reader.c++? How I code? In C or C++?
That is C++ code. The file extension for C++ files can be .cc or .cpp.
I am building a C test program on Linux. Why does this code compilation fail below? Afterlist_tis type-defined, shouldn't the compiler understand later that it is the same type as astruct list? The attempt to create a new list item using malloc() fails witherror: invalid type argument ``` #include <stdio.h> #include <stdlib.h> typedef struct list { struct list *next_ptr; int value; }list_t; int main() { list_t myList; myList->next_ptr = malloc(sizeof(list_t)); // This fails return 0; } ```
myList->next_ptrshould bemyList.next_ptrbecausemyListis not a pointer.
I have an integer array: ``` int s3[] = {97, 115, 100, 102, 103, 49, 50, 51, 37, 36, 33}; ``` and I need its string value like"asdfg123%$!" something like this: ``` printf ("%s", s4); // and output should be => asdfg123%$! ```
Copy the array item by item in a loop and store each value in achar. Then null terminate thatchararray so that it becomes a string. Or alternatively don't declares3asintto begin with.
Now I'm developing some software in the embedded Linux platform, I have some physical push buttons which I can read their pressing event through the file/dev/input/event1, in some special cases, I have to clear all event data stored in/dev/input/event1, but I don't know how.
Open the file in non-blocking mode andread()until there is nothing more to read. Use a buffer of PAGESIZE or 4K for efficiency.
I was just practicing with beginner code printing odds and evens and I could never figure out how to print them inside a simple for loop such that the values stay inside 1 single bracket { } like this: ``` The·even·number·in·range·are·{2,·4,·6,·8,·10}. ``` And not like this: ``` The even number in range are {2} The even number in range are {4} ``` Edit: oops forgot to place code fragment. ``` for(i=1; i<=n; i++){ r=i%2; if(r==0){ printf("The even number in range are {%d} ",i); } ```
``` #include <stdio.h> int main(void) { int n=21; printf("The even number in range are {"); for(int i=1; i<=n; i++){ (i%2)? 0:printf("%d ", i); } printf("}\n"); return 0; } ``` Output ``` Success #stdin #stdout 0s 5436KB The even number in range are {2 4 6 8 10 12 14 16 18 20 } ```
I know that most modern processors maintain a branch prediction table (BPT). I have read the gdb documentation but I could not found any command that should give desired results. Based on this, I have a couple questions: Is there a gdb command (or some other way) to get the BPT info of a process? If not, is it possible to view a process's BPT?
is it possible to view a process's BPT? No: at least on Intel processors it's hidden inside the processor itself and not exposed to either userspace or kernel in any way. Nor is it even documented, and constitutes "secret sauce". You can glean some details about branch predictor by conductingcareful experiments and observing various performance counters, but you can't examine it directly.
I would like to know, how to calculate 2D array's size in bytes. Array: int data[][5] = {{1, 2, 3}, {0}, {4, 3, 2}}; And how should I calculate the size of this array in bytes. Programming language is C.
You can use thesizeofoperator. The expressionsizeof datawill give you the size of the array, in bytes. Here is a short demonstration program: ``` #include <stdio.h> int main( void ) { int data[][5] = {{1, 2, 3}, {0}, {4, 3, 2}}; printf( "The size of the array is: %zu\n", sizeof data ); } ``` In my test environment, this program has the following output: ``` The size of the array is: 60 ``` The size of the array may be different on different platforms, but on most modern platforms,sizeof(int)is4, so the array's total size is4 * 3 * 5, which is60.
``` #include <stdio.h> int input(char *s, int n){ char c; int i = 0; while((c = getchar()) != '\n' && i < n){ s[i++] = c; // assigns s[i] then does i++ } s[i]= '\0'; return i; } int main() { char array[10]; input(array, 10); printf("%s", array); } ``` I have written this code but it does not work. When i input something it crashes and my shell aborts. Why is this?
``` s[i]= '\0'; ``` This will access the array out of bound when you enter more than 9 characters. To prevent this read maxn-1chars. ``` while((c = getchar()) != '\n' && i < n-1){ ```
I am trying to extract numbers from an HTML input field in C. Given the following HTTP post request, how can I extract the numbers 12 and 29 after the num1 and num2 substring and multiply them? ``` POST /test HTTP/1.1 Host: foo.example Content-Type: application/x-www-form-urlencoded Content-Length: 27 num1=12&num2=29 ```
If the string still has the same form, you can use sscanf. Ex: ``` #include <stdio.h> int main (void) { char *str = "num1=12&num2=29"; int num1, num2; if(sscanf(str, "num1=%d&num2=%d", &num1, &num2)==2) { printf("num1 = %d\n", num1); printf("num2 = %d\n", num2); } else puts("Error"); return 0; } ```
I have a task to enter a certain type of input - rgb ( x, y, z ), where x,y,z represents rgb color(integer). And I need to check it so that it is entered exactly like this. There is an example of an input: ``` rgb ( 0 , 255 , 0 ) ``` with a lot of spaces, this is a valid input, but it gives me that it is not. My peace of code: ``` if (scanf("rgb ( %d, %d, %d )", &x,&y,&z) != 3 || x > 255 || y > 255 || z > 255 || x < 0 || y < 0 || z < 0){ printf("Wrong input.\n"); return 1; } ``` There should also be a valid input if you remove all the spaces, just the form should remain - rgb(three intehger numbers with coma). And also it should be okay with a lot of spaces, like above. What am I doing wrong in the validation? Thanks a lot!
put space before each comma or use space in the format string anywhere you want it to consume spaces
I have a task to enter a certain type of input - rgb ( x, y, z ), where x,y,z represents rgb color(integer). And I need to check it so that it is entered exactly like this. There is an example of an input: ``` rgb ( 0 , 255 , 0 ) ``` with a lot of spaces, this is a valid input, but it gives me that it is not. My peace of code: ``` if (scanf("rgb ( %d, %d, %d )", &x,&y,&z) != 3 || x > 255 || y > 255 || z > 255 || x < 0 || y < 0 || z < 0){ printf("Wrong input.\n"); return 1; } ``` There should also be a valid input if you remove all the spaces, just the form should remain - rgb(three intehger numbers with coma). And also it should be okay with a lot of spaces, like above. What am I doing wrong in the validation? Thanks a lot!
put space before each comma or use space in the format string anywhere you want it to consume spaces
/I am trying to add array elements in c using myfun() but compiler shows warning [Warning] passing argument 1 of 'myfun' from incompatible pointer type/ ``` #include<stdio.h> void myfun(int*); void main() { int a[10] = {1,2,3,4,5,6,7,8,9,11}; printf("Array Elements are : "); myfun(&a); } void myfun(int* a) { int i; int sum = 0; for(i=0;i<10;i++) { printf("\t%d\t",a[i]); sum = sum + a[i]; } printf("\n\nSum : %d",sum); } ```
Correct code :- ``` #include<stdio.h> void myfun(int*); void main() { int a[10] = {1,2,3,4,5,6,7,8,9,11}; printf("Array Elements are : "); myfun(a); } void myfun(int* a) { int i; int sum = 0; for(i=0;i<10;i++) { printf("\t%d\t",a[i]); sum = sum + a[i]; } printf("\n\nSum : %d",sum); } ```
I want to implement the structure on the image in C language. But I have a problem because the 2 structures created call each other and therefore pose a problem how can I remedy it? set data structure picture :Imgur link liste set : ``` typedef struct liste_set { set *head; set *tail; } liste_set; ``` set : ``` typedef struct set set; struct set { int value; liste_set *liste; set *next; }; ``` Thank you for your help.
All you have to do is have preceeding declerations so the compiler knows whatsetis even before you actually fully declare it. ``` // declare structs struct liste_set; struct set; // typedef struct x to just x typedef struct liste_set liste_set; typedef struct set set; // describe what the structs are struct liste_set { set *head; set *tail; }; struct set { int value; liste_set *liste; set *next; }; ```
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.Closed11 months ago.Improve this question I'm doing cs50x and on week 5's problem set I keep getting this error message 'error: incompatible pointer types passing 'FILE *' (aka 'struct _IO_FILE *') to parameter of type 'const char *' [-Werror,-Wincompatible-pointer-types] while (scanf(file, "%s", word) != EOF)' when implementing the load function and I can't quite understand what am I doing wrong... Can someone help me please?
I guess you need to replacescanfbyfscanfin your load function. Btw, CS50 is a great course. I completed it about a month ago.
I'm currently learning C and I have this question... ``` char name[6] = "Pedro"; char test[25]; printf("Insert a name: "); fgets(test, 25, stdin); if(!strcmp(name, test)) puts("They are equal..."); ``` During the execution, strcmp doesn't return 0 when I insert the value "Pedro" in the array "test"... I know the array "test" have a size of 25 instead of 6, but since C dettects the end of a string with '\0', how can I use the fgets in this situation? Thank you very much...
fgets keeps the '\n' at the end of the line, it must be removed before the comparison. Example: ``` #include<stdio.h> #include<stdlib.h> #include<string.h> int main(void) { char name[6] = "Pedro"; char test[25]; printf("Insert a name: "); fgets(test, 25, stdin); test[strcspn(test, "\n")] = '\0'; if(!strcmp(name, test)) puts("They are equal..."); return 0; } ```
I'm currently learning C and I have this question... ``` char name[6] = "Pedro"; char test[25]; printf("Insert a name: "); fgets(test, 25, stdin); if(!strcmp(name, test)) puts("They are equal..."); ``` During the execution, strcmp doesn't return 0 when I insert the value "Pedro" in the array "test"... I know the array "test" have a size of 25 instead of 6, but since C dettects the end of a string with '\0', how can I use the fgets in this situation? Thank you very much...
fgets keeps the '\n' at the end of the line, it must be removed before the comparison. Example: ``` #include<stdio.h> #include<stdlib.h> #include<string.h> int main(void) { char name[6] = "Pedro"; char test[25]; printf("Insert a name: "); fgets(test, 25, stdin); test[strcspn(test, "\n")] = '\0'; if(!strcmp(name, test)) puts("They are equal..."); return 0; } ```
Please help me. I'm new to programming. I've been trying and searching for days to answer this. I need a C program that will open a text file named users.txt In that text file there are names then comma and their schools. ``` John Paul, Legit Univ Paul John, Yo Univ Lebron James, School Univ James Lebron, Legit Univ ``` All I managed so far is to display them all. The output should be all the users that are from"Legit Univ". Sample output: ``` Found 2 users from Legit Univ John Paul James Lebron ```
Usefgets()to read a line from file into a string, thenstrchr()to to find the position of the comma ',' field separator in the string (orstrstr()if the field separator is comma space ", "). Now you can check the part of the string after the field separator for a match on your query withstrcmp(). Instead of parsing the file, you could also use a regex and match against the string.
I am trying to declare multiple int with the help of for loops in c. The code almost looks like ``` for (int x = 0; x < 45; x++){ int valx = 10*x; } ``` The goal is to have a variable called val0 = 0, val1 = 10, val2 = 20...... I also need to be able to reference these made int later in the code and modify them, etc. Is there a coinvent to do this? If not is there another effective way to declare 45 variables fast? Also, I know the code is wrong I am trying to see if there is something similar. I think someone mentioned to use struct. How would that work in regard to this?
You want to create an array outside of the loop and assign to that. ``` int val[45]; for (int x = 0; x < 45; x++){ val[x] = 10*x; } ``` It wouldn't make sense to create the variables inside of the loop because those variables would disappear after the loop finishes.
I mean i want to add a character next to c in order to enter c or C . ``` switch (x) { case ('c') : printf("Donnez vous le cote du carre:"); scanf("%f",&cote); printf("La surface du carre est %f",cote*cote); break; ```
It's pretty straightforward. Note that any statementsbetweenthe two case statements will be executed for a lower case 'c' but not for uppercase. Also note that the parentheses are unnecessary. The expression'c'evaluates to the value of the character constant, which is what you want to compare to the value ofx, whether or not the parentheses are present. ``` case 'c' : // fall through case 'C' : printf("Donnez vous le cote du carre:"); scanf("%f",&cote); printf("La surface du carre est %f",cote*cote); break; ```
I want to send 8 bytes structure and since I dont have any valid member I just wanna add two unused fields which are of 4 and 2 bytes . My code below is throwing up an errorduplicate member 'unused' ``` typedef struct { uint16_t leakRatemTm; uint16_t unused; uint32_t unused; } stuct_t; ``` How do I actually add multiple unused fields in a structure. Thanks
You can use an array of char to pad with how many bytes you want. Use this in combination with the attribute packed: ``` typedef struct __attribute__((packed)); { uint16_t leakRatemTm; uint8_t unused[6] } stuct_t; ``` If you need gaps you can do something like this: ``` typedef struct __attribute__((packed)); { uint16_t leakRatemTm; uint8_t unused1[1]; //1byte gap uint16_t otherVar; uint8_t unused2[3]; //Fill till 8bytes } stuct_t; ```
I have a code snippet to initialize a sockets in windows. How would I initialize the socket in Linux environment. ``` WSADATA wsa if(WAStartup(MkeWORD(2,2), $wsa) !=0 ) { exit(0); } ```
On Linux you don't initialize a network environment like WSA. Sockets can be used out of the box. Seehttps://man7.org/linux/man-pages/man2/socket.2.htmlfor documentation.
This question already has answers here:Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer(5 answers)Closed12 months ago. I was trying to read a file char by char but the debugger when reaches the fscanf gives back a segmentation fault error, here's my code: ``` int main(){ FILE *inFile; char *carattere = NULL; inFile = fopen("../file.txt", "r"); if (inFile == NULL){ return -1; } while(fscanf(inFile, "%c", carattere) != EOF){ //segmentation fault printf("%c ", *carattere); } fclose(inFile); return 0;} ``` (I've recentely reinstalled my IDE).
You should provide some space for your character to be read. Where doescaratterepoint to when you try to write into it?
I'm trying to write a function that receives a char* pointer and an index and checks whether the bit in the index is on. i got somthing like that: ``` int bitIsOn(char *ptr, int index){ return (ptr[index/8] & (1<< (index%8))); } ``` note: I need to use c90. I am getting the following error message: error: invalid operands to binary & (have 'char *' and 'int') How can I avoid type collision here
Use unsigned data for bitwise operations. Use standard definitionCHAR_BITinstead of magic number 8 (it is defined inlimits.hheader file). ``` int checkbit(const void *data, const size_t index) { const unsigned char *udata = data; return udata[index / CHAR_BIT] & (1 << (index % CHAR_BIT)); } ``` If you want to return0or1you can use double logicalNOToperator: ``` return !!(udata[index / CHAR_BIT] & (1 << (index % CHAR_BIT))); ```
I wanted to run a binary code inside my C program (which is an interactive code) and record each keystrokes and list it in an output file. I have written the following, but seems like it is not working. ``` #include <stdio.h> #define MAX_LIMIT 200 int main() { while (system("my_binary")) { FILE *out_file = fopen("name_of_file", "w"); char str[MAX_LIMIT]; fgets(str, MAX_LIMIT, stdin); fprintf(out_file, "%s\n", str); fclose(out_file); } } ``` any suggestions what went wrong here!
Writing a program to do this is tricky and system specific. Yet if your system has ateeutility, you can run this command from the shell instead: ``` tee name_of_file | ./my_binary ```
Are void and char pointer guaranteed to have the same memory representation? In other words, after executing the following: ``` char a = 'z'; void *b = &a; char *c; memcpy(&c, &b, sizeof(b)); ``` Can I be certain that*c == 'z'(there is no undefined behavior, etc.)?
Yes, according to theC99 standard (ISO/IEC 9899)section §6.2.5 point 27: A pointer tovoidshall have the same representation and alignment requirements as a pointer to a character type.39)39) The same representation and alignment requirements are meant to imply interchangeability as arguments to functions, return values from functions, and members of unions.
GDB is trying to be helpful by labeling what I believe are global variables, but in this case each global is more than 0x10 bytes and so the second part of the variable is printed on the next line, but with an offset added to its label, which throws off the alignment of the whole printout (generated by executingx/50wx 0x604130):Is there a command to disable these labels while examining bytes? Edit: to be more specific, I would like to printout exactly what is shown in the screenshot, just without the<n1>/<n1+16>labels that are throwing off the alignment of the columns
Is there a command to disable these labels while examining bytes? I don't believe there is. One might expect thatset print symbol offwould do it, but it doesn't. The closest I can suggest isthis answer.
I want to find all my c source files from parent directory, compile them and create a static library with them all at once. I tried thisar -rc libmylib.a < gcc -c < find ../ -type f -name '*.c'but it throws: bash: gcc: No such file or directory.
gccdoesn't print the object file name so you'll have to divide it up into two command lines. Example: ``` find .. -type f -name '*.c' -exec gcc -c {} \; ar -rc libmylib.a *.o ```
I'm aware that the standardstrcmp()function is the fastest way to test if a string is "lexicographically less than, equal to, or greater than" the other. Isstrcmp()also the fastest way to see if 2 strings exactly match? If not, then what is?
I'm aware that the standard strcmp() function is the fastest way to test if a string is "lexicographically less than, equal to, or greater than" the other. Is strcmp() also the fastest way to see if 2 strings exactly match? If not, then what is? It sounds like the premise of the question is that there might be something faster thanstrcmp()becausestrcmp()figures out if the strings are less than or greater than, and you're thinking that maybe there's some other function that only determines if the strings match or not, and that that function would be faster because it somehow is doing less work. No, there is no such function.
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.Closed12 months ago.Improve this question ``` #include <stdio.h> ``` Does it work for Mac as well? Or is this library only for Windows?
Yes,stdio.h(along with several others such asstdlib.h,string.h, and others) are part of the C standard library. They are available onallstandard conforming implementations/platforms, including MacOS, Windows, Linux, and many more.
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.Closed12 months ago.Improve this question I am new to C programming but I stumbled on this code ``` int print(int nb) { if (nb < 0) { return (0); } printf("%d", nb + print(nb - 1)); nb --; return (nb); } int main(void) { print(4); return (0); } ``` I ran the code and it gave me an output of00246why is that the output that, looking at it logically, the answer is not suppose to start with a0
print(4) -> print(3) -> print(2) -> print(1) -> print(0) -> print(-1) print(-1) stops the recursion returning 0, thus a call to printf() is emitted with 0 + 0, which is 0. print(0) ends with -1 as value, and a call to printf() with 1 + -1 is emitted, which is 0. etc.
In order to declare a struct in C, I have been using ``` typedef struct Foo Foo; ``` and then defining it at some point below. Why do I have to specify the name of the struct (Foo) twice?
The format is ``` typedef old_type new_type ``` so for ``` typedef struct Foo Foo; ``` struct Foois the old type andFoois the new type, so whenever you typeFooit is really an alias forstruct Foo.
I am not able to find out why my function returns the user input only rather then the factorial of the input. ``` #include <stdio.h> #include <math.h> int factorial(int x) { //int x; int sum = 1; while (x!=0){ sum = sum * x; x--; } return sum; } int main(){ int x; printf("Enter value of x: "); scanf("%i",&x); factorial(x); printf("sum is %i", x); return 0; } ```
Yourfactorialfunction does return a new value, but then you don't actuallyusethat value. ``` printf("sum is %i\n", factorial(x)); ```
The Console in CLion doesn't print anything during debugging step-by-step (only after it gets to end of the code). I have no idea whether if this is normal, but if you can help to adjust the settings (if possible) so that it do the printing in the console as well (so that I can follow the code execution better), that would be great. I'm a total newbie, fresher at university, so please excuse this very basic question. Please try to give me the necessery steps in a way that I could understand. Thanks for your help.
Printf does not print directly to the console output, instead it adds the string to an output buffer. For better performance, the output buffer is not printed all the time. To force the output buffer to be cleared and printed, you can use: ``` fflush(stdout); ```
File1.c: ``` Init() { Add(MyLoop) } void MyLoop(bool) { // does stuff } ``` File0.c: ``` int main(void) { Init(); Run(false); } ``` File2.c: ``` void (* mpfStateMachine)(bool); void Run(bool Irrelevant) { mpfStateMachine(Irrelevant); } void Add(void (* func)(bool)) { mpfStateMachine = func; } ``` Note: I've ommited the header files, but you may assume the header files (and their #includes) are in order When I run the above code, it gives me a segmentation fault. When I comment out "mpfStateMachine(Irrelevant);" inside Run(), it compiles and runs fine. Any ideas are greatly appreciated.
Turns out the bug was completely unrelated. There was a bug inside MyLoop(). Thanks to Allan Wind for hinting I should reproduce it myself with a minimal example.
I have an x, y parameters. Using the python C API, how can I default y to the value of x if y is None. The python equivalent is: ``` def scale(x: float, y:Optional[float]=None): if y is None: y = x c_scale_api(x, y) ```
just check it againstPy_None. ``` static PyObject* scale(PyObject* self, PyObject* args) { PyObject* input2 = Py_None; // initialize to None double input1d, input2d; if (!PyArg_ParseTuple(args, "d|O", &input1d, &input2)) { return NULL; } if (input2 == Py_None) { input2d = input1d; } else { input2d = PyFloat_AsDouble(input2); } return PyFloat_FromDouble(input2d); } ``` this will return the value of the second argument for you to check.
Seeing as how it's often times a bad idea to cast from a larger to a smaller type (sayint->short), I would like to add compiler flags (GCC) that make it an error (or at least a warning) to cast from larger to smaller types. Are there flags to do this? Edit: Yes, I am referring to implicit conversions. Thank you to the people who answered this question.
If you mean: ``` short a; int b = 42; a = b; ``` -Wconversionis what you are looking for,-Werror=conversionto make it an error. If you mean: ``` short a; int b = 42; a = (short)b; ``` You can checkthis answer: By using an explicit conversion (a "cast"), you have told the compiler: "I definitely want to do this". That's what a cast means. It makes little sense for the compiler to then warn about it.
In my compilers class we are writting Flex/Lex code. When I compiled the.lfile and tried to compile the resultantlex.yy.cfile with gcc, I got the following error: ``` Undefined symbols for architecture arm64: "_yywrap", referenced from: _yylex in lex-fb85c9.o ld: symbol(s) not found for architecture arm64 clang: error: linker command failed with exit code 1 (use -v to see invocation) ``` Does is posible to compile it in a Apple Silicon (M1) Mac, at least in a Linux VM?
I created a test file and compiled: ``` % flex lex.l % cc -o lex lex.yy.c -lc -ll % grep 'yylex();' lex.yy.c yylex(); ``` The-llon thecccommand links against thelibllibrary. Current M1 based macOS does not provide alibfllibrary you may see referenced.
This question already has answers here:Simple swap function...why doesn't this one swap?(12 answers)Closed12 months ago. I'm very new to C and just starting to learn pointers. I'm very confused by this piece of code in lecture. I'm wondering if anyone can explain it to help me understand. ``` #include <stdio.h> void swap(int *p1, int *p2) { int *p; p = p1; p1 = p2; p2 = p; } void main() { int a, b; int *pointer_1, *pointer_2; scanf("%d, %d", &a, &b); pointer_1 = &a; pointer_2 = &b; if (a < b) swap(pointer_1, pointer_2); printf("\n%d > %d\n", *pointer_1, *pointer_2); } ``` The problem is why this doesn't swapaandb?
In your code ``` p = p1; p1 = p2; p2 = p; ``` you're swapping the addresses (the change is local to the function scope). You need to swap the values (*p1,*p2) stored in those memory locations.
I've a function prototype: ``` int array_length(char *(ptr)[1024]){ ... } ``` I want to call this function into another function. I have: ``` char array_slave[128][1024]; char (*ptr)[1024] = array_slave; array_length(&ptr); ``` As the compiler says, this is wrong. But why? Can you explain me "theorically" how to do in this situation? What is the reasoning to do?
The type ofptris alreadychar(*)[1024]. Thus the type of&ptris a pointer to pointer to an arraychar(**)[1024]. It differs from what the function expects thus a warning is raised. Just skip&: ``` array_length(ptr); ``` Alternatively you can passarray_slavedirectly because an array ofchar[1024]decays to a pointer to its first element producing pointer ofchar(*)[1024]type. ``` array_length(array_slave); ```
I would like to be able to check two flags in a single condition but I can't find the right way to do it. Here is an example of one of the things I tried: ``` #include <stdio.h> #define FLAG_1 0x01 #define FLAG_2 0x02 void check_flags(int flags) { if (flags & FLAG_1) printf("Flag 1\n"); else if (flags & FLAG_2) printf("Flag 2\n"); else if (flags & FLAG_1 | FLAG_2) printf("Flag 1 and 2\n"); } int main(void) { check_flags(FLAG_1 | FLAG_2); return 0; } ```
Try: ``` (flags & (FLAG_1 | FLAG_2)) == (FLAG_1 | FLAG_2) ``` Moreover, move this check at the beginning because otherwise it will be dominated byif (flags & FLAG_1)branch.
I want to pass a Pythondatetimeobject to the functionprintmebelow, seamlessly. ``` struct DateTime { uint64_t epochns; }; void printme(DateTime dt); ``` So far I was able to create this SWIG typemap to convert fromdatetimetoDateTime ``` %typemap(in) DateTime { PyObject* str = PyString_FromString( "timestamp" ); PyObject* obj = PyObject_CallMethodObjArgs( $input, str, nullptr ); $1.epochns = PyLong_AsLong( obj ); } ``` My question is: am I leaking the variablesstrandobj? Do I need to dereference them?
BothPyString_FromStringandPyObject_CallMethodObjArgsare documented to return a new reference, so bothstrandobjmust be released viaPy_DECREForPy_XDECREFor you will leak two references.
I needed a square root approximation in C so I looked upthis postand got this following implementation: ``` float squareroot(float n) { float x = n; float y = 1; float e = 0.001; // Accuracy level if (n == 0) return 0; while ((x - y) > e) { x = (x + y) / 2; if (n == 0 || x == 0) return 0; y = n / x; } return x; } ``` What is the time complexity of this?
Hint: Observe that ``` (x[k+1] - √n)/(x[k+1] + √n) = (x[k] + n/x[k] - 2√n)/(x[k] + n/x[k] + 2√n) = (x[k] - √n)²/(x[k] + √n)². ``` So by induction, ``` (x[k] - √n)/(x[k] + √n) = (x[0] - √n)^(2^k)/(x[0] + √n)^(2^k) = (√n - 1)^(2^k)/(√n + 1)^(2^k). ``` From this we find the number of iterations after which the error ise: ``` k = lg(lg(e / (2√n - e)) / lg((√n - 1)/(√n + 1)). ``` (base-2 logarithm.)
So I have this code: ``` #include <stdio.h> int main() { printf("enter character\n>>>"); char input[0]; scanf("%5s",input); printf("%s",input); } ``` that excepts 5 chars from the user. I am new to C and this one thing makes no sense to me. Why does gcc allow me to compile a program that assigns values to an array with a length of 0? Surely this is not possible? Please explain.
Your compiler ought to reject the declaration as invalid If the expression is a constant expression, it shall have a value greater than zero. (6.7.6.2). However, as @Joshua points out below, some compilers support this feature as an extension: Declaring zero-length arrays is allowed in GNU C as an extension (info gcc; 6.18) gcc -pendatic -pedantic-errorswill generate an error and only warning without-pedantic-errors. scanf()andprintf()will also be undefined behavior.
I just started learning c programming, my question might be so silly. I try to create a function to grab user input using scanf(). before that, I will have the menu displayed, and the user should only enter a number. so there is my question, how can I check whether the user enters an integer or character string or any other symbol. and send an error message if they do so?
refer toscanf() manual, they stated that : The scanf() function returns the number of fields that were successfully converted and assigned. The return value does not include fields that were read but not assigned. which means like for example , if you have a code like that : ``` int x; int numOfAssignedVars = scanf("%d", &x); ``` then if the user enter a valid number like2for example then the value ofnumOfAssignedVars = 1but if the user entered a char likesthennumOfAssignedVars = 0which indicated failure of the conversion
im sending via uart data from stm32 like this: ``` sprintf(buffer, "%d %d %d %d %d %d %d %d %d %d %d %f;", (int32_t)ir_average, (int32_t)red_average, (int32_t)dcFilterIRresult, (int32_t)dcFilterRedresult, (int32_t)chebyshevResult2, (int32_t)elipticResult2, (int32_t)wyjscie, (int32_t)bpm_up, (int32_t)fftbmp, (int32_t)currentSaO2Value, (int32_t)spo2Calib, temp); HAL_UART_Transmit(&huart4, buffer, 100, 1000); ``` how should i read it from esp8266 side in arduino ide? maybe i should do it differently? i wanted to send a packet od data and split it after reading full packet on esp8266
Generally in arduino you read using Serial.read() which returns char. Form a string out of it. ``` String resp; char _char; while(Serial.available()){ _char = Serial.read(); resp += _char; } ``` to convert it to int use.toInt() to separate individual numbers use.indexOf
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed12 months ago.Improve this question here's the image of that program While I tried to print the values of array suppose of length x, its prints correctly but when I tried to print the array with different length rather than predefined length then its giving random values ... how .. ?
Accessing an array out of bounds* will giveundefined behavior. It will compile and run, but the results are not predictable. Arrays in C are indexed starting at0. An array of nine elements has a maximum index of8. You have accessed elements9and10.
I was writting a program to assign the Value of N to M in the declaration statement.If i gave value of N in declaration i get the same value in output.But if i read from user ,i am getting 1 always ``` #include<stdio.h> #include<conio.h> main() { clrscr(); int N,M=N; scanf("%d",&N); printf("%d",M); getchar(); return 0; } ```
When you declare the value of N to M, N does not have any value, that is why you are always getting one. You need to assign the value after getting it from the user. ``` #include<stdio.h> #include<conio.h> main() { clrscr(); int N,M; scanf("%d",&N); M=N; printf("%d",M); getchar(); return 0; } ```
I want to fill an array with random integers from -10 to 10. My function looks like this: ``` int array(int a[], int n, int min, int max){ for(int i=0;i<n;i++){ a[i]=(rand()%min); printf("%d ", a[i] ); } ``` In main I have declared "min" to -10. But it does not really work, it still prints between 0 - 9. I have tried with +1 after min, then i get 10, but still no negative integers.
The number of possible number ismax - min + 1, so that's what you want to mod by, giving you a number from 0 tomax - min. Then you addminto that to give you a number frommintomax. ``` a[i]=(rand() % (max-min+1) + min ); ```
I want to fill an array with random integers from -10 to 10. My function looks like this: ``` int array(int a[], int n, int min, int max){ for(int i=0;i<n;i++){ a[i]=(rand()%min); printf("%d ", a[i] ); } ``` In main I have declared "min" to -10. But it does not really work, it still prints between 0 - 9. I have tried with +1 after min, then i get 10, but still no negative integers.
The number of possible number ismax - min + 1, so that's what you want to mod by, giving you a number from 0 tomax - min. Then you addminto that to give you a number frommintomax. ``` a[i]=(rand() % (max-min+1) + min ); ```
How does one convert from one integer type to another safely and with setting off alarm bells in compilers and static analysis tools? Different compilers will warn for something like: ``` int i = get_int(); size_t s = i; ``` for loss of signedness or ``` size_t s = get_size(); int i = s; ``` for narrowing. casting can remove the warnings but don't solve the safety issue. Is there a proper way of doing this?
You can tryboost::numeric_cast<>. boost numeric_cast returns the result of converting a value of type Source to a value of type Target. If out-of-range is detected, an exception is thrown (see bad_numeric_cast, negative_overflow and positive_overflow ).
I want to specify fractional frame rate's like23.797or59.94when creating my encoder. Here is how I do it currently: ``` AVStream* st; ... st->time_base = (AVRational){1, STREAM_FRAME_RATE }; ``` But looking at ffmpeg's source code atrational.hwe can see thatAVRationalstruct takes int's instead of float's. So my23.797turns into 23 thus encoding wrong. How can I specify fps with floating numbers?
As per the comment, you can make use ofav_d2qfrom thelibavutillibrary. By way of a basic example... ``` #include <iostream> #include <limits> extern "C" { #include <libavutil/avutil.h> } int main () { auto fps = 23.797; auto r = av_d2q(1 / fps, std::numeric_limits<int>::max()); std::cout << "time base is " << r.num << "/" << r.den << " seconds\n"; } ``` The above gives me the following output... ``` time base is 1000/23797 seconds ```
I am using C printf to print doubles and found the rounding is inconsistent. Sometimes it will not round up with certain values. ``` double t = 16.125; printf("%-10.2lf", t); ``` This prints 16.12. I thought it would round up to 16.13. ``` double t = 16.135; printf("%-10.2lf", t); ``` This prints 16.14. This is what I thought would happen for all cases.
The default rounding behaviour is round-half-to-even. This means: 16.125 is exactly halfway between 16.12 and 16.13, so it rounds (down) to 16.12 (the even one).16.135 can't be exactly represented by a floating-point number. On my system, it's 16.135000000000001563194018672220408916473388671875. This number is closer to 16.14 than to 16.12, so it rounds to 16.14.16.375 is exactly halfway between 16.37 and 16.38, so it rounds (up) to 16.38 (the even one). fesetroundallows one to change the default.
I am not allowed to use abs or any other libraries. Here is what I've tried so far. ``` #include <stdio.h> #include <limits.h> int main() { int n = INT_MIN; if (n == INT_MIN) { int a = -n; a = n % 10; putchar(a + '0'); } return (0); } ``` The output is always "(" and not the correct answer.
Apply modulus to the negative number first to get a single negative digit. Negate that. ``` #include <stdio.h> #include <limits.h> int main() { int n = INT_MIN; int a = -( n % 10); putchar(a + '0'); return (0); } ```
I wrote this little code to get from Fahrenheit to Celcius. I know that when I type "float a = 41.9" the value is 41.90000045 or something. How can I limit the decimal places to only 1 so that my "if-statement" will become true? ``` #include <stdio.h> #include <stdlib.h> #include <stdint.h> float FtoC(float a); int main() { if (FtoC(41.9) == 5.5){ printf("%f\n", FtoC(41.9)); } return 0; } float FtoC(float a){ float x = (a - 32.0) / 9.0 * 5.0; return(x); } ```
You can includemath.hlib and useroundffunction. ``` #include <math.h> float C = roundf(FtoC(41.9)*10.0f)/10.0f; if ( C == 5.5) { printf("%f\n", C); } ```
``` // main.cpp #define a aa #define aa a int main() { int a = 1; int aa = 11; } ``` As like the code above, the macro definition is nested. Is finally a = 1 or a = 11 ?
C 2018 6.10.3.4 2 discusses rescanning for more macro names after macro replacement and says: If the name of the macro being replaced is found during this scan of the replacement list (not including the rest of the source file’s preprocessing tokens), it is not replaced. Furthermore, if any nested replacements encounter the name of the macro being replaced, it is not replaced… Then, whenais replaced withaa, rescanning findsaaand replaces it witha. Then rescanning does not replaceasince it has already been replaced. Similarly, whenaais replaced witha, rescanning findsaand replaces it withaa. Then rescanning does not replaceaasince it has already been replaced.
I want pass an array of int to an array that have array of float parameter this is what I tried, it do compile but it give rubbish results ! ``` function_1(float arr*, int len) { .... .... } main() { int samp[5] = {-1, 3, 5, 10, 20}; function_1((float *)samp, 5); //not correct ! } ```
You can't. No computer have the same internal and bitwise representation offloatandint. Not to mention thatsizeof(float)doesn't have to be equal tosizeof(int). The only solution is to create a new array, and convert each and every element frominttofloat, and then pass the proper array offloat.
¿Is posible reuselua_newuserdata()returned pointer? The idea is not allocate a new userdatum every time for the same object and allow equality check (example) done by lua. ``` obj1 = c_api__foobar(); obj2 = c_api__foobar(); if obj1 == obj2 then print("equal") else print("they are supposed to be equal") end ```
well look is not possible, attemping to reuse the pointer will throw something likecalling 'c_api__foobar' on bad self (FOOBAR expected, found FOOBAR)error. ``` static int expose_foobar(lua_State* L) { void* existing_userdata = /* previous value returned by lua_newuserdata() */; LUA.luaL_getmetatable(L, "FOOBAR") LUA.lua_setmetatable(L, -2); return 1; } ``` tested in lua 5.4
I've written a simple code in C that takes in an ASCII decimal value and returns the char value that corresponds to the inputted decimal. For example, 65 would print out 'A'. ``` int x; printf("Enter an ASCII number: "); scanf_s("%d", &x); printf("Entered letter is: %c\n", x); ``` However if I change line 1 fromint xtochar x, the program will run into run-time check failure #2 stating stack around variable x was corrupted when I test the program with x = 65. I understand this usually happens if I am out of bounds of assigned memory, but 65 should still be within the memory limit of char. Why is this happening?
By usingscanf_s("%d", &x);, you tell c to scan for a decimal integer (%d) of typeint, and store it in achar. Because anintis 4 bytes, and achar1 byte, you are writing outside the char, corrupting the surrounding memory.
I am trying to compile a C file with gcc. The code in header file will need specified architecture in order to compile. ``` #if defined( _8BIT_ARCHITECTURE ) #include "type8.h" #elif defined( _16BIT_ARCHITECTURE ) #include "type16.h" #elif defined( _32BIT_ARCHITECTURE ) #include "type32.h" #else #error ARCHITECTURE not defined #endif ``` When using Visual Studio, I can configure the platform into 32-bit and it can build successfully. But how do I do the same thing with gcc commands? I was trying to use: ``` gcc -m32 -c myFile.c -I /somePath/ ``` But it keeps giving me the error statement: ``` #error ARCHITECTURE not defined ```
Adding-D_32BIT_ARCHITECTUREfix the issue
How to compute the projection of a GNSS module at a heighthwithx, y, z, roll, pitch, yawdata on a flat ground? I searched online and couldn't find anything about how to handle such question.
A place to start might be equation 1.78 in 'GPS for Geodesy' Edited by Kleugsberg and Teunissen which you can take a look at in pdfdrive.
I am following this tutorialhttps://lucasklassmann.com/blog/2019-02-02-how-to-embeddeding-lua-in-c/#installationand I was wondering how I could get the following libraries installed on ubuntu: ``` #include <lua.h> #include <lualib.h> #include <lauxlib.h> ``` I tried installing all sorts of lua-related things, like: ``` sudo apt-get install liblua5.1-0-dev sudo apt-get install lua-devel ``` But I still could not get things to work. Does anyone know how to get lua working for C?
The Ubuntu packages for Lua add an extra subdirectory so that you can have multiple versions installed at once. Either do this instead: ``` #include <lua5.1/lua.h> #include <lua5.1/lualib.h> #include <lua5.1/lauxlib.h> ``` Or pass-I/usr/include/lua5.1on the compiler command line. (If you get undefined references errors after either of these options, then you probably need to append-llua5.1to the compiler command line.)
``` #include <stdio.h> int main() { printf("Hello World"); return 0; } ``` I build by: ``` gcc -Wall -ansi -pedantic -c main.c -o main ``` uname -mgives "x86_64". After compilingfile maingives: ``` main: ELF 64-bit LSB relocatable, x86-64, version 1 (SYSV), not stripped ``` strace ./maingives: ``` execve("./main", ["./main"], 0x7ffc779cf7c0 /* 33 vars */) = -1 EACCES (Permission denied) strace: exec: Permission denied +++ exited with 1 +++" ```
You did only compile, but not link the program. Unlinked object files cannot be executed. Change your build command to: ``` gcc -Wall -ansi -pedantic main.c -o main ``` Note the missing-c.
still very new to C and trying to understand this better. The instruction is to input a certain number of lines using a while loop, but mine appears to only print a total of 10 lines never what I have instructed to print. What am I missing for it to print only what I input? ``` int numLines; printf("Enter lines: "); scanf("%d", &numLines); aroundTheWorld(numLines); //First line printf("Around the world,\n"); //Repeating lines while(numLines < 10) { printf("around the world,\n"); numLines++; } // applies a full stop printf("around the world.\n"); } ```
Instead of this condition in the while statement with the magic number 10 ``` while(numLines < 10) ``` write for example ``` while ( 0 < numLines-- ) { printf("around the world,\n"); } ```
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.Closedlast year.Improve this question I want to read a file using read() system call and copy all its contents to another file. As the input file can be large, I don't know what buffer size to use. How to change the buffer size dynamically? Or is there any other approach like reading a file part by part using a fixed buffer ? Can anyone tell how to do this.
Read the file part-by-part using a fixed buffer. To copy a file, there is no reason why you have to read the entire file in one call.
The signature of the JNI_OnLoad function is this: jint JNI_OnLoad(JavaVM *vm, void *reserved); What is the void *reserved parameter?
Although the documentation doesn't explicitly say so, this parameter is reserved for future use and should be set toNULLin all cases.
I have uint8_t size 4 integers stored in a array:uint8_t sdo_rx_data_buffer[OD_entry_len];. The length of this array is 4 bytes (OD_entry_len = 4), so is equal to float size (32 bits). I need to convert this array into float variable. For exampe, I have these values:int array[4] = {0xd0, 0x69, 0x83, 0x3f};And i should getfloat i_motor = 1.02666664;Any ideas how to convert it?
Assuming that you know that the binary representation gives a valid floating point number on your system and you got the endianess right, then you can use aunion: ``` #include <stdint.h> #include <stdio.h> typedef union { uint8_t raw [sizeof(float)]; float f; } float_converter; int main (void) { float_converter fc = { .raw = {0xd0, 0x69, 0x83, 0x3f} }; printf("%f\n", fc.f); } ``` Output on x86_64 Linux: ``` 1.026667 ```
I'm trying to includestddef.hfrom GCC folder according to the system version. Using the next sequence of macros: ``` #define __gcc_header(x) #x #define _gcc_header(x) __gcc_header(/usr/lib/gcc/x86_64-redhat-linux/#x/include/stddef.h) #define gcc_header(x) _gcc_header(x) #include gcc_header(__GNUC__) ``` I got the next error: ``` fatal error: /usr/lib/gcc/x86_64-redhat-linux/\"11\"/include/stddef.h: No such file or directory 4 | #include gcc_header(__GNUC__) | ^ compilation terminated. ```
Thanks to@Eric Postpischil, the solution is to use the macros like: ``` #define __gcc_header(x) #x #define _gcc_header(x) __gcc_header(/usr/lib/gcc/x86_64-redhat-linux/x/include/stddef.h) #define gcc_header(x) _gcc_header(x) #include gcc_header(__GNUC__) ```
I am studying C. How is this answer 110? ``` #include <stdio.h> void main() { char c1,c2,sum ; c1='5'; c2='9'; sum= c1+c2; printf("sum=%d",sum); } ```
The character'5'has an ascii value of 53.The character'9'has an ascii value of 57. 53 + 57 == 110.
This question already has an answer here:what is the difference between while(i>0) and while(i)(1 answer)Closedlast year. I am trying to run a program in C, where the following statement is used in the code. What does the following statement mean in the for loop condition of the given code? I understand i is being initialised with value 3; and i gets updated in i = i-1 ; but what does the condition part mean? why only i; should it not be i>0? Why both statements give the same output , i.e *** . Code statements: ``` int main() { for(int i=3;i;i=i-1) { printf("*"); } return 0; } ```
Simply,iwill be true when!= 0. Since your program must keep going until i is zero, It will keep checking. Here's a list of what the condition returns: i valueoutput returned byi3true2true1true0false (break)
I need to adapt a file written in Borland C++ Builder 5 to be usable in MS Visual Studio 2022. One of the files heavily utilizes thedir.hlibrary, which, as far as I can tell, is a C library exclusive to Builder. The source files are available, however they have a lot of dependencies and, as I've mentioned, are written in C. I have searched the Internet for a substitute, unfortunately to no avail. Does a similar library exist for C++? Or do I have to re-write the file (which is pretty big) using e.g.std::filesystem?
The functions indir.hare mapping quite direct to Win32 API calls offileapi.h. You could use this header for a quick port. For a modernization, it might be the best idea to re-write the code usingstd::filesystem. There is hardly any sensible C++ library with such a C-like API. Well, there are the modernized Embarcadero API-calls inSystem.SysUtils.hpp, but they are still no modern C++, and they are only available in their ecosystem.
This question already has answers here:Getting a weird percent sign in printf output in terminal with C(3 answers)Closedlast year. when I useprintffunction in Visual Studio Code there is always%character at the end of the line in terminal. why dose this happen??
That is your terminal's shell prompt. You have not printed a newline character, so the prompt appears immediately after your program's output. ``` printf("hello\n"); ```
Another way to phrase this question might be "How to end format specifiers in printf" If I want to print microseconds in this format100ususing the following code... ``` long microseconds = 100L; printf("%lus", microseconds); ``` only prints100sbecause theuis combined with the%land it interprets the format specifier as anunsigned longinstead of along
Just write ``` long microseconds = 100L; printf("%ldus", microseconds); ``` Pay attention to that you may not use a length modifier without a conversion specifier.
I am using libpcap to capture packet with the following filter: ``` "tcp[tcpflags] & (tcp-syn) != 0 and not net 127.0.0.1" ``` But I actually want to get the packet only if the sender is the client (SYN-SENT). Basically what I am trying to do is to get inform only for new connection and not multiple time for every connection. Is there a way to do that?
If you only want the SYN from the client but not the SYN+ACK from the server use: ``` tcp[tcpflags] & (tcp-syn|tcp-ack) == tcp-syn ```
The main processes launches 4 threads. Now at this time all 4 threads will start execution immediately, but I want all the threads to wait till rest of all threads are also in running state. I remember using a semaphore to track the thread counts, but not able to recall it. Is there any simple way to do without doing any busy-wait? ``` void *thread_routine(void *arg) { // this thread should wait here till rest of all threads are also ready to run // do some job here return NULL; } int main(int argc, char *argv[]) { int i = 0; pthread_t thid[4]; for (i = 0; i < 4; i++) { pthread_create(&tid[i], NULL, thread_routine, NULL); } for (i = 0; i < 4; i++) { pthread_join(tid[i], NULL); } return 0; } ```
What you describe sounds likebarrier synchronizationwhich can be implemented usingpthread_barrier_wait. Here's asimple exampleusing it (from TLPI book).
I have two questions for you; Is there any way to just build and run c code internal terminal when I press to button given figure below. Just there is build and debug options. Is there any way to open debug in internal terminal not new pop-up window like figure below. Here is my task and json files.
I handle this problem with code runner extension. First I added extension then from settings enabled run code in terminal.
I have two questions for you; Is there any way to just build and run c code internal terminal when I press to button given figure below. Just there is build and debug options. Is there any way to open debug in internal terminal not new pop-up window like figure below. Here is my task and json files.
I handle this problem with code runner extension. First I added extension then from settings enabled run code in terminal.
I'm new to coding and recently I came across a problem that my code doesn't work unless I save that first so is it necessary to save a code every time I make a change in a code.(vscode)(c)
Usually, C and C++ arecompiled, i.e. the file(s) with the source code need to go through a compiler to get translated to machine code. So, the program source needs to be saved first before it can go into the compiler, yes. Most IDEs, like VSCode, will save when you ask them to compile, because that's useful assistance to you.
``` #include<stdio.h> #include<stdlib.h> int main() { int *n = malloc(sizeof(int*));//line 1 scanf("%d",n); printf("%d",*n); } ``` I am not sure what is happening here. Does line 1 (in the snippet above) mean n now simply is a pointer to an int? And we have started using the memory allocated for a pointer as variable itself? Is the pointer to pointer cast to pointer to int?
In this line ``` int *n = malloc(sizeof(int*));//line 1 ``` you allocated memory of the size equal tosizeof( int * )and its address is assigned to the pointernhaving the typeint *. So using this pointer to access the memory it is interpreted as a memory storing an object of the typeint ``` scanf("%d",n); printf("%d",*n); ``` Actually the kind of the argument expression used to specify the size of the allocated memory is not very important. For example you could just write ``` int *n = malloc( 8 );//line 1 ```
Based on thereference, the_Atomictype specifier can not be used on arrays. Is there a standard way/workaround to be able to issueatomic_exchangecalls for an object that is stored within the array?
The standard prohibits to apply the_Atomicspecifier to an array as a whole, for example this ``` typedef double at[5]; _Atomic(at) atomic_array; // constraint violation ``` But the array elements may well be atomic ``` _Atomic(double) atomic_array[5]; // valid ``` If you want the access to the array as a whole to be atomic, you'd have to encapsulate the array within a structure and then have the_Atomicaround the structure.
Please let me know what's wrong with the code I made ``` void make_crc_table( void ) { int i, j; unsigned long poly, c; poly = 0x03; // X^6 + x + 1 for ( i = 0; i < 256; i++ ) { c = i >> 2; for ( j = 0; j < 8; j++ ) { c = ( c & 0x20 ) ? poly ^ ( c << 1 ) : ( c << 1 ); } crctable[i] = (uint8_t) c; } } ``` Thanks for the help.
You need to calculate starting at the high bit of the bytes. Get rid of the>> 2(that just results in doing the same calculation four times). Do this to calculate from the high bit: ``` c = c & 0x80 ? (c << 1) ^ (poly << 2) : c << 1; ``` Then when saving: ``` crctable[i] = (c >> 2) & 0x3f; ``` Not required, but there's no reason for theunsigned long, so just make thatunsigned.
I used malloc to give some space to pointer. First I wrote a line like below to give 4byte space for one integer. ``` int *minus = malloc(4); // minus: 0x6a1590 ``` and I used vscode debugging to see if it's done well. result showed like "minus: 0x6a1590". After that I gave char pointer a space. ``` char *str = malloc(2); // str : 0x6a15d0 "\300>������������������������������" ``` I just gave str a 2byte space but there is lots of thing in str. Why is this happening? I thought there should be two null character in str..
Whatever tool you are looking at to view the contents ofstris assuming that it points to a string. But it doesn't point to a string, it just points to the two bytes of memory that you allocated which have no particular contents. So the information you are seeing there is meaningless.
I am new to Frama-C and wanted to ask what could be causing this issue: When I run the E-ACSL wrapper script on annotated code with no header files, the a.out.e-acsl file is properly created. However, when I try to include header files using-Eand-I, the wrapper script fails to print anything and does not generate any files. e-acsl-gcc.sh -E "-I src/include -I ..." main.c I noticed that this issue happens specifically when the-Ioption is added. I am using Frama-C 24.0 (Chromium). Any help would be appreciated. Thanks.
I just added a detail tothis answerwhich should help here: the issue is thate-acsl-gcc.shcannot handle spaces between-I/-Dand its arguments. GCC accepts both-I dirand-Idir, but fore-acsl-gcc.sh, only-Idirshould be used. So, the following should hopefully work: ``` e-acsl-gcc.sh -E "-Isrc/include -I..." main.c ```
Write a program that takes an integer and prints the number of trailing zeroes. Example: Enter the number: 24100Trailing zeroes: 2 I have no Idea what condition to create to determine the number of zeroes in a number.
You could use a modulus trick here: ``` int input = 24100; int num_zeroes = 0; while (input > 0) { if (input % 10 == 0) { num_zeroes = num_zeroes + 1; input = input / 10; } else { break; } } printf("%d", num_zeroes); // 2 ```
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closedlast year. see code below . The output is 49 ( 7*7 = 49) . How this could happen? can somebody explain in details. ``` #include <stdio.h> #define SQUARE(X) X * X #define PR(X) printf("The result is %d.\n", X) int main(void) { int x = 5; printf("x = %d\n", x); PR(SQUARE(++x)); // print out 49 but x is 5 return 0; } ```
It will expand this way: ``` PR(SQUARE(++x)); ==> PR(++x * ++x) ==> printf("The result is %d.\n", ++x * ++x); ``` And, modifying variablextwice without a "sequence-point" (mainly, a semi-colon;, but there are other sequence-points) createsUndefined Behavior
I've a problem compiling the following programm: ``` // hauptteil.c (main part) #include "nebenfkt.h" #include <stdio.h> #include <stdlib.h> int main (void) { int x =10; int ergebnis=0; ergebnis =ver(x); printf("Doubled number: %d", ergebnis); return 0; } ``` ``` //nebenfkt.h int ver(int x); ``` ``` #include "nebenfkt.h" #include <stdio.h> #include <stdlib.h> int ver(int x) { int rueck; rueck= x*2; return rueck; } ``` VSC gives me the feedback "* undefined reference to `ver' collect2.exe: error: ld returned 1 exit status*" Solution The problem occurred because I only used the command "gcc hauptteil.c -o function" Instead of "gcc hauptteil.c nebenfkt.c -o function"
My mistake was discovered by Eugene Sh. My mistake was that I only used the command "gcc hauptteil.c -o function" Instead of "gcc hauptteil.c nebenfkt.c -o function".
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.Closedlast year.The community reviewed whether to reopen this questionlast yearand left it closed:Original close reason(s) were not resolvedImprove this question ``` #include <stdio.h> //Compiler version gcc 6.3.0 int main() { int a,b,sum; printf("enter two integers:"); scanf("%d %d",&a,&b); printf ("%d + %d = %d",a,b,sum); return 0; } ```
The code never assigns a value tosum. Add an assignment statement that starts withsum =. Enable warnings in your compiler and elevate warnings to errors. With Clang, start with-Wmost -Werror. With GCC, start with-Wall -Werror. With MSVC, start with/W3 /WX.
I am using the following expression in C code: sprintf(message, "0x%016llX; ", someIntValue); How do I do the same in python? I know in C what it means. the mandatory % charactera 0 flag for paddingthe 16 as "minimum field width"the ll as "length modifiers"the x conversion specifier What I don't know, is how to do it in python...
The same can be achieved using either of the following: ``` "0x%016X; " % someIntValue # Old style ``` ``` "{:016X}; ".format( someIntValue ) # New style ```
When running the command: ``` clang --target=wasm32 -nostdlib -Wl, --no-entry -Wl, --export-all howold.c -o howold.wasm ``` I get the following errors: ``` clang-14: error: unsupported option '--no-entry' clang-14: error: unsupported option '--export-all' ``` I installed LLVM usingbrew install llvmand linked it properly withbrew link llvm, then ransource .zshrc. Does macOS not support these directives or am I missing an install or command somewhere? I am new to LLVM and clang on macOS so this may be an installation problem but not entirely sure.
To pass arguments to the linker, there shouldn't be a space after-Wl,. With the extra space, you're trying to give the--no-entryoption toclangitself, which isn't valid. Try this: ``` clang --target=wasm32 -nostdlib -Wl,--no-entry -Wl,--export-all howold.c -o howold.wasm ```
I'm writing aGDBscript inpythonto print some debug information of the application. The thing is multiple architectures are supported: x86, alpha, aarch64, and probably some more later. The function printing the debug information varies from the architecture. So in fact I've got the following functions: ``` def print_info_x86(): #... def print_info_aarch64(): #... def print_info_alpha(): #... ``` And I want to achieve something like the following: ``` def print_info(): if arch == 'x86': print_info_x86() #etc.. ``` Is there a way to do that? There is a GDB commandshow architectureand it's possible to extract it fromobjdump -a, but is there a simpler way to understand what architecture the binary was compiled for inGDB?
https://sourceware.org/gdb/onlinedocs/gdb/Architectures-In-Python.html something like this: ``` f = gdb.selected_frame() a = f.architecture() print(a.name()) ```
I was reading some examples in how to convert char to int, and i have this code: ``` #include <stdio.h> int main() { char ch1 = 125, ch2 = 10; ch1 = ch1 + ch2; printf("%d\n", ch1); printf("%c\n", ch1 - ch2 - 4); return 0; } ``` as i know that if we made any Character arithmetic the char type will convert to int so why the result of first printf statement is-121not135as i know int range will handle 135 so no overflow will happened. the second printf statement will print y because we put %c in the printf .
The "char" variable types usually default to the "signed char" type.The "signed char" variables have a range of values from -127 to +127. Exceeding this positive range limit caused the negative result from this program. The value of -121 is displayed because that is the two's compliment value of the bits set for the unsigned char value of 135.
Is there a way to check, if a program is itself already running? I have only found answers for MS windows; is there a platform-independent/*nix way to do so?
On POSIX, you can usenamed semaphoresfor this purpose. Whenever the program starts, it should use the functionsem_opento open a semaphore with a unique name that is hard-coded into the program, creating the semaphore if it does not already exist, and then usesem_trywaitto attempt to acquire the semaphore. The initial value of the semaphore should be 1. If acquiring the semaphore fails due to the semaphore already having been acquired, then the program can probably assume that another instance of the same program is already running.
When I convert enum to integer type, what can I expect? Does the first variant have value of 0?Does the variant ordinal number increment by 1? Assume that I did not explicitly provide the values. If you like code, then the questions are here: ``` enum foo { A, B, }; int main(void) { assert(A == 0); assert(B == 1); } ```
Does the first variant have value of 0? Yes. Does the variant ordinal number increment by 1? Yes. What guarantees does C provide about enum ordinal values Fromhttps://port70.net/~nsz/c/c11/n1570.html#6.7.2.2: [...] If the first enumerator has no =, the value of its enumeration constant is 0. Each subsequent enumerator with no = defines its enumeration constant as the value of the constant expression obtained by adding 1 to the value of the previous enumeration constant. [...]
I'm thinking about migrating some of my services from GCE VMs to Cloud Run. And I want to see how it would be like when I have to troubleshoot, especially in (hopefully rare) case that my C/C++ program segfaults. When segfault occurs, I usually detach the VM from production and take a look at coredump, usingsudo coredumpctl gdb. My question is: can I do similar on Cloud Run? Can I collect coredump files and get them from somewhere like Cloud Storage?
Can I collect coredump files and get them from somewhere like Cloud Storage? No. Cloud Run runs container-hosted applications. If your application throws an exception, your container will be killed. Capturing a core dump for an application in a container requires the host operating system to be configured to enable that feature. Cloud Run does not provide access to the host platform. Note: Cloud Run runs containers viaKnative.
Its giving me Integer Overflow both in java and C but when I tried it in Python it gave me right answer . Any reasons ? ``` long long int a = 1000000011/2 * 5 ; printf("%lld",a); ```
There are two reasons: Most computer languages use fixed-size integers. Today, that's often 32 bits. The correct result of your calculation, 2500000025, is a 32-bit number, meaning it's too big for asigned32-bit type. (It comes out as -1794967271 intwo's complement.) Python, on the other hand, is different: it usesarbitrary-precision arithmetic.In C, as in many computer languages, expressions are evaluated "inside out". If you sayfloat f = 1 / 2;you get 0, because the compiler performs integer division, without looking to see that you wanted to get a floating-point result. If you saylong long int a = 1000000011/2 * 5;you get an overflow, because the compiler performs integer arithmetic, without looking to see that you wanted to get along longresult.
Here I have provided the C code and it is not print any thing ``` #include <stdio.h> int main(){ int i=0; for(;;){ if(i==10) continue; printf("%d ",++i); } return 0; } ```
I believe that you want to stop the loop wheniis10not to have an indefinite loop ``` int main(){ int i=0; for(;;){ if(i==10) break; printf("%d ",++i); } printf("\n"); return 0; } `` ```
When I try to run some very basic code(literally 5 lines) I get the error: "'gcc' is not recognized as an internal or external command, operable program or batch file." mingw is installed and added to path and when I type gcc --version in cmd everything is fine. I'm using the VSCode editor and I'm running Windows 10.
Try to restart VSCode. I know that if you add/remove anything from PATH and VSCode was already running, you need to re-launch it for any PATH changes to work.
``` #include<stdio.h> int main() { int i=0; for(;;) { if(i==10) { continue; } printf("%d",++i); } } ``` This above code makes the output as without print anything.But by my logic it prints the value from 1 to infinite times except 10.The continue statement doesn't run the below code after continue statement but the continue statement is inside the if condition then why it shouldn't run the statement that are below the continue statement?
The output of C-programs is normally buffered, which is likely the reason why you don't see anything. Try printf("%d\n", ++i) as the linefeed will flush the buffer.Once i reaches 10, the number will not be increased any more, so your expectation that "it prints the value from 1 to infinite times except 10" will not be met.
I have a chrome extension that works with my exe file. I want to deliver just one exe file to my client. I tried converting the zip file into hex, but then I get a string with 25 thousand lines. I don't think that's the right way to do it. How can I deliver my zip file with my exe?
What you are trying to do is definitely doable, I've seen it being done many times. If you have MinGW installed, you can usexxdtool that will do the trick for you. ``` xxd -i your_zip_filename embedded_zip_data.h ``` Now you simply add#include "embedded_zip_data.h"in your source code and it will be right there in the application data.