question
stringlengths
25
894
answer
stringlengths
4
863
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.Closedlast year.Improve this question I would like to know: what would be the worst case time complexity of inserting n number of nodes into an empty height balanced binary search tree using recursion? I know that the worst case time complexity of inserting one node into a balanced BST is O(logn). but I am confused as to whether its the same case when I insert node into an empty balanced BST.
Insert into an empty tree would would initialize a root pointer and a data node. This would be constant time operation.
I just want to know the difference between these C code segments. I used it in two different ways and final output was not same. ``` if(120<=units<160){ total= total- total*(15.0/100); printf("Revenue : %.2f", total); } if(120<=units && units<160){ total= total- total*(15.0/100); printf("Revenue : %.2f", total); } ``` Can't we use "120<=units<160" to specify a range in C language?
No, you can't test ranges in this way. What's happening here is the operators are evaluated left-to-right as peroperator precedence. So this means:(120 <= units) < 160 The value of120 <= unitswill be 0 if it is false or1 if it is true In other words, the full expression will always be true, because both 0 and 1 are less than 160.
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.Closedlast year.Improve this question I want to create a C or C++ program that automates some things for me. The idea is as such: I run the program./a.outand sit back and watch as it opens up three or four new terminal windows and runs various UNIX commands. Is there a way to do this? I am on a MacBook.
As the comments point out, this is probably best accomplished by a shell script. However, you can execute shell commands from C with thesystem(3)standard library function. To open a terminal, just run a terminal with a particular command. For example: ``` system("xterm -e 'echo hello; sleep 5'"); ```
I want my for loop to break if -1 is entered but that doesn't seem to work in this case. I've tried it a few different ways but nothing seems to make it actually break. ``` struct employee{ char name[30]; float rate; float hrsWorked; }; int main() { struct employee staff[5]; int placeholder; for(int i = 0; i < 5; i++){ printf("Enter name: "); scanf("%d", &placeholder); fgets(staff[i].name, sizeof(staff[i].name), stdin); if (staff[i].name[0] == -1){ break; } } } ```
You are storing a string of characters inname, so-and1are two different characters. This should work: ``` if (staff[i].name[0] == '-' && staff[i].name[1] == '1') break; ```
I am writing a UTF-16 decode routine. To check if it works correctly, I need to produce test strings with intentional encoding errors in them. However, when I try to produce such strings in C the obvious way, the compiler rejects my code with “... is not a valid universal character:” ``` u"\ud800" /* unmatched low surrogate */ u"\udc01\ud802" /* surrogates in wrong order */ ``` How can I produceu"..."strings with intentional encoding errors?
The\uXXXXand\UXXXXXXXXescape sequences can only encode valid universal characters. To encode otherchar16_tvalues, use a\x...escape sequence: ``` u"\xd800" /* unmatched low surrogate */ u"\xdc01\xd802" /* surrogates in wrong order */ ```
This fails with the error "Cannot find source file: WIN32. Tried extensions..." ``` add_executable(${PROJECT_NAME} $<$<CONFIG:Release>:WIN32> main.cpp) ``` I need this in order to launch the app in the console in Debug mode and being able to read information printed to the console. And as far as I know it's wrong and is advised agains in the cmake docs to checkCMAKE_BUILD_TYPEbeingReleasedirectly.
As you noticed you cannot use generator expressions for the WIN32 keyword in theadd_executablecommand. Instead, try setting the corresponding propertyWIN32_EXECUTABLEon the target: ``` set_target_properties(${PROJECT_NAME} PROPERTIES WIN32_EXECUTABLE $<CONFIG:Release>) ```
I couldnt find the answer to this question before reading:getenforce source code. I just wanted to get the mode of selinux so I would know in runtime if selinux is enforcing and spamming avc denials because gdb is reading:gdb avc denial bug. I have no intention of fixing it so the solution I thought of was to warn the user if selinux is on enforcing mode. I was checking if selinux is enabled withis_sleinux_enabled()fromselinux.h. But the problem is selinux could also be inPermissivemode which isnt an issue for denials since it only warns the user rather than killing the process.
To see the mode selinux is currently using: ``` #include <selinux/selinux.h> if (is_selinux_enabled()) return security_getenforce(); ``` link with -lselinux
In openSSL I used functionSSL_CTX_set_verifywithverify_mode= SSL_VERIFY_PEERandverify_callback= NULL. What does it mean? The client will verify the server certificates chain or not?
Reworded answer bySteffen Ullrich: The optional callback can be used to possibly override the built-in validation.
The following code should print the number of seconds passing from 0-10 and works as intended on windows vscode, however on mac's vscode the output takes 10 seconds as it should but only outputs 10 second has passed However, if I change the \r to \n , the code works but i don't want to print a new line every time. 0 second has passed1 second has passsedetc... I've been searching for some time about this and i don't know what seems to be the issue... The Code : ``` for(int i = 0;i<=10;i++) { printf("\r %d second has passed",i); sleep(1); } ```
You are suffering from buffering. By disabling buffering on stdout, the text will be output immediately on callingprintf. Here is the code: ``` #include<stdio.h> #include<unistd.h> int main() { setbuf(stdout, NULL); for(int i = 0;i<=10;i++) { printf("\r %d second has passed",i); sleep(1); } return 0; } ```
I would like to initialize a struct with all fields as zero and immediately assign it to a pointer. The struct will only need to be used within static functions whose lifetime is completely contained within the calling function. This is the line I currently have ``` move_stats *mv_s = (move_stats *){0}; ``` The struct is defined in a header file as ``` typedef struct { byte open_threes; byte open_fours; byte half_open_fours; bool overline; bool five; } move_stats; ``` byteis an alias for unsigned char. Will this create the struct in the way I want it to as written? I could not find a question exactly like this, apologies if it is a duplicate.
Your compound ;literal defines a null pointer instead of an object of the structure type ``` move_stats *mv_s = (move_stats *){0}; ``` Instead write ``` move_stats *mv_s = &(move_stats){0}; ```
I'm currently learning windows.h lib. According to docs, it is possible to know the minimum and maximum program addresses by means oflpMinimumApplicationAddressandlpMaximumApplicationAddressfields ofSYSTEM_INFOstructure,GetSystemInfo()function. However, I'm wondering: is it possible to get program start and end address, usingGetSystemInfo()? If possible, how? Thank you for advance.
If you mean the actual address that program terminates on (or whether it terminates at all), no. That is just a variation on the famous halting problem. And that has been proven to not have a general solution. Minimum and maximum address are just what memory has been assigned to a process, but there could be many places in it that the program would terminate at, depending on the exact run parameters. And it might not even reach any of them.
I looking at this codehttps://elixir.bootlin.com/linux/v4.6.7/source/Documentation/networking/timestamping/timestamping.c#L181 This code try to print the timestamp of packet usingstruct timespec *stamp = (struct timespec *)CMSG_DATA(cmsg); If this is UDP packet. Is there any way thatCMSG_DATA(cmsg)will return NULL?
If you look at the definition ofCMSG_DATAyou see ``` #define CMSG_DATA(cmsg) ((void *)((char *)(cmsg) + CMSG_ALIGN(sizeof(struct cmsghdr)))) ``` This adds an offset tocmsg. Unless you manage to feed acmsginto that macro that evaluates toNULLafter adding that offset, the result can never be comeNULL.
I have a question about using pointer. ``` char *CustomString; char str[5] = {'V', 'i', 'c', 't', '\0'}; CustomString = (char*) malloc(1); strcpy(CustomString, str); printf("%s\n", CustomString); ``` Why is it not giving "segmentation fault"? The result is an output: ``` Vict ```
When you write past the bounds of allocated memory, you triggerundefined behavior. That means the compiler makes no guarantees regarding what the program will do. It may crash, it may output strange results, or it may appear to work properly. Just because the program could crash doesn't mean it will.
I'm working on a 3D Engine for C, and I have (what I believe) to be everything. Except keyboard input, I could use the scanf() function but I imagine that has its problems (like multi-key inputs). I dont want to use a library like SDL2, I just want a header file for inputs or more preferably just getting code to scan for keys and add it to an array or something. Please do not suggest something better or a library that would do everything for me, I want to build this from scratch. Thank you.
You will probably want to process the following two window messages in yourmessage loop: WM_KEYDOWNWM_KEYUP See theMicrosoft documentation on Keyboard Inputfor further information.
Are these 2 lines of code the same ?? line 1: ``` void (**foo)(int) ``` line 2 ``` void *(*foo)(int) ``` Kindly help me understand on what is happening.
They are not the same. ``` void (**foo)(int); ``` foois a pointer to a pointer to a function that takes anintparameter and returnsvoid. ``` void *(*foo)(int): ``` foois a pointer to a function that takes anintparameter and returns a pointer tovoid. Postfix operators like()and[]have higher precedence than unary*, so ``` T *a[N]; // a is an array of pointer to T T (*a)[N]; // a is a pointer to an array of T T *f(); // f is a function returning pointer to T T (*f)(); // f is a pointer to a function returning T ```
What is the macro thatclangand/orgccwould define when compiling for a WASM backend? To clarify, one can write platform-specific code using macros the compiler defines like so: ``` #if _WIN32 // Windows-specific code #elif __linux__ // Linux-specific code #elif __APPLE__ // macOS-specific code #else #error Unsupported platform #endif ``` I would like to do the same thing specifying WebAssembly as one of the potential backends.
As per @Jonathan Leffler's comment, there does not appear to be a standard macro that is defined across compilers. My current solution for working with different compilers is to create a separate build job for WASM that defines a macro. Forgccandclang, it passes the flag-D__WASM__to define a__WASM__macro. In my setup, I just change an environment variable and my build script selects the appropriate build flags.
I want to check if the LSB is 0. if(some_size_t & 1){}works fine But why isif(some_size_t & 0){//This parts is unreachable}never reachable?
Because in order to ever get the value1i.e.trueboth operands for the logical and bitwise & i.e. AND operator have to be1. Its so called truth table is ``` op1 | op2 | op1 AND op2 ===================== 0 | 0 | 0 1 | 0 | 0 0 | 1 | 0 1 | 1 | 1 ``` Because your value, e.g. op2,0has only zeros, no ones, you will always get only zeros as a result, no matter the other operand. And0will evaluate to false. It's what we call a contradiction in logic, often noted with a up side down T or\botin latex. As then theifcondition is alwaysfalse, the code in its body will never be executed, i.e. isunreachable.
I come to crossrand()inCand foundsrand()could only guarantee the reproducibility of the same machine but not the different platform. As I already used mysrand(926)and completed a quite time-consuming simulation, I like to find the definition ofrand(). So that, I can get the same result on the different platforms as well. Could someone point me in a direction to find the definition ofsrand()inGCC 9.3.0? Thanks
gcc is a compiler and as such won't itself have an implementation.srandis part of the C standard library (libc), the implementation of which is probably glibc on your system. The following will use the tip of the master branch for glibc at the time of writing. The version used on your system may be different. srandis declaredhereas a weak symbol. Unless overridden, it'll invoke__srandom_rhere, which is definedhere. Both random.c and random_r.c appear to have ample documentation for how things work.
In the ZLIB Manual it is stated thatZ_PARTIAL_FLUSHalways flush an extra10 bits.So that we correct for that usingdeflatePrimewhen we want to append later. But why then isgzlog.ccontaining logic to find dynamically the bit countif *buf. According to the specs this is not needed and only theelseis needed to set it to 10? ``` if (*buf) { log->back = 1; while ((*buf & ((uint)1 << (8 - log->back++))) == 0) ; /* guaranteed to terminate, since *buf != 0 */ } else log->back = 10; ```
Because most of the time not all of the ten bits are written. Only in the case where the last byte is a zero are all ten bits written, because by chance (a one-in-eight chance) there were six bits pending to be written before the ten-bit empty static block.
``` #include<stdio.h> int main() { int i = 577; printf("%c",i); return 0; } ``` After compiling, its giving output "A". Can anyone explain how i'm getting this?
%cwill only accept values up to 255 included, then it will start from 0 again ! 577 % 256 = 65; // (char code for 'A')
I've already readthis,thisandthisbut it seems they're not exactly my situtation. I have a code like this ``` struct ppl_weight { uint16_t weight; uint8_t weightHour; } ppl_weightList[16]; ``` but I can't understand the array at the end of thestruct. What does it mean? Have I an array of 16struct? How does I manage this data type?
It is a declaration of an array with 16 elements of the typestruct ppl_weight. You could split this declaration ``` struct ppl_weight { uint16_t weight; uint8_t weightHour; } ppl_weightList[16]; ``` the following way ``` struct ppl_weight { uint16_t weight; uint8_t weightHour; }; struct ppl_weight ppl_weightList[16]; ```
So i have a problem where the string in struct merge with another array. See the code and output for more explanation. Code: ``` #include <stdio.h> #include <stdlib.h> struct print { char code[3]; char name[10]; }test[2]={"001","Alen","101","Paul"}; int main() { int x; for(x=0;x<2;x++) { printf("%s %s\n",test[x].code,test[x].name); } return 0; } ``` Output: ``` 001Alen Alen 101Paul Paul Process returned 0 (0x0) execution time : 0.017 s Press any key to continue. ``` The output is wrong, it should be like this: ``` 001 Alen 101 Paul ``` So why the "name" merge in "code" variables? It shouldn't be like that. So how do i solve this? Thank you.
C strings need to be NUL terminated. Yourcodearray field is one character too small. Changechar code[3];to bechar code[4];
If I have arraya, how would I set a pointer to the first row? ``` double a[2][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}}; ```
You can declare a pointer to a row and initialize it to point to the first row with the following line: ``` double (*p_first_row)[4] = &a[0]; ``` Due toarray to pointer decay, you can also write: ``` double (*p_first_row)[4] = a; ``` The parentheses are necessary, because the declaration ``` double *p[4]; ``` declares an array of pointers, whereas the declaration ``` double (*p)[4]; ``` declares a pointer to an array.
I was reading a C code, and I didn't understand well a line : ``` str = realloc(NULL, sizeof(*str)*size);//size is start size if(!str)return str; ``` what does the!strmean ? The code read an input string from a user then realloc dynamically the memory.
A pointer in C is "falsy" if it is a null pointer, and "truthy" otherwise. Soif (!str) return str;means that ifstris NULL (meaning that the allocation failed) the function returnsstr(i.e. NULL). It could also be written asif (str == NULL) return str;.
This question already has answers here:Can the precision of a floating point number be dynamically changed in C?(2 answers)Closedlast year. I want to set custom precision using printf() like for example: ``` double pi = 3.14159265358979323846; cin>>n; cout<<setprecision(n)<<pi; ``` I want to implement this same functionality using printf()
Fromprintf: (optional).followed by integer number or*, or neither that specifies precision of the conversion. In the case when*is used, the precision is specified by an additional argument of typeint, which appears before the argument to be converted, but after the argument supplying minimum field width if one is supplied. So: ``` int n = ...; printf("%.*f\n", n, pi); ```
What should a script that compiles and executes a C program look like? By condition, the script must be run with the following flags: gcc -Wall -Werror -Wextra -o In my understanding, when running the script, I have to enter the name of the program file ``` % gcc -Wall -Werror -Wextra "file_name".c -o "file_name" % ./"file_name" ```
The script can take the name of the program as an argument, which you access using$1. Then substitute that for the file name in the commands. ``` #!/bin/sh prog="$1" if gcc -Wall -Werror -Wextra "$prog".c -o "$prog" then "./$prog" else echo "$prog.c did not compile successfully" fi ```
This question already has answers here:Can the precision of a floating point number be dynamically changed in C?(2 answers)Closedlast year. I want to set custom precision using printf() like for example: ``` double pi = 3.14159265358979323846; cin>>n; cout<<setprecision(n)<<pi; ``` I want to implement this same functionality using printf()
Fromprintf: (optional).followed by integer number or*, or neither that specifies precision of the conversion. In the case when*is used, the precision is specified by an additional argument of typeint, which appears before the argument to be converted, but after the argument supplying minimum field width if one is supplied. So: ``` int n = ...; printf("%.*f\n", n, pi); ```
What should a script that compiles and executes a C program look like? By condition, the script must be run with the following flags: gcc -Wall -Werror -Wextra -o In my understanding, when running the script, I have to enter the name of the program file ``` % gcc -Wall -Werror -Wextra "file_name".c -o "file_name" % ./"file_name" ```
The script can take the name of the program as an argument, which you access using$1. Then substitute that for the file name in the commands. ``` #!/bin/sh prog="$1" if gcc -Wall -Werror -Wextra "$prog".c -o "$prog" then "./$prog" else echo "$prog.c did not compile successfully" fi ```
clang -O3optimizes this code: ``` _Bool f1(char x) { _Bool b1 = x == 4; _Bool b2 = x & 3; return b1 & b2; } ``` to: ``` f1: xor eax, eax ret ``` However,clang -O3does not optimize this code: ``` _Bool f1(char x) { _Bool b1 = x == 2; _Bool b2 = x & 1; return b1 & b2; } ``` ``` f1: cmp dil, 2 sete al and al, dil ret ``` Why? Note: the&b1 & b2is used intentionally. If&&is used, thenclang -O3optimizes it to: ``` f1: xor eax, eax ret ``` How it can be explained?
Why? Inefficient code generation(due to "missing narrowing transforms for bitwise logic").
Having such a simple C code ``` #include <stdio.h> #include <setjmp.h> void Com_Error(int); jmp_buf abortframe; int main() { if (setjmp (abortframe)){ printf("abortframe!\n"); return 0; } Com_Error(0); printf("main end\n"); return 0; } void Com_Error(int code) { // ... longjmp (abortframe, code); //... } ``` I'm getting: abortframe! My question is WHY does it prints theabortframe!if we pass0(NOTtrue) and hence the conditionif (setjmp (abortframe)){...}should NOT be meet so noabortframe!string printed?
Read the friendly manual (C17 7.13.2.1): The longjmp function cannot cause the setjmp macro to return the value 0; if val is 0, the setjmp macro returns the value 1.
So I recently decided to make the switch to using c89 only for my code from now on. I use cmake and i'm not sure how to tell cmake to use c89. Per a information on a website it says "(accepted values are 98, 99 and 11)", which is really strange because 89 isn't there. ``` set (CMAKE_C_STANDARD 89) ``` This code gives me an error. Whats really strange is that Ive searched everywhere on the web and couldn't find anyone asking about this. Does anyone know how to use/(restrict) to using only c89 in cmake. the cmake document says to use ``` Supported values are: 90 C89/C90 ``` This code works ``` set (CMAKE_C_STANDARD 90) ``` However I want the compiler to use just C89 not C90.
Useset(CMAKE_C_STANDARD 90)to use C89. C89 is the same as C90, also called ANSI C. Note: prefer to useset_target_properties(your_target C_STANDARD 90)explicitly on your target, so it doesn't affect other targets.
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.Closedlast year.Improve this question I would like to know why the loop below just execute one time? Here is my code. ``` for(i=0;i<MAX;i++) { printf("name:"); gets(student[i].name); printf("math score:"); scanf(" %d",student[i].math); fflush(stdin); } ```
At least the code contains a typo. You have to write ``` scanf(" %d", &student[i].math); ^^^ ``` Also this call ``` fflush(stdin); ``` has undefined behavior. And the functiongetsis unsafe and is not supported by the C Standard. Instead use functionfgetsorscanf.
I understand that passing a null pointer will trigger an undefined behavior, but if I usecalloc()to initialize a char array and print it, for example: ``` char * a = calloc(10, sizeof(char)); printf("%s\n", a); ``` calloc()should initialized the char array to 0. Since in ASCII table 0 refers to NULL, I expected undefined behavior. However, every time I run it, it will actually print nothing. Is this output fixed? Can I reason about the output?
In C a string is generally understood to terminate at the first 0 byte encountered. Since the first byte in the result ofcallochas value 0, it is interpreted as immediately ending the string, leaving you with the empty string.
Im trying to make a widgets application inCwithSDL2and I've been wondering if there is anyway of making an SDL2 window not show up on the menu/window bar? To hide something like this Thanks!
Take a look toSDL_WindowFlags,SDL_WINDOW_SKIP_TASKBARis what you are looking for. ``` Uint32 flags = SDL_WINDOW_SKIP_TASKBAR; SDL_Window * window = SDL_CreateWindow( /* ... */ flags ); ```
I wrote a program to print hello world at first. ``` #include <stdio.h> int main() { printf("age is age"); return 0; } ``` and when I open in a terminal it keeps showing hello world as I wrote it previously.
Thewhite dotafter the file name indicates you haven't saved the changes in the file. In order to compile the changes, You have to save the file before compiling it otherwise it will recompile the last saved file. This will definitely work save the file. [ctrl + S]recompile the file.run the.exefile
I want to check why a program is not receiving UDP messages. A client program is sending 4 integers every time sample. I have a server program that is using "recvfrom()" to get the UDP messages on a port but the program does not seem to be receiving the messages on the port number and is stuck in the "recvfrom" function. I was wondering if there are debugging techniques I can use to debug this issue? Thanks!
There are many possibilities, common case could be, Firewall on your machine or in transit, for example, your another endpoint is behind a firewall that disallow UDP inbound traffic from this address.Routing, make sure the ping worksYour code bug, make sure loopback address works To debug, you could install Wireshark to inspect specific interface's traffic.
We can use inline assembly by using__asm__(). However, this approach can only support instructions that are recognized by the compiler. What I am using is gem5 hardware simulator, in which I implemented a new instruction in RISCV. Such instruction is a bit string of 1's and 0's. Hence, if such instruction is in the executable, then it will be fetched, decoded and executed by gem5 hardware simulator. However, since that is a new instruction, the compiler does not recognize it. For example, suppose the instruction that I implemented has mnemonicnewInst %a0, %a1. If I directly insert it using inline assembly by ``` __asm__("newInst %0, %1": /* etc... */); ``` The compiler would not be able to translate that into machine code. Hence, may I know if there is a way to hard code the instruction using inline assembly, without modifying the compiler?
You can put raw bytes in with.byte: ``` __asm__ (".byte 0xf0, 0x0b, 0xaa"); ```
i have a problem where the function somme_diagonale return the right result when called in main, but as soon as i multiply it to ( 2 / 9 ) and print the result it appears to be 0. function : ``` { int i, s = 0 ; for ( i = 0 ; i < n ; i++ ) { s = s + mat [ i ] [ i ] ; } return s ; }``` call : ``` printf("resultat est : %f", ( float ) ( 2 / 9 ) * somme_diagonale ( F ) );``` i have tested that somme_diagonale ( F ) returns 165 ( int ). can someone help me ? ```
Hi,in order to have afloatvalue, either the 2 or the 9 must be cast. This, though, must happenbeforethe division is performed.(2/9)produces a result of typeint, which onlythenis cast tofloat. What you should do is replace that piece of code with of these options (sorry in advance, I'm not a fan of spaces): (float)2 / 9 * somme_diagonale(F)2 / (float)9 * somme_diagonale(F)(float)2 / (float)9 * somme_diagonale(F)
I recently started using C in Visual Studio, and I've been having an issue where Visual Studio automatically lists the name of parameters in front of arguments to functions. It's possible I unintentionally pressed a key. Example: As you can see in the image, the_Format:is being displayed, which is quite annoying. I have browsed through the text editor settings, but I can't seem to find the issue. I mainly use VS for C#, and so far this only seems to happen with C. Any solution would be appreciated.
First step, go to options. Press Ctrl+Q then type "inline": Second step, uncheck inline hints: I use C#, but I think the settings are the same here.
what will happen if scanf accepts more characters than there is room for in the buffer? For example, ``` char foo[2], bar[5]="abcd"; sscanf(bar, "%s", foo); ```
That will be an undefined behavior as @Mad Physicist mentioned in the command but if you want to avoid I, you can use thewidthmodifier ofscanf()function to read the exact size from the buffer. Read by 1 less than the size of the buffer to leave space for the the null character. The example: ``` char buff[8], str[32]="asdfasdfasasdfasdfdfasdf"; sscanf(buff, "%7s", str); ```
what will happen if scanf accepts more characters than there is room for in the buffer? For example, ``` char foo[2], bar[5]="abcd"; sscanf(bar, "%s", foo); ```
That will be an undefined behavior as @Mad Physicist mentioned in the command but if you want to avoid I, you can use thewidthmodifier ofscanf()function to read the exact size from the buffer. Read by 1 less than the size of the buffer to leave space for the the null character. The example: ``` char buff[8], str[32]="asdfasdfasasdfasdfdfasdf"; sscanf(buff, "%7s", str); ```
I want to use this benchmark to evaluate my optimization in compiler. I can compileint computationof DSPStone on X86 architecture, but the other cannot. The error is the type of main function is float. I know it is not allowed in X86 architecture, so I want to know if there are other ways to compile it on X86. Thanks!!
You just create a float function and call it with your main function. Please read some C tutorials. I suggest this one:https://www.tutorialspoint.com/cprogramming/index.htm ``` float computation(float f); int main(int argc, char *argv[]) { float test = 3.14; test = computation(test); return 0; } float computation(float f) { f = f + f; return f; } ```
My code suddenly not working anymore today, what could be the issue? Here is the part of the code. ``` struct timespec tp; clock_gettime(CLOCK_MONOTONIC, &tp); int32_t tnow = tp.tv_sec * 1000 + tp.tv_nsec / 1000000; if (tnow - decoder->last_dumped >= 300) { decoder->last_dumped = tnow; // it was working before ... } ```
tv_sec is a signed integer holding seconds, so 1000 * tv_sec will overflow an int32_t. Use int64_t. Overflow will occur after (1 << 31) milliseconds, which is about 24.8 days.
I'm trying to setup a little JNI demo with Autotools using the Clion IDE. The problem is: I don't know how to tell Autotools to include jni.h. Also Clion does not resolve the #include <jni.h>. This is the bare minimun example I'd like you to tell me how to fixdemo.
The $JAVA_HOME must be set. The fixed configure.ac looks like this: ``` AC_INIT([helloworld], [0.1], [maintainer@example.com]) AX_JNI_INCLUDE_DIR for JNI_INCLUDE_DIR in $JNI_INCLUDE_DIRS do CFLAGS="$CFLAGS -I$JNI_INCLUDE_DIR" done AM_INIT_AUTOMAKE AC_PROG_CC AC_CONFIG_FILES([Makefile]) AC_OUTPUT ``` CLion will then include the jni.h correctly.
I feel really stupid but this is the first time dealing with C for a basic CS course. I try to do everything but it keeps giving me a unexpected token when trying to run the code. ``` #include <stdio.h> int main(void) { puts("Hello World!"); } ``` even using printf and \n at the end, same result, always unexpected token, what am I missing? I've coded some complex javascript stuff before but this made me feel like a noob TT
You should compile your code and then run the obtained executable. Installgccand run ``` gcc -Wall -Wextra -pedantic ./hello.c -o hello ``` This will produce a binary file named "hello". Then you can run ``` ./hello ``` and "Hello World!" will be printed to the screen.
I want to calculate greatest of given three integer numbers in C programming without using anyif/elsecondition orswitchcase. For example in this way. ``` #include <stdio.h> #include <stdlib.h> int main() { int num1, num2, max; scanf("%d %d", &num1, &num2); max = (num1 + num2 + abs(num1 - num2)) /2; printf("%d\n", max); return 0; } ``` Here is my code to calculate the max of given two integer numbers.
You can call the max function twice: ``` #include <stdio.h> #include <stdlib.h> int main() { int num1, num2, num3, max; scanf("%d %d %d", &num1, &num2, &num3); max = (num1 + num2 + abs(num1-num2))/2; max = (max + num3 + abs(max-num3))/2; printf("%d\n", max); return 0; } ```
``` int main(int argc, char **argv) { double s = 43; write(1, &s, sizeof(double)); } ``` This is the output : �E@ ``` int num = 1234; write(STDOUT_FILENO, &num, sizeof(num)); ``` I have the same issue too, output : �
writedoes not convert the value to text before writing it. What you are doing is writing the binary value of the double to a file. You should convert it to a string before, like so : ``` int main(int argc, char **argv) { double s = 43; char buff[26]; //Buffer to store the string snprintf(buff, sizeof(buff), "%f", s); //Convert the float to a string write(1, &s, strlen(buff)); } ``` Note the use ofsnprintf. It works like printf, but writes to an array instead.sprintfwould also work but can be unsafe as there are no limit to the number of characters written, which can cause segmentation faults.
The goal is for the function to say hi ("Hello User"), but it keeps telling me that my sayHi function is invalid. I'm not sure why. ``` #include <stdio.h> #include <stdlib.h> int main(){ sayHi(); return 0; } void sayHi () { printf ("Hello User"); } ```
You can either try this ``` #include <stdio.h> #include <stdlib.h> void sayHi(); int main() { sayHi(); return 0; } void sayHi() { printf ("Hello User"); } ``` or this ``` #include <stdio.h> #include <stdlib.h> void sayHi() { printf ("Hello User"); } int main() { sayHi(); return 0; } ```
I'm trying to make 2D array struct in C like this in main function. ``` function_1(struct example** ex){} void main(){ struct example ex[num_1][num_2]; function(ex); } ``` But gcc keep telling me that type of ex and struct example** ex is different. How can I solve this error?
I edited my original answer: You could instead write ``` function_1(struct example (*pex) [num_1][num_2]){} void main(){ struct example ex[num_1][num_2]; function(& ex); } ``` at least if you knownum_1andnum_2at compile time.
Compiler:MinGW-W64 GCC-8.1.0 (x86_64-posix-seh) Missing library:graphics.h It seems like this library was not installed by default. If such case is true, where can I get it? As a side note, I am not interested in installing a full IDE like Visual Studio just to use this one library.
After looking into this for 5 minutes, I think you will need to install eithersdl-bgiorWinBGIm. Since MSYS2 doesn't seem to have packages for these, you would need to compile those projects from source. This means you would need to figure out the correct set of configuration optiosn and possibly fix any build errors. If you do succeed in doing that, you might consider contributing your work as an MSYS2 package so others can benefit from it (https://github.com/Alexpux/MINGW-packages).
(In C socket programming, usingpollto manage the fd's and its events)With a data stream socket returned from anaccept()call, what's the difference between the event POLLHUP and getting 0 when calling recv(fd, ...) ? They both seem to indicate the connection was closed from the other end, but I wanted to know if there is any technical difference between the two.
POLLHUPin thereventsof astruct pollfdtells you if the other end of a pipe or socket has been closed. That means you can't write to the descriptor (If it's open for writing) without getting aSIGPIPE, but there might still be data pending waiting to be read (If it's open for reading). Once all remaining bytes have been read, then functions likerecv(2)andread(2)will return 0. BothPOLLINandPOLLHUPcan thus be set at the same time, but notPOLLOUTandPOLLHUP- those two are mutually exclusive.
This question already has answers here:How to divide 2 int in c?(5 answers)Closedlast year. ``` int arr5[8]={10,20,30,40,50,60,70,80}; len=8; int beg=0,mid,end=len-1,loc; mid=int((beg+end)/2); printf("%d",mid); ``` I was trying to write a code for binary search but can't typecast the value of (beg+end)/2 to mid. ``` error: expected expression before 'int' mid=int((beg+end)/2); ^~~ ```
For starters using the type specifierintin this statement ``` mid=int((beg+end)/2); ``` does not make a sense. It is enough to write ``` mid=(beg+end)/2; ``` As all operands in the expression in the right side of the assignment have the typeintthen the evaluated value also has the typeint. As for the casting then in C you have to write ``` mid= ( int )((beg+end)/2); ```
I often see programs where people putargcandargvinmain, but never make any use of these parameters. ``` int main(int argc, char *argv[]) { // never touches any of the parameters } ``` Should I do so too? What is the reason for that?
The arguments to themainfunction can be omitted if you do not need to use them. You can definemainthis way: ``` int main(void) { // never touches any of the parameters } ``` Or simply: ``` int main() { // never touches any of the parameters } ``` Regardingwhy some programmers do that, it could be to conform to local style guides, because they are used to it, or simply a side effect of their IDE's source template system.
I am having such trouble figuring out how this piece of code works - if(fork()||!fork()) I know the first fork creates a child for the initial process, and !fork() creates a child for the previous child. But for which process do we enter the if condition? If I was wrong earlier, please correct me!
The easiest way to understand this is to convert the||expression to separateifstatements that implement the short-circuiting. ``` if (fork()) { // This is the parent process /* body */ } else { // This is the child process if (!fork()) { // This is the grandchild process /* body */ } } ``` Where/* body *is whatever was in the body of the originalifstatement. Sincefork()returns non-zero in the parent process, the body is executed in the parent after creating the first child, and in the grandchild.
Is it possible to create a Rectangle and somehow turn it into a Texture in SDL2 C? You can easily load images to textures using the image library but making a simple rectangle seems a lot more complicated.
It is generally not meaningful to create a texture in which all pixels are the same color, as that would be a waste of video memory. If you want to render a single rectangle in a single color without an outline, it would be more efficient to do this directly using the functionSDL_RenderFillRect. If you really want to create a texture for a single rectangle in a single color without an outline, then you can create anSDL_SurfacewithSDL_CreateRGBSurface, then useSDL_FillRecton thatSDL_Surfaceto set the color, and then useSDL_CreateTextureFromSurfaceto create aSDL_Texturefrom thatSDL_Surface.
Whenever I run check50/submit50 on speller it says this: expected exit code 0, not 2 I also saw this happening with other people. Some people said that the cause of this was altering programs such as dictionary.h and speller.c, but this kept happening even after I reset all changes to the programs. Anyone have any suggestions? Error message: ``` :) dictionary.c exists :( speller compiles expected exit code 0, not 2 :| handles most basic words properly can't check until a frown turns upside down ``` Here's my dictionary.c code:https://pastebin.com/N1aMNqmX speller.c code:https://pastebin.com/AFV9eHVm
The program does not compile as C becausenode *table[N];cannot be defined as a global variable withNdefined asconst unsigned int N = 676;DefineNas#define N 676 The exit code of2might be produced because of a compilation error. Without this problem, the code compiles and runs fine.
Doestmp = malloc(sizeof(x));the same automatically astmp = malloc(sizeof(x)); *tmp = x;? More specifically, is malloc instantly initialising my variable or is it just allocating memory and I have to initialise it myself?
No. The memory returned by malloc isn't initialized. Quotingcppreference, Allocates size bytes of uninitialized storage.
I am new to C programming and I am getting a Segmentation Fault when passing a single character and trying to vailidate if it is a digit. Here is a sample: ``` #include <cs50.h> #include <stdio.h> #include <ctype.h> int main(int argc, string argv[]) { if (isdigit(argv[argc-1])) { printf("Use only one Argument%i\n", argc); return 1; } return 0; } ```
As Eugene said,argv[argc-1]is of typechar*as it was meant to hold a string. The segmentation fault is probably a result of lookup. Assuming you would like to test the first character of the last argument, this should be written like this: ``` if (isdigit(argv[argc-1][0])) { printf("Use only one Argument%i\n", argc); return 1; } ``` You can also use the '*' notation to defer to the first char, but I believe[0]will be slightly more readable in this case.
Doestmp = malloc(sizeof(x));the same automatically astmp = malloc(sizeof(x)); *tmp = x;? More specifically, is malloc instantly initialising my variable or is it just allocating memory and I have to initialise it myself?
No. The memory returned by malloc isn't initialized. Quotingcppreference, Allocates size bytes of uninitialized storage.
I am new to C programming and I am getting a Segmentation Fault when passing a single character and trying to vailidate if it is a digit. Here is a sample: ``` #include <cs50.h> #include <stdio.h> #include <ctype.h> int main(int argc, string argv[]) { if (isdigit(argv[argc-1])) { printf("Use only one Argument%i\n", argc); return 1; } return 0; } ```
As Eugene said,argv[argc-1]is of typechar*as it was meant to hold a string. The segmentation fault is probably a result of lookup. Assuming you would like to test the first character of the last argument, this should be written like this: ``` if (isdigit(argv[argc-1][0])) { printf("Use only one Argument%i\n", argc); return 1; } ``` You can also use the '*' notation to defer to the first char, but I believe[0]will be slightly more readable in this case.
I have an array of function pointersint (*oper_ptr[4])(int, int) = {add, sub, mul, divi};for the below functions which simply perform a standard operation on two passed integers: ``` int add(int num_a, int num_b); int sub(int num_a, int num_b); int mul(int num_a, int num_b); int divi(int num_a, int num_b); ``` What is the best way to pass this array into another function. I have tried:void polish(char* filename, int (*oper_ptr[4])(int, int))with for e.g.,oper_ptr[0](num_a, num_b);to call the first function.
The way you have done it works. But as always with function pointers, it's a bad idea to use them without typedef: ``` typedef int operation (int num_a, int num_b); void polish (char* filename, operation* op[4]); ```
I tried building an add function as a library with Microsoft's cl.exe, but none of the functions are able to be accessed externally. I also tried adding the Extern "C" in the header with this from another post: ``` #ifdef __cplusplus #define EXTERNC extern "C" #else #define EXTERNC #endif EXTERNC int add(int a, int b); ``` Build script: ``` cl /LD add.c ``` Built binary in Dependency Walker
To export a function you need to use__declspec(dllexport)or a.deffile. ``` __declspec(dllexport) int add(int a, int b) { return a + b; } ```
I have the following macro: ``` #define FIELD_ACCESSOR_FUNCTIONS(typeName, fieldAccessorNamePrefix) \ JNIEXPORT jobject JNICALL my_pckg_NativeExecutor_get ## typeName ## FieldValue(JNIEnv* jNIEnv, jobject nativeExecutorInstance, jobject target, jobject field) { \ return environment-> ## fieldAccessorNamePrefix ## FieldAccessor->getValue(jNIEnv, target, field); \ } FIELD_ACCESSOR_FUNCTIONS(Object, object) ``` And when I start the compilation I get the following error: ``` NativeExecutor.cpp:59:20: error: pasting "->" and "object" does not give a valid preprocessing token return environment-> ## fieldAccessorNamePrefix ## FieldAccessor->getValue(jNIEnv, target, field); \ ^~ ``` How can I solve?
Drop the first##. The name you are trying to generate isfieldAccessorNamePrefix ## FieldAccessor. The->must not be part of the token.
I have the following macro: ``` #define FIELD_ACCESSOR_FUNCTIONS(typeName, fieldAccessorNamePrefix) \ JNIEXPORT jobject JNICALL my_pckg_NativeExecutor_get ## typeName ## FieldValue(JNIEnv* jNIEnv, jobject nativeExecutorInstance, jobject target, jobject field) { \ return environment-> ## fieldAccessorNamePrefix ## FieldAccessor->getValue(jNIEnv, target, field); \ } FIELD_ACCESSOR_FUNCTIONS(Object, object) ``` And when I start the compilation I get the following error: ``` NativeExecutor.cpp:59:20: error: pasting "->" and "object" does not give a valid preprocessing token return environment-> ## fieldAccessorNamePrefix ## FieldAccessor->getValue(jNIEnv, target, field); \ ^~ ``` How can I solve?
Drop the first##. The name you are trying to generate isfieldAccessorNamePrefix ## FieldAccessor. The->must not be part of the token.
I want to print the Fibonacci series up to 50 terms but when the n is 50 it's not working it works until n <= 48. Is there any way to do that? ``` #include <stdio.h> int main() { int n; scanf("%d", &n); unsigned long long arr[50] = {0, 1}; for (int i = 0, j = 2; i < n; i++, j++) { arr[j] = arr[i] + arr[i + 1]; } for (int i = 0; i < n; i++) { printf("%d => %llu\n", i, arr[i]); } return 0; } ```
well the problem is solved I did mistakes in the loop condition so here is the updated code. ``` #include <stdio.h> int main() { int n; scanf("%d", &n); unsigned long long arr[50] = {0, 1}; for (int i = 2; i < n; i++) { arr[i] = arr[i - 1] + arr[i - 2]; } for (int i = 0; i < n; i++) { printf("%llu ", arr[i]); } return 0; } ```
How can I get the Windows Hostname (NetBIOS) while coding a windows 10 kernel driver? I know GetComputerNameExA works in User mode, but how do I do the same in kernel mode?
You can get hostname through the following registry path: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName Read the registry.
So, i've this code, but i dont know how to print result of a function foo() ``` #include <stdio.h> void foo(int arr[]){ int *sum = 0; int product = 1; for(int i = 0; i < sizeof(*arr); i++){ sum += arr[i]; } for(int i = 0; i < sizeof(*arr); i++){ product *= arr[i]; } printf("%d\n", *sum); printf("%d\n", product); } int main(){ int arr[] = {1,2,3,4,5}; foo(arr); return 0; } ``` i've been tried just to do printf(arr()); but it isn't workded, what i do incorectlly?
Try usingsumin place of*sum. ``` int sum = 0; printf("%d\n", sum); ``` It should work.
In C code, if a function is used exclusively within a file, it's good practice to declare it to bestatic. But sometimes I define a function to be static but don't actually use it (yet), in which case the compiler complains at me: ``` ../src/app.c:79:12: error: 'foo' defined but not used [-Werror=unused-function] ``` What's the right way to tell the compiler (gcc in this case) that unused static functions are okay?
You can add theunusedattribute to the function: ``` __attribute__((unused)) static void foo(void) { } ```
I have 3 object files : ``` main.o general.o specific.o ``` in main.o there is a call to function :void handle(void), general.o implement a generic functionality tohandle(), specific.o might or might not have an implementation tohandle(), I want to specify in my cmake that "search to link handle with specific.o if fail then try with general.o" Is that possible ?
There certainly is nothing in standard C++ which allows this. For Gcc/clang toolchain you can definehandleas a weak symbol ingeneralTU with__attribute__((weak))and as ordinary symbol inspecific. Be very careful with this though, ensure thathandleitself is not called ingeneral. Because if it is, the call might be inlined before the linker sees anything, resulting insomecode calling the general method, the rest specific. Link-time optimization might be actually more safe here.
Im confused of the use of the systemcall execve. The second parameter should be a pointer to the arguments but it doesnt work, it does however execute correctly when I send the whole command(/bin/bash) + arg as a second parameter. ./test /bin/bash "echo 'this is a test' | wc -c" ``` #include <unistd.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> int main(int argc, char *argv[]) { execve(argv[1], &argv[1], NULL); ////works, but I dont understand how since the 2nd param is wrong. return 0; } int main(int argc, char *argv[]) { execve(argv[1], &argv[2], NULL); ////doenst work, it should since Im sending the correct aguments. printf("hi"); return 0; } ```
argv[0]contains the name of the file being executed. Therefore,execvealso needs the file being executed as first element (index 0).
I have this linker.ld where I want to remapped ram. ``` MEMORY { ram (rx) : ORIGIN = 0x80000000, LENGTH = 8M } ``` What is the difference between adding the linker like this: ``` sparc-gaisler-elf-gcc -O2 -std=c99 linker.ld -Ttext=0x80000000 -o main.o ``` vs. ``` sparc-gaisler-elf-gcc -O2 -std=c99 -Tlinker.ld -Ttext=0x80000000 -o main.o ``` The first one I get an warning: ``` redeclaration of memory region ``` and the second one, I get ``` no memory region specified for loadable section .data ``` I don't really understand what is the difference in how -T<linker_file> and just adding <linker_file> directly.
The answer is very simple. With-Tyou replace the default linker script, without both will be used. Fist case both are used and both define the same memory regionSecond case - your linker script is far too trivial and misses all section definitions.
For example I want to type in terminal: make name and make compile and runs the name.c file without the need to specify the rule "name" in the makefile.
If you want object files to go in some other directory you'll have to create a makefile with new rules describing that. Something like this: ``` OBJDIR = obj %: %.o %: $(OBJDIR)/%.o $(LINK.o) $^ $(LDLIBS) -o $@ $(OBJDIR)/%.o: %.c $(COMPILE.c) -o $@ $< ``` The%: %.oline deletes the built-in rule.
We can use#ifdef _linux_or#ifdef __APPLE__to identify the user's operating system. But can we define different versions of the operating system? For example between macOS Big Sur and macOS Monterey. In search of an answer, I came across theAvailability.hlibrary, but I didn't quite understand how to find the right version of OS
You can test for the OS at runtime in C/C++ code like so: ``` if (__builtin_available( macOS 12.0, * )) { // Monterey or later } else { // before Monterey } ``` Of course you'll have to think about what should happen when macOS 13 comes out.
I know that using the callsystem()is like usingfork(),execl()andwait(). So the return ofsystem()is equal to the return ofwait(). My question is: how can I usewait()macros (i.e.,WIFEXITED(),WEXITSTATUS(), and so on) after usingsystem()? Because macros needs the int to whichwait()points, andsystem()don't give me that int.
system()gives you that int. Here'sPOSIX: If command is not a null pointer, system() shall return the termination status of the command language interpreter in the format specified by waitpid(). Here's Linuxman 3 system: the return value is a "wait status" that can be examined using the macros described in waitpid(2). (i.e., WIFEXITED(), WEXITSTATUS(), and so on). It also comes with an example demonstrating this: ``` while (something) { int ret = system("foo"); if (WIFSIGNALED(ret) && (WTERMSIG(ret) == SIGINT || WTERMSIG(ret) == SIGQUIT)) break; } ```
I am using an Arty Z7 and storing certain data in DDR memory and would like to view the contents of memory during the execution of my program. I would like to do this so I can ensure what I am storing in memory is what I expect. Is this possible to do this in the Vitis debugger and if so, how?
Of course this is possible to do in Vitis! I'm using Vitis 2020.2 but the steps should be largely the same in any version. Start a debug sessionPause executionClick "Window > Memory Browser"A memory browser tab opensYou can drag this tab to a different area if you likeEnter an address or expression in the boxYou can scroll the memory view to quickly access nearby memory addresses instead of typing them in.
I was hoping to implement optional arguments in c by using macros to set a function based on the variable type. ``` #define dostuff(BOOL) dostuffwithbool(BOOL) #define dostuff(INT) dostuffwithint(INT) ``` Is this kind of thing possible at all? (even though I know it probably isn't). I'd accept any answer no matter how long or hacky.
The preprocessor itself is not capable of processing C types because macros are expanded after tokenization of program but thebeforesyntactical constructs of C language are parsed. Depending on your application you can use_Genericavailable from C11. It is basicallyswitch-caseover types. ``` #define dostuff(val) \ _Generic((val), bool: dostuffwithbool \ , int: dostuffwithint) (val) ``` Note that this solution will not work ifdostuffwithbool/dostuffwithintwere function-like macros. The macros would not be expanded due to a lack of(following a macro.
I can see that methods exist for iterating over the GstElement's within a bin... but for any given GstElement is there are way to programatically determine if it is in fact a bin?
AllGstElements are derived from the GLibGObjecttype, so the GLibG_OBJECT_TYPE()macro can be used to check the type: ``` if (G_OBJECT_TYPE(element) == GST_TYPE_BIN) ... ``` Even simpler is to use the convenience macros that are declared ingstbin.h: ``` if (GST_IS_BIN(element)) ... ```
I'm trying to print a list in C that lines up the index of the list and a colon to the ouput as follows: ``` ... 8 : SOME STUFF 9 : MORE STUFF 10 : MORE STUFF BUT LESS PADDING ... 100: MORE STUFF BUT NO PADDING ... ``` I'm currently using: ``` printf("$%d", index); printf(":"): // this is the line that needs changing printf(" some stuff"); ```
``` int array[] = { 1, 2, 3, 4, 5, 6, 7, 42, 999 }; enum { NUM_ARRAY = sizeof( array ) / sizeof( array[ 0 ] ) }; for ( int i = 0; i < NUM_ARRAY; ++i ){ printf( "%-3d: sometext\n", array[ i ] ); } ``` This is a for-loop through an array. Every array-item will be printed with a padding of three. Output: ``` 1 : sometext 2 : sometext 3 : sometext 4 : sometext 5 : sometext 6 : sometext 7 : sometext 42 : sometext 999: sometext ```
Why can't I use EXIT_SUCCESS instead of 0 in the return statement in Visual Studio Code? I get the error: id "EXIT_SUCCESS" is not defined ``` #include <stdio.h> int main(void) { puts("Thanks for help"); return EXIT_SUCCESS; /*problem*/ } ```
The definitions of theEXIT_SUCCESSandEXIT_FAILUREmacros are in the "stdlib.h" header file, so you need to#include <stdlib.h>in order to use them. (Some compilers may implicitly include that header when you include "stdio.h" but you can't rely on that behaviour.)
Are these two Code equal?(clear flag) ``` ClearFlag(NewDeviceObject->Flags, DO_DEVICE_INITIALIZING); NewDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING; ```
Yes they are equal. Unlike APIs,ClearFlagis a macro. You can enter thentifs.hthat you compile with and see it. Microsoft doesn't change macros like this, because then you won't be able to use the same binary on any older windows (which is not something they like). This is why only small utilities like that are inlined. Anyway it's a much better practice and much cleaner to use the macro, so use it like you use other win macro that won't be changed for same reasons (it's just not a bug not using it).
Why when we are declaring the function fgets() we need to put -1 string from the original char? like this: ``` #include <stdlib.h> #include <stdio.h> int main () { char string[15]; fgets(string,14,stdin); // < the original variable has 15 strings, but in fgets() we need to set 14, why? printf("%s\n", string); return 0; getchar(); } ``` I'm a beginner in C, so i'm having this doubt in my mind
Youdon'tneed to.fgetstakes three arguments. A C string buffer to read into.A count of characters.A file stream to read from. It reads at mostcount - 1characters into the buffer, thus leaving room for the null terminator every C string needs. As a side note: your call togetcharfalls after thereturnand is thus completely pointless as control flow will never reach it.
Is it possible to detect at compile time that the fourth argument of vsnprintf() consists of fewer than required by the third argument of vsnprintf()? I mean: ``` #include <stdio.h> #include <stdarg.h> void foo(const char* format, ...) { char buffer[256]; va_list args; va_start (args, format); vsnprintf(buffer, 256, format, args); // args may points to fewer arguments than expected in the format va_end (args); } int main () { foo("%d %d", 1); // the format requires two arguments, but only one is provided, so a warning from the compiler is expected here return 0; } ``` gcc -Wall main.ccompiles the above without warnings
Apply an attribute tofoo. ``` __attribute__((__format__(__printf__, 1, 2))) void foo(const char* format, ...) { ``` Compile with-Werror=format.
When I'm using this code, the output is incorrect. ``` #include <stdio.h> int main() { int a, *ptr; a=10; *ptr=&a; printf("%d",*ptr); return 0; } ``` Output is:634927948 But when I'm using this code, It's giving the correct output. ``` #include <stdio.h> int main() { int a=10; int *ptr=&a; printf("%d",*ptr); return 0; } ``` Output is:10
*ptr=&a;means "write the address ofainto the memoryptrpoints to". Note thatint *ptr;is not initialized, so you're writing to a random memory location.Thus,*ptris that address ofa:(size_t)&a == 634927948.int *ptr=&a;means "ptris a pointer that points to the memory whereais located".Thus,*ptris the valueatthe address ofa, which isa == 10itself
If it is defined as follows: ``` char x[] = "abcdefg"; char y[] = {'a','b','c','d','e','f','g'}; ``` then why arrayxis not equivalent to arrayy?
When you create a manual array, you choose put or not the end character "\0", BUT when the C compiler read the second way to create the array, add automatically the end character, so it's different because have different length. You can also test with the following example, ``` #include <stdio.h> int main(void) { printf("%zu\n", sizeof(x)); printf("%zu\n", sizeof(y)); } ```
Can ZeroMQ Publisher Subscriber sockets be configured so that a newly-connected client always receive last published message (if any)? What am I trying to do:My message is a kind of system state so that new one deprecates previous one. All clients has to have current states. It works for already connected clients (subscribers) but when the new subscriber appears it has to wait for a new state update that triggers a new message. Can I configure PubSub model to send the state to the client immediately after connection or do I have to use a different model?
There is an example inthe ZMQ guidecalled Last Value Caching. The idea is to put a proxy in between that caches the last messages for each topic and forwards it to new subscribes. It uses an XPUB instead of a PUB socket to react on new connections.
I didn't find the answer on internet if there is please link it... ``` #include <stdio.h> int main(){ FILE*fp; char arr[4]; printf("Opening...\n"); fp=fopen("slide.txt", "r"); printf("Opened\n"); if(fp==NULL){ printf("No such file\n"); return 1; } fscanf(fp, "%s", arr); printf("Printing...\n"); printf("%s\n", arr); printf("Printed\n"); printf("Closing...\n"); fclose(fp); printf("Closed\n"); return 0; } ``` Content of the file: ``` ciao ``` Output that I have: ``` Opening... Opened Printing... ciao Printed Closing... Segmentation fault (core dumped) ```
Declare the character array at least like ``` char arr[5]; ``` and use ``` fscanf(fp, "%4s", arr); ``` That is you need to reserve a space in the array for the terminating zero character'\0'for the read string.
The code below is part of my code to read CAN ID in Rx callback: ``` tmpp = (((0x07 << 0x1D)|(0x368 << 0x12)) & 0x1FFC0000); //unsigned long long int tmpp - equal to 0xDA00000 if (CAN0_IF2ARB0_ID == tmpp) { //do some action } ``` The problem is that while the 29 bit CAN ID is 0xDA00000, the condition is not true. But when I directly set tmpp astmpp = 0xDA00000, the program successfully enters the loop. In fact, the calculationtmpp = (((0x07 << 0x1D)|(0x368 << 0x12)) & 0x1FFC0000);seems to have some problem (the value is 0xDA00000, but in Softune, it is not calculated correctly). I would be grateful if you could help me to find the problem. Thanks.
0x07is anint- perhaps even a 16-bitint. Use at leastunsigned longconstants for values to be shifted into a 32-bit value. ``` // tmpp = (((0x07 << 0x1D)|(0x368 << 0x12)) & 0x1FFC0000); tmpp = ((0x07ul << 0x1D) | (0x368ul << 0x12)) & 0x1FFC0000u; ```
``` struct child { char name[32]; int height; }; struct child group_a[8]; ``` I'd like to initialise every child in group_a with the same name and height, for example name = "XXX" and height = "100". Is there a quick of doing it, rather thanstruct child group_a[8] = {{"XXX", 100}, {"XXX", 100}, ..., {"XXX", 100}}?
It cannot be done in standard C without deeper preprocessor magic. However there is an extension for ranges in designated initializers. It is supported by main compilers (GCC, CLANG, Intel). ``` struct child group_a[] = { [0 ... 7] = { .name = "XXX", .height = 100 } }; ```
``` #include <stdio.h> int main() { int A, B; int SOMA = A+B; scanf("%d%d", &A, &B); printf("SOMA = %d\n", SOMA); return 0; } /* INPUT --> OUTPUT 30 10 --> SOMA = 16 1 3 --> SOMA = 16 300 1000 --> SOMA = 16 */ ``` why am i getting these results instead of the sum? I wanted the message "SOMA = sumValue" with the end of the line.
``` int SOMA = A+B; scanf("%d%d", &A, &B); ``` You are addingAandBbefore the user has input any values. Reverse those two.
``` p = (int *)malloc(m * n * sizeof(int)); ``` If I usepas a two-dimensional dynamic array, how do I access the elements inside?
If you can rely on your C implementation to support variable-length arrays (an optional feature), then a pretty good way would be to declarepas a pointer to (variable-length) array instead of a pointer toint: ``` int (*p)[n] = malloc(m * sizeof(*p)); // m rows, n columns ``` Then you access elements using ordinary double indexes, just as if you had declared an ordinary 2D array: ``` p[0][0] = 1; p[m-1][n-1] = 42; int q = p[2][1]; ``` Most widely used C implementations do support VLAs, but Microsoft's is a notable exception.
How can I find using C if a binary search tree is too tall relatively fast (most of the time)? To be more specific , lets say I need to find if a tree has a height of at least 10 ,without having to search the whole treemost of the time. (This is possible because I expect most of the input to be binary search trees which have a heigh greater than 10.)
If there are no preconditions about the structure of the tree, there's no other way but checking one side of the tree, then the other. ``` int check_depth(struct tree *root, int depth) { if (!root) { return 0; } else if (depth <= 1) { return 1; } else { return check_depth(root->left, depth-1) || check_depth(root->right, depth-1); } } ```
This question already has answers here:If free() knows the length of my array, why can't I ask for it in my own code?(9 answers)Closedlast year. I need to read inputs from a csv and put it into a dynamically allocated arrayAy. ``` int* Ay = malloc(nz * sizeof(int)); ``` The number of inputs from the csv will vary in each case. Later I passAyto another function where I need to calculate its length. I have used the following methods but it doesn't give me the right result. ``` int Aylen = sizeof(Ay) / sizeof(Ay[0]); ``` or ``` int Aylen= 1[&Ay] - Ay; ``` or ``` int Aylen=*(&Ay+1)-Ay; ``` Please suggest a way to find the length. Thank you.
There is no portable way to determine the size of a dynamically allocated buffer. You need to keep track of that yourself. This means you have to pass bothAyandnzto any function that accessesAy.
I was trying an experiment and I expected this code to throw an exception or print ambiguous value for n and exit but its end up running infinitely. Why it runs infinitely? ``` #include <stdio.h> int main() { int y=5; int n=4; while(y || n) { printf("n = %d y = %d\n",n,y); y--; n--; } return 0; } ```
The loop runs as along ayORnare non-zero. For the loop to terminate,yandnwould both have to be zero at the top of the loop, but that never happens becauseyandnstart off not being equal to each other and each of them goes down by one each iteration. Also note that signed integer overflow/underflow isundefined behavior, so if you run the loop long enough for that to happen, there are no guarantees about what will happen.
I thought I could return an array like I do in Java, but I think there is no way to declare acharfunction in C.
No. You return an array via a pointer (possible embedded in a struct either as a pointer or an array). The array is either dynamically allocated in the function, or passed into the function as an argument and then returned again: ``` char *f() { char *s = malloc(42); ... return s; } ``` ``` char *f2(char *s) { ... return s; } ```
If you'rereading from a regular file, and it returns 0 because you got to EOF, but then someone else appends something to the file, a subsequentreadsyscall will give you the new data. Similarly, if you'rereading from a TTY, and it returns 0 because the user hit Ctrl+D, but then the user types some more text, a subsequentreadsyscall will give you the new data. But what about if you'rereading from a pipe? Is it ever possible that onereadsyscall could return 0, and that a later one would then get more data out of a pipe?
Yes.readon the same FD will start returning data again if something reopens the pipe for writing. You can easily reopen named pipes, and Linux lets you reopen anonymous pipes by writing to/proc/<pid>/fd/<fd>. In particular, you can open this file for writing even if the FD is only open for reading in the process that you're getting it from.
I've just started learning C and I've decided to create a while loop to make sure I get the hang of things. This is my code: ``` #include <stdio.h> void main(){ int num, guess, turns; num = 13; guess = getchar(); turns = 0; while(guess != num){ printf("%d", guess); ++turns; printf("Turns:\n"); printf("%d", turns); guess; } } ``` It gives me an infinite loop. Can someone please tell me where I went wrong? Also, if you have any suggestions or tips, please feel free to leave them.
getchar() does not read from terminal, you have to use: ``` scanf(" %d", &guess); ``` In the while loop you have to read a value from terminal again (if the guess is wrong) ``` while(guess != num){ printf("Turns:\n"); printf("%d", guess); ++Turns; scanf(" %d", &guess); } printf("%d is the correct guess", guess); ```
I would like to store all bits of adoublein a 64-bit integer in C. I.e. the most significant bit should be the sign, after that the exponent, then the fraction. I would like to use a union.
The safest way to do this is to usememcpy. ``` double x = 123.456; uint64_t y; memcpy(&y, &x, sizeof y); ``` If you don't havememcpyat your disposal, you can use aunion: ``` union { double d; uint64_t i; } u; double x = 123.456; uint64_t y; u.d = x; y = u.i; ```
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 Description Searches for the last occurrence of the character c (an unsigned char) in the string pointed to by the argument str. The terminating null character is considered to be part of the string. Returns a pointer pointing to the last matching character, or null if no match was found.
The functionstrrchr()is very simple to write in C: it suffices to iterate on the string, remembering the last position where the character was seen... ``` #include <string.h> /* 7.24.5.5 The strrchr function */ char *strrchr(const char *s, int c) { const char *p = NULL; for (;;) { if (*s == (char)c) p = s; if (*s++ == '\0') return (char *)p; } } ```
Which one should I choose: 1.pcloseshould not be attempted ifpopenhas already failed, even though it's tolerant in handlingNULLhandle. 2.Passing whateverpopenreturns topclose, just like it's ok to pass whatevermallocreturns tofree. After I carefully read the manual(i.e.:man pclose), I can't find any evidence thatpclosecould handleNULLparameter.
Since the documentation doesn't demand thatpclosegracefully handle aNULLargument, you can't rely upon it. Now, it may be that a particular libc implementation provides that guarantee but, if you want to maintain portability, you should only rely upon guaranteed behavior.
During my programming activities I encountered a problem with running out of RAM memory. The message says; ``` Error[e16]: Segment DATA16_Z (size: 0x638 align: 0x1) is too long for segment definition. At least 0x44 more bytes needed. The problem occurred while processing the segment placement command "-Z(DATA)DATA16_I,DATA16_Z,DATA16_N=0200-_SYS_RAM_END", where at the moment of placement the available memory ranges were "CODE:20b-7ff" Reserved ranges relevant to this placement: 200-7ff DATA16_I Error while running Linker ``` So now I would like to have more information about DATA16_I, DATA16_Z and CSTACK on msp430 microcontroller, can anyone help me understand what these memory segments mean?
Simply read your compiler documentationhttps://wwwfiles.iar.com/msp430/webic/doc/EW430_CompilerReference.pdf for example: