question
stringlengths
25
894
answer
stringlengths
4
863
I'm trying to update a text on the terminal without have to print again the text. Right now I'm trying to do it on a simple code: ``` #include <stdio.h> #include <stdlib.h> #include <time.h> int main(int argc, char *argv[]){ for(int i=0;i<=100;++i){ printf("\r[%3d%%]",i); sleep(1); } printf("\n"); return 0; } ``` The code literally print nothing, with the pointer blinking at the start of the line.Can someone help me?
The standard output stream is typically line buffered, so if you don't print a newline (i.e.\n) then the output will remain in the buffer. After callingprintf, callfflush(stdout);. This will flush the standard output stream so that you can see the text.
Example use-case, do a thing for all types that contain the string "int". More precise, have a structPointin different versions asPoint__allocaorPoint__boehm, and then a macronewthat switches on that name. Hm, maybe macro stringification could do that?
Standard C supports only very limited introspection (examination of the program by itself) and nothing that would discern whether a type name contained particular characters or any ability to enumerate “all types” at all, let alone all types matching a criterion. In short, there is no support for the feature you request.
Here is a code for dynamic memory allocation usingmalloc ``` void main() { int *p,n=5; p=(int*)malloc(5*sizeof(int)); p[0]=10; // or *p=10; p[1]=20 // or *(p+1)=20; } ``` As per my knowledge,pis a pointer variable that points to the base address of the allocated memory. If I dont use the*operator, then I can't access the contents pointed to byp. But the statementsp[1]=20and*(p+1)=20do work the same. Why is this same and also what is the use of*if we can do it this way toop[1]But then does it also means that when i use malloc the array allocated to the process will have the same name as the pointer used to point the base address
The difference between *p and p[1] is that *p is a pointer that points to the first element of the array, while p[1] is the second element of the array. The difference is that *p gives you access to the entire array, while p[1] only gives you access to the single element.
I am trying to write a programe that will store data in a table of structures. My problem is that i can't figure out why my realloc isn't working. I am trying to realloc a table that is in a table of structures (sounds confusing, i know), but it won't work. Here is the part of my program i have a problem with: ``` typedef struct { int *node; int l; }przejscie_t; void czytaj(przejscie_t **graf, int vp, int vk){ *graf=realloc(*graf,(vp+1)*sizeof(przejscie_t)); (*graf)[vp].l=1; (*graf)[vp].node=realloc((*graf)[vp].node,(*graf)[vp].l*sizeof(int)); //it crashes here (*graf)[vp].node[(*graf)[vp].l]=vk; } ```
``` (*graf)[vp].node=realloc((*graf)[vp].node,(*graf)[vp].l*sizeof(int)); //it crashes here ``` reallocneeds a valid initialized pointer as first parameter (orNULL, in this case it stands as ifmallocwas called), since(*graf)[vp].nodeis not initialized you are passing garbage.
We recently learned opening files in the uni and the prof didn't tell us this. So I open a text file and do a check whether the file is equal to NULL or not. What if it is equal to NULL? It means that I have no data in the file? ``` FILE* file = fopen(filename, "r"); if (file == NULL) { return 1; } ```
if fopen() returns a NULL, it means that the file opening was not successfully accomplished, also in that case it sets the errno global variable is set to duplicate an error. You can also read 'man fopen' in your terminal for more details.
``` #include <stdio.h> struct dog { int name[10]; char breed[10]; int age; char color[10]; }; int main() { struct dog frodo; struct dog **ptr=&frodo.name; for(int i=0;i<10;i++) frodo.name[i]=i; for(int i=0;i<10;i++) printf(" frodo.name[%d]%d\n",i,frodo.name[i]); for(int i=0;i<10;i++) printf(" ptr =%d\n",ptr[i]); } ``` I tried using double pointer but the index is not matching when value is being printed. O/P: frodo.name[0]0 frodo.name[1]1 ptr =0 ptr =2
I expect thatptrshould be a pointer to the first element offrodo.namewhich is array of 10ints. Therefore the type ofptrshould beint*. Use: ``` int *ptr=&frodo.name[0]; ```
I was given a function that I have to fill out and it has these input parameters: ``` char * replace( const char * text, const char * (*word)[2] ) ``` From my understanding, the function should return a string and is given a string in the first parameter. The second parameter is an array of subarray that each have 2 strings if I'm not mistaken, but what is the meaning of the*(*name)[2], what is the difference between that and**name[2]And how would I call this array in the function? EDIT: How do Iusethis array in the function?
Due to array decay of functions parameters the function's declaration is equivalent to: ``` char * replace( const char * text, const char * word[][2] ) ``` So the second argument must be a 2D array ofconst char*. ``` int main() { const char * words[1][2] = { {"hello", "world"} }; replace("some text", words); } ```
I'm developing a keyboard tracker to track all the keys pressed by the user along with time. I found many blogs ongetnstimeofday(struct timespec*)but it's deprecated in latest kernel version because of the "year 2038 problem on 32-bit architectures". Its replacement function isktime_get_real_ts64but I'm not able to understand it. Can someone help me to give the basic idea to implement it or if you can share the working code?
You use it pretty much the same way you'd usegetnstimeofday: ``` #include <linux/time.h> #include <linux/timekeeping.h> //... struct timespec64 now; ktime_get_real_ts64(&now); struct tm tm_now; time64_to_tm(now.tv_sec, 0, &tm_now); //tm_now is similar to the userspace tm ```
``` #include <curses.h> #include <unistd.h> #include <iostream> int main() { initscr(); mvaddstr(10, 10, "Hello, world"); refresh(); sleep(4); endwin(); std::cout << "DONE\n"; } ``` I'm working on a project and I need to take down the curses windows for a while just to write a path to directory in cmd and then let the curses windows come back. I found this code on this site and tried to use sleep command in the code but it didn't work. So if anyone knew how to solve this please write it down here. Thnx :)
napmsis the (portable) curses function to use instead ofsleep
I am getting this error message while trying to run the following program "relational comparison result unused". ``` #include <stdio.h> int main(void) { int i, j; for(i = 0, j = 0; i < 10, j < 3; i++, j++) { printf("%i %i\n",i, j); } } ``` I am expecting a result ``` 0 0 1 1 2 2 ```
After adding two conditions It's not two conditions, you probably needi < 10 && j < 3. relational comparison result unused Asuser3386109mentioned, it's because the compiler discards the result ofi < 10caused by the comma, so you need to change it toi < 10 && j < 3. I am expecting a result 0 0, 1 1, 2 2 Actually, I'm getting this result. ``` 0 0 1 1 2 2 ```
As my understanding, I can compile my C code into 32bit binary or 64bit easily, but, some open source projects sais "We don't support 32bit CPU", so why?what makes the code source 64bit only? I already checked many topics, questions & responses, but all are related to the OS, CPU, and the compiled binary files. While my question is related to the code source itself.
The instruction sets of CPUs will vary, and the instructions available will vary depending on the mode it's running in. The program might rely on larger integers provided in 64-bit mode, or it might have assembler that uses 64-bit instructions. The different modes of operation also have different memory models. For example, a 32-bit Windows program can address 4 GiB of memory (a huge chunk of which it can't even use). On the other hand, a 64-bit Windows program can access virtually unlimited memory.
I am trying to make my own slice function, but for some value like (0,15) it is printing absurd value at the end. It is working fine for other inputs. Here is my code: ``` #include<stdio.h> void slice(int a, int b, char *str) { char new[b - a]; for (int i = 0; i < b - a; i++) { new[i] = str[a + i]; } puts(new); } int main() { char str[] = { "My name is Ayush Anand" }; slice(0, 15, str); return 0; } ``` What's wrong?
There should be extra room for a null-terminator. So, at the (b - a)th index, add one. ``` for (int i = 0; i < b - a; i++) new[i] = str[a + i]; new[b - a] = 0; // Null-terminator ``` As mentioned in one of the comments,a > bis invalid. So, add a condition before the declaration of the new string. ``` if (a > b) { fprintf(stderr, "a > b error"); return; } char new[b - a]; ... ```
I need to create a two dimensional array that looks like this: ``` [1 10 20 30] [2 11 21 31] [3 12 22 32] [4 13 23 33] [5 14 24 34] ``` I hope you got the logic. Each column starts with numbers like10or20and goes down until19or29. I honestly don't understand how I should do this. I tried the following code before: ``` int arr[10][10], i = 0, j = 0; for(i = 0; i < 10; i++){ for(j = 0; j < 10; j++){ arr[i][j] = i; } } ``` But the result is different from what I want. Could someone explain to me how can I create such two dimensional array? Thanks in advance.
you need one more variable. ``` int k = 0; int arr[10][10], i = 0, j = 0; for(i = 0; i < 10; i++){ for(j = 0; j < 10; j++){ k = j*10 + i; arr[i][j] = k; } ```
I'm trying to print non-printable characters in C files, but I can't print the given character because I don't know its meaning. I noticed this when I compared my program with cat. cat -nt file.txt: ``` 134 is 127 7f ``` cat -n file.txt: ``` 134 ^? is 127 7f ```
In theCaret Notation(whichcatuses when-vor-tis specified)^?representsthe DEL character(Unicode U+007F, ASCII encoding 127 decimal, 0x7f in hex).
five UARTs are used in my project,they all enable the DMA-RX channel and UART-IdleLine Interrupt to receive data of random lengths. In UART-RX interrupt,the data will copy from DMA buffer to the ring buffer of the specific UARTs. For every UART,I have to declare a DMA buffer and a ring buffer which may larger than DMA buffer.And Some UARTs like a PPP-UART have large data to receive,but the SRAM of my chip is limited and the interrupt is not allowed to nest.So I wonder is it possible that all UARTs use one DMA buffer. After testing this,it seems to work well 5 UARTs using the same DMA buffer.Anything that I should pay attention to?
Of course, you can't. DMA receive is happening without the core knowledge. If more than one UART will receive data the data will be corrupted. The interrupts only inform you if the DMA controller has reached the end (or middle) of the buffer or if UART receiver (if capable) is idle for a particular time.
I'm trying to copy a string of characters in another string using dynamic memory allocation but it doesn't work: ``` #include <stdlib.h> #include <stdio.h> int main() { char* s1, * s2, * s3; s1 = (char*)malloc(11 * sizeof(char)); s2 = (char*)malloc(11 * sizeof(char)); s3 = (char*)malloc(11 * sizeof(char)); fgets(s1, 11, stdin); fgets(s2, 11, stdin); int i = 0; do { *(s3 + i) = *(s1 + i); i++; } while (*(s1 + i) != '\n' && *(s1 + i) != '\0'); puts(s3); return 0; } ```
You do not null terminate thes3string. ``` } while (*(s1 + i) != '\n' && *(s1 + i) != '\0'); s3[i] = 0; puts(s3); ```
I have function in C with 3 params. I want to call that function with pre-defined values. Is there any solution? My idea which does not work. ``` #define PRE_DEFINED_MACRO (10, 15 , true) void myFunc(uint8_t temp, uint32_t value, bool valid) { .... } .... //call the function like that myFunc(PRE_DEFINED_MACRO); ```
Your macro already includes parentheses, so when this ... myFunc(PRE_DEFINED_MACRO); ... is expanded, the result is: ``` myFunc((10, 15 , true)); ``` You could do this instead: ``` myFunc PRE_DEFINED_MACRO; ``` I find that pretty confusing, however. Personally, I would prefer to remove the parentheses from the macro's replacement text: ``` #define MYFUNC_ARGS 10, 15 , true // ... myFunc(MYFUNC_ARGS); ``` That makes it much clearer that the call tomyFunc()is, in fact, a function call. The choice of macro name also makes the intended purpose of the macro much clearer.
I'm not too sure how to troubleshoot or understand what could be happening, any help would be appreciated and if there is any clarification needed I would be more than happy to provide, Thanks!
The string you're constructing inrandoesn't have a terminating null byte, soatoiwill read past the bytes you've written into the ones you haven't (and possibly past the end of the array), which is what valgrind is telling you. You'll need to manually terminate the string after reading the characters. ``` while(line[i] != ',') { ran[k] = line[i]; i = i + 1; k = k + 1; } ran[k] = 0; ```
The code is supposed to print out 13:Hello World!, but the output is only 13:. ``` #include <stdio.h> int main(){ char *str = "Hello World!\n"; int Laenge= 0; while (*str++){ ++Laenge; } printf(" %d:%c\n", Laenge, *str); return 0; } ```
You setstrto point to the beginning of the string, and then you incrementstrtill you get to the end. By that time,stris now pointing to the end of your string. Try using a different pointer to walk through your string, or just save a copy of the pointer for later use. It also looks like you're syntax is wrong for the print statement. I haven't coded in C for decades. I'm a Python user now. But I think*strwould reference one char, and you want to reference the entire string. So ifstrwas not corrupted, use%sandstrinstead of%cand*strin yourprintf().
I am using the below code to make a HTTPSGETrequest. I'd like to keep the connection alive to make multiple requests without having to connect each time, so I set"Connection: Keep-Alive\r\n". However, once I did this, the behaviour changed and the code now blocks onBIO_read()(equivalent to::recv()). Now I cannot return to process the received data. How can I only connect once, but not block onBIO_read()/::recv()?
You have to pay attention to what you read. Parse the response headers. There would be wither a "Content-Length: xxx", or "Transfer-Encoding: chunked". That woukd give you an information on where the body ends.
In my game/program.. I am editing my obj_list, item_list etc. like item_list[0] = hp_potion.. Instead of this, I really want to do this: item_list.append(rect). So I can get rid of writing every single index and remembering them to add another variable. If there is a solution. I am happy to know that. Thanks for your time. I tried for loops etc. Nothing works like python syntax.
C does not provide a built-in function to add an element to an array. Arrays in C are fixed length. But Python lists can grow dynamically. If you want to implement Pythonlistlike structure in C, you can uselinked listwith dynamic memory allocation.
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed10 months ago.Improve this question Code: ``` #include <stdio.h> #define puts "%s C preprocessor" int main() { printf(puts, puts); return 0; } ``` Output: ``` %s C preprocessor C preprocessor ``` See also... Can anyone explain me the logic behind this output? I tried to solve it,but I didn't get the proper explanation through my friends. If anyone can explain me ,it'll be very helpful.
The macro let to (code after linker): ``` int main { printf("%s C preprocessor", "%s C preprocessor"); return 0; } ``` printfworks like: The output is then ``` %s C preprocessor C preprocessor ```
I have tried to use tflite default package in Keil MDK environment, but I am facing some compiling problems. project code My Device: Armv8-M Mainline based device My TFlite runtime environment: runtime environment There are hundreds of errors existed. error type1 error: use of undeclared identifier 'EAFNOSUPPORT'/.../... error type2 error: use of undeclared identifier 'errno' What's maybe going wrong? I tried to compile the package in an empty project with the same environment settings, and it could be compiled instead of such as errors.
I solved the problem by disabling the redefined symbol in ROM.lib file.
I am a newbie in C. I am trying to build a whitelist program that returns 0 if a character in the given string(user_data)is not in the list of'ok_chars' ``` #include <stdio.h> #include <string.h> static char ok_chars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890."; char user_data[] = "Bad &"; char * cp = user_data; const char * end = user_data + strlen (user_data); for (cp += strspn(cp , ok_chars); cp != end; cp += strspn (cp , ok_chars)) { //*cp = '_'; if(user_data not in ok_chars){ //I don't know how to implement this return 0; } } ``` Kindly assist.
``` int isOK(const char *needles, const char *haystack) { int result = 1; while(*needles) if(!strchr(haystack, *needles++)) { result = 0; break; } return result; } /* .... */ if(!isOK(user_data, ok_chars)) return 0; /* .... */ ```
In Cython one can use exact-width integral types by importing them fromstdint, e.g. ``` from libc.stdint cimport int32_t ``` Looking throughstdint.pxd, we see thatint32_tis defined as ``` cdef extern from "<stdint.h>" nogil: ... ctypedef signed int int32_t ``` Does this mean that if I useint32_tin my Cython code, this type is just an alias forsigned int(int), which might in fact beonly 16 bits wide? The issue is the same for all the other integral types.
They should be fine. The typedefs that are really used come from the C stdint.h header, which are almost certainly right. The Cython typedef ``` ctypedef signed int int32_t ``` Is really just so that Cython understands that the type is an integer and that it's signed. It isn't what's actually used in the generated C code. Since it's in acdef externblock it's telling Cython "a typedef like this exists" rather than acting as the real definition.
``` #include <stdio.h> #include <string.h> int main() { char first[] = "This is the first part of"; char second[] = "the full string, this being the second half\n."; char buffer[70]; strcpy(buffer,first); strcat(buffer,second); puts(buffer); return 0; } ``` I am receiving the error on strcat function, please assist
It seems that the size of the arraybufferis not large enough to contain the concatenated strings. Declare it at least like ``` char first[] = "This is the first part of"; char second[] = "the full string, this being the second half\n."; char buffer[sizeof( first ) + sizeof( second ) - 1]; ```
Considering :value: An unsigned integer on 32 bits. pos: which is the index of the bit to get from value. ( The index 0 is the first bit so the lowest value ) I want to implement a functionget_bit(value,pos)so that it retruns the value of the bit (0 or 1) from the unsigned integervalueat indexpos for example value = 5 (0101 in binary) thenget_bit(5,0)=1 get_bit(5,1)=0 get_bit(5,2)=1 Can you explain me what is the most optimized way to solve this problem ?
You can achieve it with ``` (value >> pos) & 0x01; (value >> pos) // Shift the value pos positions to the right & 0x01; // Only take the first bit (lowest value) ``` I recommend researching "bit shift" (the>>) and "bit mask" (the&) for examplehereto get a better understanding about the subject.
The line in question is: ``` #if ! defined(_VALUE) foo = 23; #endif ``` It seems to build, but I am not sure its behavior is as expected.
Your example tells the preprocessor to exclude the text if "_VALUE" is defined; else to include it. Most compilers give you an option to "display preprocessor output", e.g. "-E" for gcc: x.c ``` #if ! defined(MY_DEFINITION) foo = 23; #endif ``` Sample output: ``` $ gcc -E x.c # 1 "x.c" # 1 "<built-in>" # 1 "<command-line>" # 1 "x.c" foo = 23; $ gcc -E -DMY_DEFINITION x.c # 1 "x.c" # 1 "<built-in>" # 1 "<command-line>" # 1 "x.c" ``` Here is a good overview:C - Preprocessors
In C (let's say C11 if we need to specific), is the following program well-defined? Will it always printa=3 b=4or could compiler optimizations affect the output? (The real-world motivation is to provide a read-only public "view" of a struct that is only supposed to be modified by a particular module, i.e. source file.) ``` #include <stdio.h> #include <stdlib.h> struct obj_private { int a; int b; }; struct obj_public { const int a; const int b; }; int main(void) { void *mem = calloc(1, sizeof(struct obj_private)); struct obj_private *priv = mem; struct obj_public *pub = mem; priv->a = 3; priv->b = 4; printf("a=%d b=%d\n", pub->a, pub->b); return 0; } ```
These two types arenotcompatible. What you should be doing instead is using a pointer to aconstobject. ``` struct obj_private *priv = mem; const struct obj_private *pub = mem; ```
Now I'm writing a makefile for my C project, and I want to implement a RELEASE&DEBUG compilation branch, it's like the script within the makefile could know which target name the user inputted in the command line, then it can decide what kind of GCC options it will use to compile the current program, is there any way to achieve this? Thank U. I tried to define a variable in the makefile and pass its value through the command line likemake type=release, but this is not what I wanted.
Assuming you're talking about GNU make then there is: look up theMAKECMDGOALS macroin the GNU make manual. But, this is really not the right way to do things. I recommend that instead you look uptarget-specific variablesin the manual and see if that gives any ideas.
The number n^k is entered, I need to output the value in a character array-string I have no idea how to write the code
Your problem does not seem well specified. You are not describing the problem or the limits in detail. Regardless, here is some simple code to hopefully get you started. ``` #include <stdio.h> #include <math.h> int main(void) { int n; printf("Enter N:\n"); scanf("%d", &n); int k; printf("Enter K:\n"); scanf("%d", &k); int result = pow(n,k); char text[100]; sprintf(text, "%d", result); printf("The Answer is %s\n", text); return 0; } ```
i want to write a program in C that will give PI using Wallis Formula ``` #include<stdio.h> #include<math.h> int main() { long int i; double sum=1, term, pi = 0; /* Applying Formula */ for(i=1;i< 1000000;i++) { term = pow((2*i),2)/((2*i-1)*(2*i+1)); sum = sum * term; } pi = 2 * sum; printf("PI = %.10lf",pi); return 0; } ``` i wrote that code and it keeps giving me PI = -inf
Your problem seems to be, that your integer variableiis a 4-Byte value. Whenthe denominator((2*i-1)*(2*i+1))is evaluated, you get an overflow ifiis greater than about 23170(Sqrt(2^31) / 2). With the loop boundary set to 23170 your formula works. It also works when using an 8-Byte integer foritogether with your original loop boundary.
I am trying to code the summation of the following series: I can't figure out how to alternate the sign from "-" to "+" to "-" and so on.... Here is my code: ``` #include<stdio.h> int main() { int i=1,n; float sum,num,den; den=2; sum=0; printf("Enter number of terms for summation: "); scanf("%d",&n); for(i=1;i<=n;i++) { num=i*(i+1); den=den*(i+2); sum+=num/den; } printf("%f",sum); } ```
Start a variable at 1. ``` int coeff = +1; ``` then: ``` sum += coeff * num/den; coeff *= -1; // Toggles -1 to +1 and back to -1 each loop. ``` Whencoeffis +1, then the expression is+1 * -1, which results in-1. Whencoeffis -1, then the expression is-1 * -1, which results in+1. the variable keeps toggling back-n-forth between+1and-1.
When I use this ``` comparer.exe <test_comparer24_1>.bmp <test_comparer24_2>.bmp ``` in cmd, this error show up The specified file could not be found even thought I have the bmp files in the same folder. This is the part of code: ``` int main(int argc, char *argv[]) { if (argc != 3) { fprintf(stderr, "Use the format: %s <filename1>.bmp <filename2>.bmp\n", argv[0]); return -1; } return BMPComparer(argv[1], argv[2]); } ``` any ideas to help me figure this out ?
The<and>characters are likely included in the help text to indicate that you should replace the contents. The characters<and>have a special function on most shells and are calledredirections. Please try your command without the<and>characters: ``` comparer.exe test_comparer24_1.bmp test_comparer24_2.bmp ```
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.Closed10 months ago.Improve this question Hi I was wondering if there is an alternative ofstr.substring()instring.h. If not, what is an efficient alternative?
Assuming that we all agree that using c++ it is safer and more professional to use the standard library tools. That said, if we're talking about C and not C++, this should be one of the ways to extract a substring with the "string.h" library: ``` #include <stdio.h> #include <string.h> int main() { char test[] = "abcdef"; char subtext[3]; memcpy(subtext, &test[1], 2); //Result: "bc" subtext[2] = '\0'; printf("%s", subtext); return 0; } ```
During the aeronmd's main process of aeron-driver in c code, functionaeron_driver_context_bindings_clientd_create_entriesis invoked twice, one inaeron_driver_context_initand another inaeron_driver_init. Is that a duplication? or there are some reasons for the design consideration?
This method does two things, it allocates space for bindings and it allocates space for interceptors. There are some bindings that need the space earlier in the initialisation phase, so we pre-create some space up front. However, it is still possible to add interceptors after the context has initialised, therefore we need to double check that there is space in the list available for those as well. There is probably a refactoring to separate out the state information of transport bindings vs interceptors and initialise them separately.
I am writing a cache lab in C and I have got the whole input file to print in a char array, but any and all help for my cache lab online uses int to hold the input file, so I am thinking I need that too. I have a three input files. One holds: ``` 10 20 22 18 E10 210 12 ``` I can get 10, 20, 22, 18 to print: ``` FILE* file; int address; file = fopen("address01" , "r"); while (fscanf(file, "%d", &address)) { printf("%d\n", address); } fclose(file); ``` but it stops after 18 since the next input is a char. I know characters can be held as an int on their own, so how can I also do this with the E and the 10 being together?
You can use the%xformat specifier to read hexadecimal values into anint. For example: ``` int address; if (fscanf(file, "%x", &address) == 1) { printf("%d\n", address); } ``` This will read the hexadecimal valueE10into theintvariableaddress.
``` #include <stdio.h> int main(){ int number[]; scanf("%d", &number); int counter = 0; while (counter < number){ printf("%d\n", counter); counter += 1; } } ``` I am getting an error saying that an integer cant be compared with a pointer but im not sure how to fix it and dont understand why it doesnt work,. ``` type here ```
This declaration of an array of incomplete type ``` int number[]; ``` is invalid. Just declare an object of the typeintlike ``` int number; ``` There is no any need to declare an array. Instead of the while loop ``` int counter = 0; while (counter < number){ printf("%d\n", counter); counter += 1; } ``` it is better to use for loop like ``` for ( int counter = 0; counter < number; ++counter ){ printf("%d\n", counter); } ``` because the variablecounteris used only in the scope of the loop.
Suppose for an embedded program, the hardware is designed such a way that it performs certain operation if the memory address 0x8729 is filled with 0xff. Is there a way to access the memory address 0x8729 and write to it?
Try this: ``` uint8_t * p_memory = (uint8_t *) 0x8729; const uint8_t value_from_memory = *p_memory; *p_memory = 0xff; // Writing to memory. ``` You may not need the cast, but I put it there anyway. Explanation: Declare auint8_tpointer and assign to your memory address.To write, dereference the pointer and assign your value.To read, dereference the pointer and assign the value to your variable.
There is a function like this. I took this error expected identifier or '(' before 'void' How to solve this problem? Thank you. ``` struct node * void ekleSirali(struct node * r,int x){ if(r==NULL){ r=(struct node *)malloc(sizeof(struct node)); r->next=NULL; r->x =x; return r; } ``` I don't know whether I should write struct.
The type specifiervoidis redundant and invalid in this context. Write ``` struct node * ekleSirali(struct node * r,int x){ ``` That is the function return type can be eithervoid(if the function returns nothing) orstruct node *(if the function returns a pointer of the typestruct node *as shown in your code snippet).
I have an array ofuint64_tvaluesuint64_t *data;in where I need to store 4 different data types:int,char*,bool,float. I solved every type by simple casting to(uint64_t), but it doesn`t work for float: ``` float val = 1.5f; uint64_t var = (uint64_t) val; printf("%.1f", (float) var); // prints 1.0 ``` Is there a way to move data between variables on even lower level than casts? I've tried to combine casts in every way but the result was0.0or1.0.
... to storefloatvalue inuint64_tvariable ... Copy it. ``` float var_f = 1.5f; uint64_t var_u64; _Static_assert(sizeof var_f <= sizeof var_u64, "Wide float"); memcpy(&var_u64, &var_f, sizeof var_f); ``` To recover ``` memcpy(&var_f, &var_u64, sizeof var_f); printf("%g\n", var_f); ```
I am trying to understand line 231 here:https://github.com/erich666/GraphicsGems/blob/master/gems/Roots3And4.c Where it saysnum += SolveQuadric(coeffs, s + num);withnumbeing an int andslooking to be an array of doubles. The K&R assumption is because of the function declaration where after parenthesis and before the body curly bracket the type and size of the arrays are defined. So if this really is an array and an int added, what is the outcome? The int added to every entry in the array? extending the array? or something completely different? I am trying to port the code and I am not sure how to read this part.
``` num += SolveQuadric(coeffs, s + num); ``` wheresdouble array andnumis an integer. s + numgives the reference of then-th element of the array.
I need to write a recursive function with 2 parameters that calculate the result of their multiplication byonly using addition exemple : mult(2,5)=>10 I wrote the function but I think that I'm missing something in the return ``` int mult(unsigned int num1, int num2) { if (num1 == 0) return 0; return mult(num1 - 1, num2); } ```
You should return: ``` return num2 + mult(num1 - 1, num2); ```
What is a merit for the signed int return value of memcmp compared to say bool? I don't think I've ever used the return value of memcmp other than to compare it against zero.
What is a merit for the signed int return value of memcmp Useful for sorting objects based on their binary representation. Note:memcmp()returns a +,0,- based on the first mismatched byte as if bytes areunsigned char, notchar.
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed10 months ago.Improve this question i keep getting a conflicting type error when i get try to compile my code the function declaration was made in my header file and the function itself was created in another file but yet i still keep getting a an error. need help with this i was expecting compilation success
To Remove This Error, Rename_exit()Method To Something Else,Since another Method With Same Name Is Declared In The Libraries You Have Included Inmain.hfile.That's All You Just Need To Do.
thank you for taking your time to help me with my problem. The problem basically is that I am supposed to have two functions and a main function. The first function is supposed to open a file a second function is supposed to put them into two dynamic arrays. I have found useful article on how to use a file as a parameter for other function but that solves only half of my problem. The thing I can not help myself with is actually opening it in a non-main function a returning it back to main and sending it to different non-main function.
you need something like this ``` FILE *openFile(){ FILE * f = fopen("myfile","r"); return f; } ``` then do ``` FILE* f = openFile(); int c = fgets(f); ... ```
I have address of an struct store in int variable. Can I dereference the struct?? say: int x = 3432234; // memory address of struct now I want to access the some struct from it. I have been suggest these steps. store the address in an int variablecast that int to a struct pointerthen dereference it But don't know how to apply.
If you have astruct foo, the easy way is to not use anint xbut make the type a pointer-to-struct foo,struct foo *x. One can use thearrow operatorto access members from a valid pointer directly. ``` #include <stdio.h> struct foo { int a, b; }; int main(void) { struct foo foo = { 1, 2 }; struct foo *x = &foo; printf("%d, %d\n", x->a, x->b); } ``` Sometimes, hardware requirements complicate this, but this is the simple solution.
I use-Werror ... -Wno-unknown-pragmascompiler flags (cause I don't need unknown pragmas to cause an error). However, this silences all unknown pragma warnings. Is there a way to produce-Wunknown-pragmaswarnings while not turning them into errors, and to apply-Werrorto all other warnings.
-Werror -Wno-error=unknown-pragmasshould do the trick.
According to FSH UNIX Sockets shall be created in/run(or on legacy distros in/var/run). I am trying to create a socket in a non-root application in that directory and get error 13. Is/runonly for services started via systemd/init? If so, where do you put UNIX sockets from user applications?
Is /run only for services started via systemd/init? For root, yes. where do you put UNIX sockets from user applications? On modern systems in$XDG_RUNTIME_DIRif the variable is set, with fallback to/run/user/$UIDif not set. For portability, you can use/tmp. Usually$XDG_RUNTIME_DIRwill be just set to/run/user/$uid. https://renenyffenegger.ch/notes/Linux/fhs/run/user/uid/indexhttps://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
I want to shutdown PC with C without using system() functiom ``` #include <stdio.h> #include <Windows.h> int main(){ system("shutdown -s -t1"); } ``` I'd like to find better way.
You can shut down the Windows operating system using the functionExitWindowsExwith theEWX_SHUTDOWNorEWX_POWEROFFflag. However, as stated in the documentation, the calling process will require theSE_SHUTDOWN_NAMEprivilege. See the documentation on how to allow the process to obtain that privilege.
``` #include<stdio.h> int main() { char main[]="Structured Programming"; char copy[30]; for (int i = 0; main[i] !='\0' ; i++) { copy[i]=main[i]; } printf("%s",copy); } ``` In the above problem this just should printStructured Programming, but I'm gettingStructured Programming a, this happens on all ide's, but not on online compilers, online compilers are working fine, can anyone tell me the reason?
Sometimes "undefined behavior" means it appears to work. You can initializecopy, or simply copy the NUL: ``` i = 0; do { copy[i] = main[i]; } while (main[i++]); ```
Made a C for-loop, and it doesn't get into it. It just skips it entirely, and I don't know why ``` int main(void) { int N = 5; int input; scanf("%d", &input); int c; for(c=0; c==N; c++) { srand(time(0)); int random = rand() % 99; printf("Loteria: %d\n", random); if (input == random) { printf("\nAcertou!\n"); } } return 0; } ```
It appears you misunderstood the for loop termination condition. Theconditionpart infor ( ; condition ; )does not specify when to stop, but how long to continue if true. A tiny change of your condition should work: ``` for (c = 0; c < N; c++) { ``` This is the idiomatic code to iterate a loop exactly N times.
To debug myCcode I compile it with the-gflag and uselldbto see where myseg faultis for example.I use the-gflag so the output oflldbis inCnotAssembly.but now I have a multiple files project andlldbshows onlyAssemblyeven tho I'm using the-gflag, it's like the-gflag applies only to one file.Example: ``` gcc -g example.c lldb a.out >run I get c code here ``` ``` gcc -g example1.c example2.c main.c lldb a.out >run I get assembly code here ``` Can anyone tell me what I'm I missing here?and how can I get c code inlldb. Thanks in advance.
When you justrunthe program you shouldn't be getting code at all. You will be getting code if the programstopsrunning. Then you need to look at the call stack to make sure you're actually in your own code. If you're in library code then it will likely not have source available and you'll get assembler code. Goupthe call-stack until you reach your own code.
This question already has answers here:How do I work with dynamic multi-dimensional arrays in C?(9 answers)Closed10 months ago. I am curious how the best programmers in the world allocate memory for a 2d array. Any tips and advice will be much appreciated. PS I am just a student trying to learn.
Use array pointers ``` { size_t rows = 10; size_t cols = 50; int (*array)[cols] = malloc(rows * sizeof(*array)); /* ... */ free(array); } ```
I'm using GCC version 10.2.1 in Linux Debian (x86-64). i write this c code: ``` #include <stdio.h> int main() { printf("Hello World!"); return 0; } ``` Now my question is how can compile and run this code forarmv7l? Target system Is a evaluation board thank you
you can usearm-linux-gnueabihf-gcc hello.c -o hellocommand . and befor you should install arm-linux-gnueabihf-gcc in your linux system . here is full sample that work for me
When using a floating point constant in C, what's the difference between usingEande(orGandg, for that matter)? For example, what's the difference between1.575E1and1.575e1? Isn't C supposed to be a case-sensitive language? If there's no difference between usingEande, why's that? I've looked it up online and on the textbook I'm using and haven't been able to figure it out.
There is no difference.1.575E1is the same as1.575e1. Just like there is no difference between0xaand0xA—they are both equal to10, and have the same type. In C, identifiers are case-sensitive. Identifiers are names of functions, types, variables, etc.
I have this program with me. Where I am trying to concatenate a user input to a command, inorder to execute it in a wsl environment. ``` #include<stdio.h> #include<stdlib.h> int main(){ char cmd[100]; char usr_in[50]; fgets(usr_in, sizeof(usr_in), stdin); cmd = snprintf(cmd, sizeof(cmd), "ping %s", usr_in); system(cmd); return 0; } ``` But this gives me the following error during compilation. ``` error: incompatible types in assignment of ‘int’ to ‘char [100]’ cmd = snprintf(cmd, sizeof(cmd), "ping %s", usr_in); ``` I am not able to figure out which integer assignment it is talking about. Thesizeof(cmd)is the only integer there and it is a valid argument to thesnprintf.
snprintfreturnsint(the number of characters printed) and you are trying to assign the return value tocmdwhich ischar[100].
I have the exercise to control the input of the eip/rip register (in my case rip) arbitrarily. The following program is given: ``` #include <stdio.h> #include <string.h> #define VAR_SIZE 32 void output(int argc, char** argv) { char stack[VAR_SIZE]; strcpy(stack, argv[1]); printf("%s\n", stack); } int main(int argc, char** argv) { output(argc, argv); return 0; } ``` We may use the debuggergdb. Unfortunately I have no idea where to start.
In order to set the value of the RIP x86-64 register, you can use the following command ingdb: ``` set $rip = 20 ``` This will set the value of the register to20.
I have a small code that I need to know the complexity of and can't figure it out myself, can someone help/guide me to the solution? ``` int funn(int n) { int i, j, k = 0; for (i = n / 2; i <= n; i++) for (j = 2; j <= n; j = j * 2) k = k + n / 2; return k; } ``` at first, I thought that the complexity is O(n) but there are some multiplications that I'm not sure of. I'm new to that stuff so I need a guidance
The outer loop is (n/2) which is O(n). The inner loop is O(log n). So the whole thing is O(n log n).
I have this issue where I need to square line in Pascal's triangle and when it comes to big numbers it only outputs0 ``` unsigned long sum_squared(const int line){ unsigned long long n = 2*line; unsigned long long x1 = factorial(line); unsigned long long k = x1*x1; unsigned long long x = factorial(n)/(k); return x; } unsigned long long factorial(unsigned long long n) { if (n == 0){ return 1; } return n * factorial(n - 1); } ``` I test it with: ``` printf("%lu\n", sum_squared(14)); ```
The key word here is"outputs". You need the correct format specifier to outputunsigned long long:%llu.
Can someone plz explain me what is the diffrence between those tow lines and when we will want to use each one of then ``` int array[] = { 1, 2, 3 }; // init a regular array int *numList = {1, 2, 3}; // init an array of pointers? ``` I am expecting that there are probably seenarios we will want to use the second over the first, But when? Thank You in Advance
You're conflating some concepts. As@ikegaminoted, your second line: ``` int *numList = {1, 2, 3}; ``` Gets treated as: ``` int *numList = 1; ``` Which not an array, nor a valid pointer. If you want to create an array of pointers, you use the same syntax as normal arrays, with the type being a pointer: ``` int* numList[] = { &array[0], &array[1], &array[2] }; ``` Will create an array of 3 int pointers, pointing to your original array's elements.
My C program receives a certificate chain from a server and stores it in a buffer (certs in DER format). Is it possible to find out where the leaf certificate is stored within this buffer and the length of it by using the openssl library? I need this information to be able to calculate a checksum based only on the contents of the leaf certificate. Parsing certificate chains seems like a common task, so I suppose there should be support for it by the openssl library.
The solution to my question was to parse the buffer using d2i_x509() to find each certificate.
This question already has answers here:How can I print a quotation mark in C?(9 answers)Closed11 months ago. How to print"inprintf("something equal "x(as char)" ")??
``` #include <stdio.h> int main(void) { printf("something equal \"x(as char)\" "); return 0; } ``` In C, the escape character is\. So to print a literal", instead of using it to end a string, use\".
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed11 months ago.Improve this question Feedback after running code in vscode; ``` gcc : The term 'gcc' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:40 ``` The code I input; ``` #include<stdio.h> int main() { printf("Hello World") } ```
you need to install the gcc compiler on your system and it add to path. here u can take help. https://www.scaler.com/topics/c/c-compiler-for-windows/
I simply want to pass an&arrin C language. For example: ``` #include <stdio.h> void test( PARAMETER??? ) { return; } int main() { int arr[] = {1,2,3,4,5,6,7,8}; test(&arr); return 0; } ``` How should I declare the parameter? As it is of typeint (*)[8] I simply want to pass&arrin C language. I know I can passarrandlengthargument, but how can I via this?
As it is of typeint (*)[8] If you want to pass&arr, then that is exactly the type you need to declare the parameter as, eg: ``` void test(int (*param)[8]) { // use param as needed... } ```
``` char ch; int nr=0; printf("\n: "); ch = getchar(); while(ch != 'q' && ch != 'Q'){ ch = tolower(ch); if(ch == 'a' || ch == 'e' || ch == 'o' || ch == 'i' || ch == 'u') nr++; printf("something"); ch = getchar(); } printf("vocale: %d", nr); ``` its supposed to count the number of vowels until the user presses q or Q. it's such a silly program and yet i cant get past it.
Instead of usinggetchar ``` ch = getchar(); ``` that also reads white space characters usescanflike ``` scanf( " %c", &ch ); ``` Pay attention to the leading space in the format string. It allows to skip white space characters. For example ``` while ( scanf( " %c", &ch ) == 1 && ch != 'q' && ch != 'Q'){ ``` Also it will be more safer to write ``` ch = tolower( ( unsigned char )ch ); ```
I found out that structures without any named members (and without any members in particular, as I understood)invokeUB in C. Only GNU GCCsupportssuch structures as an extension. I've tried to create a piece of code which will behave differently when compiled using GCC vs. Clang but with no success. I'm wondering if there is a C program that if you compile it via Clang, it will work differently than if it was compiled using GCC. The opposite option, in a nutshell, is that Clang also supports empty structures but this is not mentioned in documentation.
Literally the only thing I could find in clang's documentation is some info about a warning-Wgnu-empty-struct, which will be activated in-pedanticmode. So the compiler clearly supports GNU empty structs. As for where to find the clang documentation regarding how empty structs should be used, what they are good for and under which language standards they are valid, I have no idea.
I have the following piece of code that writes the value oftimeinto thetempbuffer. ``` #include<stdio.h> int main() { unsigned char temp[8]; unsigned int time = 0x00101010; sprintf(temp, "%x", time); } ``` Bothtempandtimeare unsigned values; however, I still get the following warning: ``` Pointer targets in passing argument 1 of ‘sprintf’ differ in signedness ``` Can someone please explain why I am getting this warning and how to remove it?
Either do: ``` #include<stdio.h> int main() { char temp[8]; unsigned int time = 0x00101010; sprintf(temp, "%x", time); } ``` or ``` #include<stdio.h> int main() { unsigned char temp[8]; unsigned int time = 0x00101010; sprintf((char*) &temp, "%x", time); } ``` sprintf is defined assprintf(char*, const char*, ...), so the first argument needs to be a signed char pointer.
int* pointer=10;I want a variable which directly points to the contents of stored adress inpointer. The cause of this act is that I have variable:dummy_type a;Thisa, has been used many time in my code. I've decide to allocateawith my static pool memory. Through the process of allocation I can have just it's pointer. But I need it's dereferenced version having name likea. For example:int a=5;then you can extract it's pointer. But if you haveint* pa=adressyou can not create a dereferencea. But I needa.
I think what you want is something like this: ``` type_t * a_pointer; #define a (*a_pointer) ``` If you remember to allocate memory at the right time and store your pointer ina_pointerthen you don't need to change the rest of your code that was written to usea.
I'm on windows 10, It used to work before i don't know why it stopped working, it gives the error message "Formatting failed. See the output window for details." refer to I've looked for a solution online but what I've found is people saying to use a different extension rather than the default c/c++ formatter which i really don't want to do, why ? it changes my code theme i just want this fixed i don't want a replacement
Fixed! just updated to the pre-release version of the c/c++ extension and it worked like a charm, you can update it back later :)
``` #include <stdio.h> int main(int argc, char *argv[]) { int a[4] = {20, 4, 7, 8}; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (a[i] < a[j]) { a[i] = a[j]; } } printf("%d\n", a[i]); a[0] = 20; a[1] = 4; a[2] = 7; a[3] = 8; } } ``` I simply trying to show the output as descending order but not getting expected result Expected : 20 8 7 4 Error follows: 20 20 20 20 Please help me to rectify ..
You aren'tswappinga[i]witha[j], you're simply copying the value ofa[j]toa[i]. To do a swap, you needthreeoperations: ``` int tmp = a[i]; // save the value of a[i] a[i] = a[j]; // write a[j] to a[i] a[j] = tmp; // write saved value of a[i] to a[j] ```
I understand why stl indices are unsigned, because you would never have a negative index. But for normal C arrays, the indicesaresigned. Why is this? If there is a good reason for C array indices to be signed, why did they decide to make stl indices different?
Array indexing in C is really just a pointer offset.x[y]is exactly the same as*(x + y). That allows you to do things like this: ``` int a[3] = { 1, 2, 3 }; int *p = a; /* p points to a[0] */ printf("p[1]=%d\n", p[1]); /* prints 2 */ p += 2; /* p points to a[2] */ printf("p[-1]=%d\n", p[-1]); /* prints 2 */ ``` Which is why negative array indexing is allowed.
I have to get a string from keyboard, and then print only the numbers from the char, but with the actual value. **Example ** Input: I am 19 years old output: 19 (as an integer) I wrote this code, but I cant convert it whatever I do. ``` #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> void main() { char sir[20]; int i=0; printf("Introduceti varsta sub forma - Eu am X ani. - : "); gets(sir); while(sir[i]!='\0') { if(sir[i]>='0' && sir[i]<='9') { int nr = atoi(sir[i]); printf("%d", nr); } i++; } ```
The functionatoiexpects a pointer of the typechar *while you are passing an object of the typechar. Instead of this record ``` int nr = atoi(sir[i]); ``` just write ``` int nr = sir[i] - '0'; ``` Pay attention to that the function gets is unsafe and is not supported by the C Standard. Instead use fgets.
This is my code ``` #include <stdio.h> int isPrime(int n) { if (n == 1 || n == 0) { return 0; } for (int i=2; i <= n/2; i++) { if (n%i == 0) { return 0; } } return 1; } int main() { int n = 2; isPrime(n); return 0; } ``` I try to run my program, but there is none of return value. Why and how can i fix this?
C is not aREPL. It will only print what you explicitly tell it to print: ``` printf("%d\n", isPrime(n)); ``` In the context ofmain()you could alsoreturn1that and check in the shell: ``` return isPrime(n); ``` Where then you can do: ``` ./isprime && echo "Is prime!" ``` 1Keep in mind this worksonlyforintreturn values, and that0means success or in C parlance: "No error".
My file structure looks like this: primaryFile.hprimaryFile.csecondaryFile.hsecondaryFile.c primaryFile.h has: ``` #include secondaryFile.h typedef struct{ secondaryStruct member} primaryStruct; extern primaryStruct pStruct ``` secondaryFile.h has: ``` typedef struct{ uint8_t member} secondaryStruct; ``` Now I want to editpStruct.memberinsecondaryFile.c. But if I includedsecondaryFile.hinprimaryFile.hI can't include it back now. What am I supposed to do to editpStructinsecondaryStruct.c?
OK, I'm just dumb, I should have done#include "primaryFile.h"insecondyFile.cnot in.hin order to modify struct members.
I want to create a macro that adds a prefix to the argument and calls it as a function. Something like this: ``` #define FUNC(name) /* some code */ FUNC(add) // => __some_function_name_prefix__add() FUNC(subtract) // => __some_function_name_prefix__subtract() FUNC(multiply) // => __some_function_name_prefix__multiply() FUNC(divide) // => __some_function_name_prefix__divide() ``` This is what I have tried: ``` #define FUNC(name) __some_function_name_prefix__name() FUNC(add) // => __some_function_name_prefix__name() FUNC(subtract) // => __some_function_name_prefix__name() FUNC(multiply) // => __some_function_name_prefix__name() FUNC(divide) // => __some_function_name_prefix__name() ``` But, he problem is that it will always expand to__some_function_name_prefix__name()and won't use the argument. How can I fix this?
``` #define FUNC(name) __some_function_name_prefix__##name() ```
I have 2 arrays:int element[3] = {0, 1, 2};int quantity[3] = {2, 3, 4};Now I want a result array that will have two zeros, three ones and four twos.int result[2+3+4] = {0, 0, 1, 1, 1, 2, 2, 2, 2};How do I do this using loop?
You need to count the number of elements in the result array and to declare either a variable length array with the calculated value or to allocate dynamically such an array. For example ``` int quantity[3] = {2, 3, 4}; size_t n = 0; for ( size_t i = 0; i < 3; i++ ) { n += quantity[i]; } int result[n]; // or // int *result = malloc( n * sizeof( int ) ); ``` And then in nested loops you need fill the resulted array. For example ``` for ( size_t i = 0, j = 0; i < 3; i++ ) { for ( size_t k = 0; k < quantity[i]; k++ ) { result[j++] = element[i]; } } ```
If I have a number (long), how can I split its digits into an array? Example:4003607001000014->[4, 0, 0, 3, 6, 0, 7, 0, 0, 1, 0, 0, 0, 0, 1, 4]. I tried using modulo (n % (10 * i)), whereistarts at1and its value increases by a multiple of10each iteration of a for loop. Then adding the result to the array from n to 0, but this way, any zeros are ignored.
Try dividing the number by 10 each iteration, this is more straightforward than modulo by increasing powers of 10: ``` unsigned char digits[BIG_ENOUGH]; unsigned long number; unsigned i = 0; while (number) { digits[i++] = number%10; number /= 10; } ``` If you needdigits[0]to store the most significant digit instead of the least significant digit, reverse the array afterwards: ``` for (unsigned low = 0, high = digits-1; low < high; low++, high--) { unsigned char tmp = digits[low]; digits[low] = digits[high]; digits[high] = tmp; } ```
Considervalbeing a user input. I expectvalto be between 0-65535 Instead of checking ifvalis not withing acceptable range before denying it, I was wondering if is this : ``` uint16_t count = atoi(val); ``` the same as this : ``` uint16_t count = (uint16_t)atoi(val); ``` Is this an acceptable way of "securing" the user input? I do not intend to send a feedback to the user, I just want to make sure it won't explode if someone submits -123 or 999999. It does not matter ifcountequals2because someone submitted65538
Is this:uint16_t count = atoi(val);The same as this:uint16_t count = (uint16_t)atoi(val); They behave exactly the same. For the former, by assigning anintto auint16_t, it is being implicitly converted anyway. Since auint16_tcannot contain any more than65536or less than0, the conversion safely stores themodulusof theintvalue in theuint16_tvariable.
This is my program. I found that if I input n>480, the program wouldn't output any solution. How do I express it and print "No Output" in this program? ``` #include <stdio.h> main() { int x,y,z,n; scanf("%d",&n); for(x=0;x<=n;x++) for(y=0;y<=n;y++) for(z=0;z<=n;z++) if(5*x+2*y+0.1*z==120&&x+y+z==n) printf("%d,%d,%d\n",x,y,z); } ```
Try counting the true-branch passes in the loops, as pointed out by Alex P: ``` #include <stdio.h> int main() { int n; int results = 0; scanf("%d",&n); for(int x=0;x<=n;x++) { for(int y=0;y<=n;y++) { for(int z=0;z<=n;z++) { if(5*x+2*y+0.1*z==120 && x+y+z==n) { printf("%d,%d,%d\n", x,y,z); results++; } } } } if (results == 0) { printf("No results\n"); } } ```
How to change initial iterator value of my loop to debug in VScode? Example: I want debug my code starting i=10. How do I do to select this argument to my debugging? I'm loosing so many time clicking in "Step Over" to investigate my code. I'm using language C
You can do so by either taking theuser input-->i(that's inefficient) or else you can changeiwhile debugging in vs code Here is a image for reference But incase you only want to check wheni is k(some constant)without skippingthe iterations below it(wheni<k), you can useif(i>=k){code}
This question already has answers here:Why dividing two integers doesn't get a float? [duplicate](7 answers)Closed11 months ago. Code: ``` int main(){ double x = 10; double Fahrenheit = (x * (9/5)) + 32; double Celsius = (5 / 9) * (x - 32); printf("%lf\n", Fahrenheit); printf("%lf\n", Celsius); return 0; } ``` output: ``` 42.000000 -0.000000 ``` I have tried re-arranging the formulas, I have also tried using functions but I can't seem to figure out why the ouput is incorrect. For reference the expected output: ``` 50.00000 -12.22222 ``` re-arranging to: ``` double Fahrenheit = (x * 9 / 5) + 32; double Celsius = (x - 32) * 5 / 9; ``` worked! but so did adding a .0 to all int numbers
The problem is that you are performing the computation as ints (9/5) == 1 when (9.0 / 5.0) == 1.8. Add .0 to all your numbers and you'll be fine
This is part of a code to count white spaces, numbers, or other from the K&R "C programming book." I am confused why it compares "int c" to digits using '0' and '9' instead of 0 and 9. I realize the code doesn't work if I use 0 and 9 without quotes. I am just trying to understand why. Does this have to do with c being equal to getchar()? ``` while ((c = getchar()) != EOF) if (c >= '0' && c <= '9') ++ndigit[c-'0']; else if (c == ' ' || c == '\n' || c == '\t') ++nwhite; else ++nother; ```
looking at the man page forgetchar, we see that it returns the character read as an unsigned char cast to an int. So we can assume the value stored is not an integer number, but its ascii equivalent, and can be compared with chars such as '0' and '9'.
I am slowly learning libxml2 API (version is 2.9.10) and I think I missing something obvious after a call toxmlNodeGetContent. I am getting the base64 data stored in the XML file using: ``` xmlChar *base64_data = xmlNodeGetContent(cur); ``` What API from libxml2 should I use to decode the base64 back to the original binary ? Grepping the source code, all I can find isxmlBase64Decodewhich does not seems to be exported.
libxml2 offers no API to decode base64. You have to do it manually or use another library.
``` void f(); int main(int argc, char** argv) { if (f) { // other code } } ``` With VS2017, the linker complaint about unsolved external symbol, while it works with GCC. According to C99 spec, is it valid? Or it's implementation detail?
C standard requires that every symbol should bedefinedexactly once in a correct program, but does not require any diagnostic if the rule is not observed. So if you declare a function that is never defined in any compilation unit any use of that function is beyond C specification. The gcc compiler is known to have plenty of extensions, some of which are also accepted by clang. If you know that you will only use gcc, you can use them, if you want to write portable programs you should not.
I am building a calculator app using c language and gtk4, inactivatefunction I have ``` GtkWidget * entry; GObject * Sum = gtk_builder_get_object(builder, "sum"); entry = gtk_entry_new (); gtk_entry_set_max_length (GTK_ENTRY (entry), 200); g_signal_connect(Sum, "clicked", G_CALLBACK(sum), (gpointer) entry); ``` and the callback function ``` static void sum(GtkWindow * window, gpointer user_data) { const gchar *entry_text; //entry_text = gtk_entry_get_text (GTK_ENTRY (user_data)); entry_text = gtk_entry_get_tabs(GTK_ENTRY(user_data)); g_print("%s\n", entry_text); } ``` this does not seem to work because when ever i press the sum key I get(null)printed to the console How does one read data from aTextViewand pass it to a callback function
GtkEntryimplementsGtkEditableinterface. So you can dogtk_editable_get_text (GTK_EDITABLE (entry))to get the text in aGtkEntry.
I have write in a unsigned char *, two int and send it via a socket in C. How can i retrieve those values from the receiver side. Code: ``` unsigned char * request = malloc (8 * sizeof(unsigned char)); int index = htonl(rand() % 1000); int size = htonl(key_size); memcpy(request, &ind,4); memcpy(request+4, &size,4); ```
You just reverse all those operations. Read from the socket intobuffer, then use: ``` int index, size; memcpy(&index, buffer, 4); memcpy(&size, buffer+4, 4); index = ntohl(index); size = ntohl(size); ``` Note that all your code assumes thatsizeof int == 4. It would be better to useint32_tto ensure that the variables are the expected size.
I am usingdsyevwithIntel MKLin C. I am diagonalizing a20_000 x 20_000real symmetric matrix ofdoubles. I want to know how much time is left from the dsyev call, or roughly where it is. I compile the source .c code using the Intel Link Line advisor. Is there a way to do this? Thank you!
No, LAPACK methods are not designed to do that. You can create a performance model on the target machine and analyse the complexity of the function to predict the computational time taken by the function (approximate time). Alternatively you can reimplement the function using BLAS building block (not very simple).
``` int number; int *ptr; ptr = &number; printf("ptr: %d", *ptr); printf("number: %p", &number); ``` After assigning the address of the variable to the pointer, I want the variable to output its address and the pointer to output the address of the variable. EDIT: ``` int number; int *ptr; ptr = &number; printf("ptr: %p", *ptr); printf("number: %p", &number); ``` I tried this code and its gave me same adresses.
The code below should do what you're looking for. using %p in printf will print the address that the pointer is pointing to. ``` int main() { int number; int *ptr; ptr = &number; printf("ptr: %p\n", ptr); printf("number: %p", &number); } ```
I'm trying to create a program that display the value of days in a week. Monday is 1, Tuesday is 2, Wednesday is 3, ... Sunday is 7. If the user input is 3 then the output will be 1 2 3. If the user input is 10, then the output will be 1 2 3 4 5 6 7 1 2 3. ``` #include <stdio.h> int main() { int n; scanf("%d", &n); for( int i = 1; i <= n; i++) { if(i > 7) { continue; } printf("%d ", i); } return 0; } ``` If I input 10, this code will only output 1 2 3 4 5 6 7.
Just write ``` for( int i = 0; i < n; i++ ) { printf( "%d ", i % 7 + 1 ); } putchar( '\n' ); ``` Or it is better to introduce a named constant for the magic number 7 as for example ``` enum { DAYS_IN_WEEK = 7 }; for( int i = 0; i < n; i++) { printf("%d ", i % DAYS_IN_WEEK + 1 ); } putchar( '\n' ); ```
I was looking for a tutorial for ESP32. I discovered a few tutorials, each of which uses a different IDE, such as the Arduino IDE or IDF . So they're both using c. But do these two ides have the same syntax? Is it possible to use the same code on an Arduino Ide? If I take a tutorial for IDF Ide, whatever I learn can I apply to an Arduino Ide?
Syntax doesn't depend on the IDE, there's standard C, and there's extensions, which depend on the compiler being used. An IDE may support more than one compiler. In general it doesn't matter at all unless you're using extensions, which should be restricted to platform-specific abstractions and other low-level stuff, not to be seen in application code.
I was looking for a tutorial for ESP32. I discovered a few tutorials, each of which uses a different IDE, such as the Arduino IDE or IDF . So they're both using c. But do these two ides have the same syntax? Is it possible to use the same code on an Arduino Ide? If I take a tutorial for IDF Ide, whatever I learn can I apply to an Arduino Ide?
Syntax doesn't depend on the IDE, there's standard C, and there's extensions, which depend on the compiler being used. An IDE may support more than one compiler. In general it doesn't matter at all unless you're using extensions, which should be restricted to platform-specific abstractions and other low-level stuff, not to be seen in application code.
So I am trying to round DOWN to 2 decimal places in C - EDIT: I actually need to change the value, not just display it to 2 decimals. For example: ``` double x = 0.1234; x = 0.12; double y = 3.14159; y = 3.14; ``` Is the an integrated function in <math.h> similar to floor(), or is there another way to do this?
Well I need to value to change so I used x = (double)((int)(x*100))/100; This works, but you are limited to a relatively low range, i.e: 123456789 * 100 overflows. Check ifmodfhelps: ``` #include <stdio.h> #include <math.h> double dec2(double number) { double fractpart, intpart; fractpart = modf(number, &intpart); return intpart + round(fractpart * 100) * 0.01; } int main(void) { printf("%f\n", dec2(0.1234)); printf("%f\n", dec2(3.14159)); return 0; } ``` Output: ``` 0.120000 3.140000 ```
I am trying to decode the reference code to access the registers in MAX35101 IC. The code has this syntax at various lines. What does this mean? ``` bool MAX35101_Update_TOF_AVG_DIFFData(Flow_ResultsStruct* TOF_DIFF_Results) { bool success = false; success |= MAX35101_Read_2WordValue(TOF_DIFF_AVG_REG, &TOF_DIFF_Results->TOF_DiffData); return success; } ``` Simply what doesZ |= X(a, &b->c);mean?
Z |= X(a, &b->c);could be rewritten asZ = Z | X(a, &(b->c)); We have a pointer to a structFlow_ResultsStruct* b. To access a member of a struct via a pointer we use a->. So it is get the address of membercof structbfor which we have a pointer. Passaand the address to X. Now logical or (|) the return value withZwhich is false (0) soZequals the return of the function.
This question already has an answer here:Why can I not modify a string literal in c?(1 answer)Closed11 months ago. for example: ``` char stringer[]="hello"; stringer[2]='A'; ``` The above works to change'l'to'A'. But if I do the following: ``` char *stringer="hello"; stringer[2]='A'; ``` This doesn't work, is there a reason for this?
As answered by Some programmer dude in comments: Literal strings are really non-modifiable arrays of characters. Withchar *stringer="hello";you makestringerpoint to the first character of such an array. Attempting to modify its contents leads to undefined behavior. That's why you should always useconst char *when pointing to literal strings. Strings can be modified when using pointer, if the pointer is pointing to something you're allowed to modify. For example ``` char stringer[] = "hello"; char *pointer = stringer; pointer[2] = 'A'; ```
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed11 months ago.Improve this question I want to generate 10,000 pairs of numbers between 0 and 9. Like 00, 01, 02, 03... 99. I tried with the following function but it did not produce the desired results. ``` for(int i=0; i<1000; i++) { rand_num = (int)(100.0*rand()/(RAND_MAX+ 1.0)); printf (" %d ", rand_num); } ``` Can anyone help me to solve this?
If you want zero prefix just tellprintfto do that ``` for(int i=0; i<1000; i++) { rand_num = (int)(100.0*rand()/(RAND_MAX+ 1.0)); printf (" %02d ", rand_num); } ``` Demo Read the documentation on the format specifier
I have a function that looks kind of like this: ``` Exception* make_exception(Exception* caused_by, size_t caused_at, const char* format, ...) __attribute_format_arg__(3); ``` TheExceptiontype is just a struct containing the result of the function. I get the following error: ``` error: function does not return string type ``` Is there any way to fix this?
You want to use: ``` #ifdef __GNUC__ __attribute__((__format__(__printf__, 3, 4))) #endif Exception* make_exception(Exception* caused_by, size_t caused_at, const char* format, ...); ``` Seehttps://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes.
I read an article in which different compilers were compared to infer which is the best in different circumstances. It gave me a thought. Even though I tried to google, I didn't manage to find a clear and lucid answer: will the program run faster or slower if I use different compilers to compile it? Suppose, it's some uncommon complicated algorithm that is used along with templating.
Yes. The compiler is what writes a program that implements the behavior you've described with your C or C++ code. Different compilers (or even the same compiler, given different options) can come up with vastly different programs that implement the same behavior. Remember, your CPU does not execute C or C++ code. It only executes machine code. There is no defined standard for how the former gets transformed into the latter.
In my code I have two char pointer, one to a string and the other as an error indicator forstrtoumax()andstrtod(). I am currently using the typesize_t(aka unsigned long) to calculate the difference between them. Is there any type designed to specifically match pointer type size on every machine? Or do I have to check it myself with macros?
For pointer difference useptrdiff_t. If you're just trying to store a pointer as an integer, useuintptr_t(orintptr_t).
I found the code below in a project and I'm having problems understanding why GCC doesn't complaint sincedlcis called before it has been defined. ``` #define CAN_SET_DLC(dlc) (CANCDMOB |= (dlc)) typedef struct { uint8_t mob_n; uint8_t handle; long id; long id_msk; uint8_t dlc; uint8_t data_pt[8]; uint8_t status; } can_msg; ``` ¿The variable type of dlc should also be defined?: ``` define CAN_SET_DLC(uint8_t dlc) (CANCDMOB |= (dlc)) ```
The preprocessor has no knowledge of variables or any language construct. It is just a token processor. In#define a(b) ( b + 1 )this means that anytime the preprocessor encountersa(foo)in the source text, it will replace it with( foo + 1 ). Then the compiler will check whether it is correct C.