question
stringlengths
24
425
answer
stringlengths
5
405
This question already has answers here:Two semicolons inside a for-loop parentheses(4 answers)Closed6 years ago. I'm analyzing a C program and i find this loop that i can't understand. There is no counter or limit or variable. ``` /* ioloop */ for (;;) { // statements } ``` is this an infinite loop ?
It's an idiomatic way of writing a potentially infinite loop in C. Alternatives such aswhile(1)often issued a compiler warning.
What's the exact difference betweenprintkandpr_infofunctions ? And under what conditions, should I choose one over the another ?
Thekernel's printk.hhas: ``` #define pr_info(fmt,arg...) \ printk(KERN_INFO fmt,##arg) ``` Just like the name,pr_info()isprintk()with theKERN_INFOpriority.
I am working on a project in the X11 API, and I have a Window based custom control consistently rendering. But for some reason, when I re-size the window, the control does not redraw unless I interact with the control directly, or move the entire main window.
I found the solution to my problem. I just needed to add the Structure Notify Mask to my custom window input. ``` XSelectInput(display, CustomWindow, StructureNotifyMask); ```
Regarding c variables, I want to know what the x does in: ``` int var[x] ```
This is a declaration of aVariable Length Array(VLA). The value of expressionx(most likely, a variable) is treated as the number of array elements. Itmust have a positive valueat the time the expression is evaluated, otherwise the declaration of the VLA produces undefined behavior.
Isdup(file_des)equivalent tofcntl(filedes, F_DUPFD, 0)? Ifyes, then which is better to use?
Yes it exactly the same. According to theposixstandard The dup() function provides an alternative interface to the service provided by fcntl() using the F_DUPFD command. The call dup(fildes) shall be equivalent to:fcntl(fildes, F_DUPFD, 0); dup()is shorter and easier to read, I would use that.
Regarding c variables, I want to know what the x does in: ``` int var[x] ```
This is a declaration of aVariable Length Array(VLA). The value of expressionx(most likely, a variable) is treated as the number of array elements. Itmust have a positive valueat the time the expression is evaluated, otherwise the declaration of the VLA produces undefined behavior.
Isdup(file_des)equivalent tofcntl(filedes, F_DUPFD, 0)? Ifyes, then which is better to use?
Yes it exactly the same. According to theposixstandard The dup() function provides an alternative interface to the service provided by fcntl() using the F_DUPFD command. The call dup(fildes) shall be equivalent to:fcntl(fildes, F_DUPFD, 0); dup()is shorter and easier to read, I would use that.
I can't seem to find the answer on here, but I'm sorry if this is a duplicate. Here's my question: When I have two pointers to the same location, then I change the address of one (let's say pointer A), will I (by accident) be changing the address of the other pointer (pointer B)? Or will pointer B's location stay the same?
Changing the contents of a pointer (as opposed to the object being pointed to) will not affect other pointers to the same object.
I can't seem to find the answer on here, but I'm sorry if this is a duplicate. Here's my question: When I have two pointers to the same location, then I change the address of one (let's say pointer A), will I (by accident) be changing the address of the other pointer (pointer B)? Or will pointer B's location stay the same?
Changing the contents of a pointer (as opposed to the object being pointed to) will not affect other pointers to the same object.
I have recently started to learn ANSI C. I have come across this: ``` int a[7]; *(a+2); ``` I don't understand how it's possible to add 2 toa. Does it add 2 to every element ina? Also, what is the function of the*? Does it create a pointer?
a+2causesato be interpreted as a pointer toa's first element. This is calledarray decaying. It then offsets that pointer by2anddereferences(*) the resulting pointer. So it's the same asa[2].
Are there any static code metrics tools that measure total size of static local variables in c functions. The tools that I explored report the stack size but not the size of the static local variables. Is there another option apart from using linux objdump and parsing the output?
The POSIXsizecommand can be used for this purpose. The size of the data section is the size of all data in static storage (except data declared const on some targets).
Everytime I compile and run c file, I have to type: gcc filename.c a.out I don't want to do this in two lines, How to compile and run in one line on linux terminal?
Try ``` gcc filename.c && a.out ``` It only runs the second command if the first was successful. Seehttps://askubuntu.com/questions/334994/which-one-is-better-using-or-to-execute-multiple-commands-in-one-line
The .txt file will have the matrix we need to input into our program, it may have more than one matrices. I am using VIM editor on Linux. Is there any specific escape sequence to copy the .txt file while compiling?
To redirect standard output to a file, the>character is used like this: ls > file_list.txt And To take input from the file , the<character is used like this: ./a.out < input.txt
How to print the formatting characters such as:%pout? A backslash doesn't do any good as it does with quotations(""). I tried it in a simple toy program and I suppose the value returned by it was garbage : What I was trying to print was the statement : ``` With the formatting character %p and '&' ```
Using double percentage i.e.%%will print single%for you: ``` printf("With the formatting character %%p and '&'\n"); ```
How to print the formatting characters such as:%pout? A backslash doesn't do any good as it does with quotations(""). I tried it in a simple toy program and I suppose the value returned by it was garbage : What I was trying to print was the statement : ``` With the formatting character %p and '&' ```
Using double percentage i.e.%%will print single%for you: ``` printf("With the formatting character %%p and '&'\n"); ```
I want the program to print the wordhelloto the text file by means of strings. ``` #include <stdio.h> void main () { char word[10] = {"hello"}; FILE*fp; fp = fopen("C:\\temp\\Dictionary.txt", "w+"); fprintf(fp, word[0]); } ```
You're printing first char instead of the string. And it might not be a valid format either. Correct call will befprintf(fp, "%s", word). And don't forget to close file too.
Is it possible to multiply usingi**in C? For example, I can incrementiusingi++. Why doesn'ti**work in C? ``` #include <stdio.h> int main(void) { int result; for (int i = 2; i < 100; i**){ result = i + 1; printf("%i\n", result); } return 0; } ```
No, it's not possible. There is no operator like**in C unlike unary increment (++) and decrement (--) operators. You should have tryi *= i.
Is it possible to multiply usingi**in C? For example, I can incrementiusingi++. Why doesn'ti**work in C? ``` #include <stdio.h> int main(void) { int result; for (int i = 2; i < 100; i**){ result = i + 1; printf("%i\n", result); } return 0; } ```
No, it's not possible. There is no operator like**in C unlike unary increment (++) and decrement (--) operators. You should have tryi *= i.
Let's say we have the following C code: ``` #include<stdio.h> int main(){ char *a = "askakasd"; return 0; } ``` I tried to find my local variable "a", but I don't know how to recognize it looking in this output, where p is the C code compiled:
It's not there. Since the code can't tell at execution time whether it's there or not, the linker removed it to save space.
Probably really trivial question, but: Recently started working an open-source system -janus-gatewayand i am in a need to run a method every 1 second(checking if all users muted). What are the options to do this in C? Should i spawn a new thread? Answer with an example would much appreciated!
Ended up spawning a new thread and doing stuff that way.
Let's say we have the following C code: ``` #include<stdio.h> int main(){ char *a = "askakasd"; return 0; } ``` I tried to find my local variable "a", but I don't know how to recognize it looking in this output, where p is the C code compiled:
It's not there. Since the code can't tell at execution time whether it's there or not, the linker removed it to save space.
Probably really trivial question, but: Recently started working an open-source system -janus-gatewayand i am in a need to run a method every 1 second(checking if all users muted). What are the options to do this in C? Should i spawn a new thread? Answer with an example would much appreciated!
Ended up spawning a new thread and doing stuff that way.
Probably really trivial question, but: Recently started working an open-source system -janus-gatewayand i am in a need to run a method every 1 second(checking if all users muted). What are the options to do this in C? Should i spawn a new thread? Answer with an example would much appreciated!
Ended up spawning a new thread and doing stuff that way.
!I had written this simple program on a different Ubuntu PC using Gedit]1
You do not have execute permissions for your executable. Use ``` chmod +x ./secondo ``` first to correct this. Thisquestion gives more detail.
!I had written this simple program on a different Ubuntu PC using Gedit]1
You do not have execute permissions for your executable. Use ``` chmod +x ./secondo ``` first to correct this. Thisquestion gives more detail.
How to decide if two ip are on the same subnet or not? The only input is the ip address and the subnet mask! What is the optimal way, usingC/C++, to compute if two ip have the same subnet?
``` bool checkForSubnetEquality(in_addr_t ipA, in_addr_t ipB, uint32_t subnetMask) { return (ipA & subnetMask) == (ipB & subnetMask); } ```
I have searched on the Internet but most of the answers suggest using library conio.h which is not available. Can anyone give me answer for this question. Thanks in advance.
If you are on Windows system("cls"); If you are on Linux/unix system("clear");
How to decide if two ip are on the same subnet or not? The only input is the ip address and the subnet mask! What is the optimal way, usingC/C++, to compute if two ip have the same subnet?
``` bool checkForSubnetEquality(in_addr_t ipA, in_addr_t ipB, uint32_t subnetMask) { return (ipA & subnetMask) == (ipB & subnetMask); } ```
I have searched on the Internet but most of the answers suggest using library conio.h which is not available. Can anyone give me answer for this question. Thanks in advance.
If you are on Windows system("cls"); If you are on Linux/unix system("clear");
How to cast "ptr" to assign directly a zend_long into it without writing two lines? ``` zend_long *val = *ptr; *val = *(ISC_LONG*)var->sqldata; ```
Assuming that your original code is correct, the corresponding assignment looks like this: ``` *((zend_long*)*ptr) = *(ISC_LONG*)var->sqldata; ```
I am trying to initiate a TCP Three-Way-Handshake in C. However, it occurred to me thatconnectmay already be establishing such a connection or in some way interfering. Doesconnectautomatically establish a TCP connection whenever the socket it's called on has theIPPROTO_TCPoption set?
Yes,IPPROTO_TCPcreates TCP socket. To use raw socket, you need to pass SOCK_RAW as second argument to thesocketfunction.
How would I go to cast/convert literalchar '0'toint 0? i.e.: ``` char string[] = "0101"; char ch = string[0]; x = magic(ch); if (x) printf("int zero") ```
``` ch = 0; ``` Now, if you want to convertanydigit-character to its numeric equivalent, you'd need something like: ``` ch = ch - '0'; ```
I am trying to initiate a TCP Three-Way-Handshake in C. However, it occurred to me thatconnectmay already be establishing such a connection or in some way interfering. Doesconnectautomatically establish a TCP connection whenever the socket it's called on has theIPPROTO_TCPoption set?
Yes,IPPROTO_TCPcreates TCP socket. To use raw socket, you need to pass SOCK_RAW as second argument to thesocketfunction.
How would I go to cast/convert literalchar '0'toint 0? i.e.: ``` char string[] = "0101"; char ch = string[0]; x = magic(ch); if (x) printf("int zero") ```
``` ch = 0; ``` Now, if you want to convertanydigit-character to its numeric equivalent, you'd need something like: ``` ch = ch - '0'; ```
It is undefined behavior to do this? ``` char *a = "hello"; char b[] = "abcd"; a = b; ``` My compiler throws no warning, with the maximum warning level.
There is no UB here. You are simply re-assigning a pointer to point at the address of the start of the array instead. Note that you are not actually modifying the value thatais pointing at, onlyaitself, andais a normalchar *.
How to convert rgb to hexadecimal using GTK? I can convert from hex to rgb usinggdk_rgba_parse (GdkRGBA *rgba, const gchar *spec);, but not the reverse.
You can do this manually: ``` sprintf(spec, "#%02X%02X%02X", (int)(rgba.red*255), (int)(rgba.green*255), (int)(rgba.blue*255)); ``` Be sure to provide a buffer large enough to hold the string or use g_strdup_printf instead.
How to convert rgb to hexadecimal using GTK? I can convert from hex to rgb usinggdk_rgba_parse (GdkRGBA *rgba, const gchar *spec);, but not the reverse.
You can do this manually: ``` sprintf(spec, "#%02X%02X%02X", (int)(rgba.red*255), (int)(rgba.green*255), (int)(rgba.blue*255)); ``` Be sure to provide a buffer large enough to hold the string or use g_strdup_printf instead.
This question already has answers here:Maximum size of a bit field in C or C++? [duplicate](2 answers)struct bitfield max size (C99, C++)(4 answers)Closed6 years ago. Is the following code legal? ``` struct BigInt { uint64_t a : 128; }; ```
A bitfield must fit within a singleint, so you're out of luck unlessintis 128 bits on your platform. (You were also missing a;at the end of thestructprior to the edit.)
I have one program that uses shared library. In shared library, error case they have written exit(0). So if that function is called then exit(0) will be executed of shared library. Will it exit my program too ?
Yes it terminates the calling process immediately.SIGCHLD signal will be send to process which inherited by process 1 or init.
I got a warning: ``` assignment makes integer from pointer without a cast. ``` The line that triggers the warning is: ``` nev[i][0]=""; ``` Thenevvariable is a 2 dimension char block(please don't ask why, I don't know). Thanks in advance guys!
Ifnevis a 2-dimensional array ofchar, thennev[i][0]is achar. But""is an array ofchar, not achar. – Barmar nev[i][0]="";-->nev[i][0]=0;– BLUEPIXY
As the title suggests, I would like to create connection between a JavaScript (usingWebSocket) client and a C/C++ (usingWinsock) server. A simple code example would be much appreciated.
You can't use Websocket at java side and a Winsock only implementation on C++ side, you have to implement Websocket over winsock or using some thing like Qt Platform which has an implementation Websocket under C++. sample codes are available onQt Docs.
In my program I have got a NxN table stored in one-dimensional table. So, I use#define Board(x,y) board[(x)*N + (y)]and works perfectly So, what if my board becomes N1xN2 and N1 is different than N2? How should I set the #define instruction then? thank you in advance
It shouldn't work perfectly. You need(board[(x)*N+(y)])for square boards, and(board[(x)*N2+(y)])for non-square boards, assuming x from 0 to N1-1, y from 0 to N2-1
In my program I have got a NxN table stored in one-dimensional table. So, I use#define Board(x,y) board[(x)*N + (y)]and works perfectly So, what if my board becomes N1xN2 and N1 is different than N2? How should I set the #define instruction then? thank you in advance
It shouldn't work perfectly. You need(board[(x)*N+(y)])for square boards, and(board[(x)*N2+(y)])for non-square boards, assuming x from 0 to N1-1, y from 0 to N2-1
I wonder how to convert like a char: 1101_0110(D6) to two char(ascii format) 0100_0100(44) and 0011_0110(36). Thanks a lot!
sample code ``` #include <stdio.h> int main(void){ char x = '\xD6'; char asc[3]; sprintf(asc, "%02X", (unsigned char)x); printf("%s\n", asc);//D6 } ```
I wonder how to convert like a char: 1101_0110(D6) to two char(ascii format) 0100_0100(44) and 0011_0110(36). Thanks a lot!
sample code ``` #include <stdio.h> int main(void){ char x = '\xD6'; char asc[3]; sprintf(asc, "%02X", (unsigned char)x); printf("%s\n", asc);//D6 } ```
I'm searching for a method to convert a two Byte UNICODEora variable (1-3 Byte) UTF-8 string to Chinese Simplified (GB2312). I found a lot of methods for php, Java, C# and Windows but nothing for standard "C". Right now, my best solution is to translate this JavaScript example:https://gist.github.com/19317362/a1d8e40bfb6587463d4d Thanks in advance!
As Remy Lebeau mentioned, I used the C-compatible library iconv.
I know the difference betweenself.xxxand_xxxBut I don't understand the difference betweenself->_xxx = yyyand_xxx = yyy Is it only a matter of writing in ObjC and C?
When accessing an ivar there is no difference betweenself->_ivarand_ivarin terms of resulting compiled code. Only use case I can think of where it matters is if you have another local or global variable with the same name in the same scope, and you want to use the ivar.
Normally when a foo() have memory problem the whole program will simply core dump, crash. But does C have any protection ways to guarantee a program will not crash, just goto a state or simply return, when core dump happens inside foo()?
Can not say for try and catch statement in c but yes you can write signal handler to catch segfault. Here is a link.How to catch segmentation fault in Linux?
The code i'm looking for is the following : We have a source number100, a destination number,50and we have10steps. 100 ----> 50 in 10 steps. How can i find the value X, corresponding tothe number i have to subto 100, 10 times to have 50. I found :dest*steps/srcbut didn't work... Regards.
It's as simple as this ``` X = (src-dest)/NumOfSteps ```
I was trying some C codes in Dev C++ and Visual C++. For Example: ``` int t =6; printf("\nt = %d ",&t); ``` The output is : ``` t = 2358848 ``` why is it so ? How can I get the value of t?
&tgives you theaddress oft, not its value. To print the value do: ``` printf("\nt = %d ", t); ```
If I have a .jar file with a compiled scala method, is there any way to call it from a C/C++ dll ? How can I do this? I have only been able to find infos on the opposite.
A Scala program (once compiled) is a Java class. So follow this suggestion:How to access the Java method in a C++ application
When I try to execute a c code with the following two lines, ulimit still shows to be unlimited but i want the answer to be 1024. system("ulimit -d 1024"); system("ulimit -d");
If you want to set the ulimit for calling process, usesetrlimit(2), with arguemntRLIMIT_DATA. system()will fork and the ulimit command only affects the child process, not the calling process.
When I try to execute a c code with the following two lines, ulimit still shows to be unlimited but i want the answer to be 1024. system("ulimit -d 1024"); system("ulimit -d");
If you want to set the ulimit for calling process, usesetrlimit(2), with arguemntRLIMIT_DATA. system()will fork and the ulimit command only affects the child process, not the calling process.
So I compiled a simple cpp program using clang++ with termux on android, but I can't run the program, I get the following error: ``` $ ./execname -bash: . /execname: Permission denied ```
Are you running on shared storage (under/sdcard)? The file system there does not support executable permissions. Try compiling and running the file directly in the$HOMEdir!
I wrote my c program add.c, then preprocessed with cpp, then compiled with CC to obtain an add.s file. Now I would like to open it to see the assembly code. Can't find a way to do it.
The.sfiles are basically assemblersourcefiles, so you can pretty much open them in whatever tool you used to create the.cfiles in the first place. In other words, mere mortals will opt forNotepad++orEmacs, but the true intelligentsia will useVim:-)
This question already has answers here:How to generate a random int in C?(32 answers)Closed6 years ago. Here is my code: ``` alpha = ((rand() % 12) + 1) * 2 + 1; ``` I want to generate randomoddnumbers between 0-25. But except integer13. How can I fix this? Thank you.
Generates number from 0 to 23. If it's a 13, then store 25 in your variable : ``` alpha = ((rand() % 11) + 1) * 2 + 1; if (alpha == 13) alpha = 25; ```
I have achar*to where I want to set the byte, from malloc. How do I set it to 1 or 0, for example?
Assign to your dereferenced pointer: ``` //This will (obviously) set it to 1 *your_pointer = 1; //This will set it to 0 *your_pointer = 0; ```
``` char msg[100] = {’C’,’P’,’R’,‘E’,‘\0’,‘2’,‘8’, ‘8’,‘\0’}; int my_length = 0xFFFFFFFF; my_length = strlen(msg); ``` I thought it is nine, however, the answer is 4. anyone can explain? thanks
strlenwill stop counting as soon as it hits a null terminator (as C uses null terminated strings and expects to only find them at the end of a string). You have four characters before your first null terminator, therefore the length is 4.
I am trying to compile a C program and am required to use these flags. I was hoping you could tell me why I am getting these errors. Command: ``` gcc -ansi –Wall –pedantic stack.c ``` Output: gcc: –Wall: No such file or directorygcc: –pedantic: No such file or directory
It's ``` gcc -ansi -Wall -pedantic ``` You're using one of those dashes:Dash(specifically, you are using en-dash U+2013). You need to use minus sign-instead
I am working on compiler design for 8051. I want to declare a memory of say 30 locations, each location is of 8bits. How do I declare that in C?
to declare 30 x 8 bits memory: ``` char memory[30]; ``` to declare n x n memory: ``` char memory[30][30]; ``` it declares 30 x 30 x 8bits memory.
What is the exact equivalent of the following function for Ubuntu? http://www.qnx.com/developers/docs/6.4.1/neutrino/lib_ref/e/endian_be16.html
What you need is: ``` #include <endian.h> result_in_host_endianness = be16toh(my_big_endian_number) ``` Seehttp://man7.org/linux/man-pages/man3/endian.3.html
What is the exact equivalent of the following function for Ubuntu? http://www.qnx.com/developers/docs/6.4.1/neutrino/lib_ref/e/endian_be16.html
What you need is: ``` #include <endian.h> result_in_host_endianness = be16toh(my_big_endian_number) ``` Seehttp://man7.org/linux/man-pages/man3/endian.3.html
I have several header and source files that I needed to create, in which there are functions that generate random numbers. If I wanted to initialize my rng, where do I have to put my "srand(time(NULL))" line, in my code? Is it ok to put it in my main.c file? Does it affect the other source files?
Yes, you can put it in the main file. Once you callsrandit is applicable for the entire program, even if it has multiple files.
The title is the exact error my compiler(geany on ubuntu) gives me when I try to compile. The part of code in question is the following: ``` for(int q=strlen(stringA)-1;q>0;q--) { //do stuff } ``` I've already set the C99 mode and the initialization of variables in the 'for' header is accepted. Is what I did simply illegal in C?
I assume you are missing an include. Try: #include <string.h>
I am usingfPointInput = fopen(fileName, "r");, when trying to access the data chunk inide the .WAV file but never getting any comprehensible results. (Data array is filled mostly with zeroes except the first few hundred indices). Can this be caused by the usage of inaccurate opening mode ?
Thisarticleindicates that usingrbworks well. Note that nothing in this answer isWindowsspecific. Just standardCIO.
The title is the exact error my compiler(geany on ubuntu) gives me when I try to compile. The part of code in question is the following: ``` for(int q=strlen(stringA)-1;q>0;q--) { //do stuff } ``` I've already set the C99 mode and the initialization of variables in the 'for' header is accepted. Is what I did simply illegal in C?
I assume you are missing an include. Try: #include <string.h>
I am usingfPointInput = fopen(fileName, "r");, when trying to access the data chunk inide the .WAV file but never getting any comprehensible results. (Data array is filled mostly with zeroes except the first few hundred indices). Can this be caused by the usage of inaccurate opening mode ?
Thisarticleindicates that usingrbworks well. Note that nothing in this answer isWindowsspecific. Just standardCIO.
I want to use interrupt handlers ``` void EXTI3_IRQHandler(void) { //body } ``` but when I build the project, I get the following error: SymbolEXTI3_IRQHandlermultiply defined (by stm32f10x_it.o and main.o) I have included library stm32f10x_exti.h
Handlervoid EXTI3_IRQHandler(void)already defined in filestm32f10x_it.c. You can replace code of your handler frommain.cto this special file or comment blank handler instm32f10x_it.c.
What would this translate to (in a more verbose way)? ``` local.sin_addr.s_addr = (!ip_address) ? INADDR_ANY:inet_addr(ip_address); ``` Trying to understand Ternary operators and I can't quite get it.
A ternary is similar to anifstatement, but it can be used where an expression is required. So it's equivalent to: ``` if (!ip_address) { local.sin_addr.s_addr = INADDR_ANY; } else { local.sin_addr.s_addr = inet_addr(ip_address); } ```
I want to do an evented read on Serial port which will run only when the data is available. I have triedsigactionbut it causes problem when making a highly threaded application, alsosleepfunction seem to work incorrectly according to many forums. So I am looking for a similar way as in windowsWaitCommEventthat is used in MSDN.
The canonical equivalents for linux systems is to usepoll()orselect(). Workings are different of course.
I want to do an evented read on Serial port which will run only when the data is available. I have triedsigactionbut it causes problem when making a highly threaded application, alsosleepfunction seem to work incorrectly according to many forums. So I am looking for a similar way as in windowsWaitCommEventthat is used in MSDN.
The canonical equivalents for linux systems is to usepoll()orselect(). Workings are different of course.
If "Allow windows manager to decorate window" is on. What is the function name in the wine source that knows a user click this X button and send the WM_CLOSE to the app? Thank you
The window manager sends ClientMessage with type WM_PROTOCOLS and the protocol value WM_DELETE_WINDOW. This is handled in dlls/winex11.drv/event.c: X11DRV_ClientMessage() -> handle_wm_protocols().
While running a sample code from the internet, I am stuck at 'glutTimerfunc'. I cannot figure out what is this error.
glutTimerFunctakes a pointer to a function that must have a signature of ``` void (*func)(int value) ``` YourframeTimerCallbackfunction doesn't take an integer parameter. Hence the error. Refer tohttps://www.opengl.org/resources/libraries/glut/spec3/node64.html
This question already has answers here:Yosemite and Valgrind(12 answers)Closed6 years ago. I am not sure if I can installvalgrinddebugger in my Macbook Pro. I searched online but most posts are related to Ubuntu. Can someone tell if this is possible? If so, can it be by brew for example?
you can use "brew install valgrind" to install valgrind.
Is there any way to roundsystemGuessup. In this case the outcome ofsystemGuessis 5.5 I want it to be 6 how do I do this? See code below: ``` int main(void){ int systemGuess = 0; stystemGuess = (10 - 1)/2 + 1; printf(" %d ", stystemmGuess); } ```
Use floating point division andceil: ``` stystemGuess = ceil((10 - 1)/2.0) + 1; ``` If you want to round 0.4 down, useroundinstead.
Why we don't use extern when using function from one .c file in another .c file , but we must do extern for variables case? Is it related to linker?
Functions are extern qualified by default (unless you change it to internal withstatic). For example, ``` int func(void) { } extern int func2(void) { } ``` Bothfuncandfunc2are external. Theexternkeyword is optional for external functions.
``` int j=4; (!j!=1)?printf("Welcome"):printf("Bye"); ``` In the above code segment, according to me, firstj!=1will result in true and!trueis false which must result in printingByebut I getWelcomeas the output. Can anyone explain this one?
!executed first because unary operator!has a higher precedence than!=. !4become0then0 != 1becometrue. So, output isWelcome.
I'm programmingSTM8micro controller inSTVD. I happen to use an assembly instruction in the middle of code. As shownhereI used a instruction as below ``` asm("MOV $00500A,#$3"); ``` But I'm facing with following error ``` #error cpstm8 ..\app\sched.c:183(5) missing prototype ``` Can anyone help me in fixing this?
For STM8 assembly instruction, you need to use_before the instruction as shown below ``` _asm("MOV $00500A,#$3"); ```
I'm programmingSTM8micro controller inSTVD. I happen to use an assembly instruction in the middle of code. As shownhereI used a instruction as below ``` asm("MOV $00500A,#$3"); ``` But I'm facing with following error ``` #error cpstm8 ..\app\sched.c:183(5) missing prototype ``` Can anyone help me in fixing this?
For STM8 assembly instruction, you need to use_before the instruction as shown below ``` _asm("MOV $00500A,#$3"); ```
GDB is showing the content of a register as ``` rbp 0x604420 0x604420 <sval> ``` What does sval mean? Does it means string val?
What does sval mean? It means that there is a symbol (givenx86_64target,0x604420would usually mean it's a.textsymbol) with that value in the binary, andrbphappens to point to that symbol. You can runnm your-binary | grep svaland see that symbol. Does it means string val? No,nothingof the sort.
I am learning C usingthissite. Underfgetc()Function the author said: This function reads a single character from a file and after reading increments the file position pointer. ``` FILE *fp; fp = fopen(filename, "r"); ``` What I want to ask is that thefile position pointeris different from the pointerfpor not?
It means your current offset in the file. It is the return value offtell.
GDB is showing the content of a register as ``` rbp 0x604420 0x604420 <sval> ``` What does sval mean? Does it means string val?
What does sval mean? It means that there is a symbol (givenx86_64target,0x604420would usually mean it's a.textsymbol) with that value in the binary, andrbphappens to point to that symbol. You can runnm your-binary | grep svaland see that symbol. Does it means string val? No,nothingof the sort.
I'm trying define "ip_addr" from lwip. That's my code: ``` #include "lwip/tcp.h" #include "ip_addr.h" ... struct ip_addr ip; ``` But when i'm trying to compile this, compiler gives me error: ``` error: storage size of 'ip' isn't known ```
Try: ``` ip_addr_t ip; ``` and your second #include line should it not be: ``` #include "lwip/ip_addr.h" ```
my code can be compiled with C or C++ compilers. I'd like to know which one is doing the compilation is there preprocessor define to tell me this ?
The definition is__cplusplus. ``` #ifdef __cplusplus // treated as C++ code #else // treated as C code #endif // __cplusplus ```
my code can be compiled with C or C++ compilers. I'd like to know which one is doing the compilation is there preprocessor define to tell me this ?
The definition is__cplusplus. ``` #ifdef __cplusplus // treated as C++ code #else // treated as C code #endif // __cplusplus ```
I want to create a socket connected directly to the gpu. I would like to send data from a server to the gpu without spending a copy/moving time from host to device. Is it possible?
If you have suitable network hardware and are willing to write your own device driver for your network adaptor, thenmaybe.SeveralInfiniband and iWARP adapter vendors can have engineered such support for their products. But realistically, no.
When writing a program (Unix-style), can it address and manage more than one stdout and stdin channels?
No; there is (at most) one standard input and one standard output at any given time. Ultimately, since the question specifically mentions Unix, standard input is file descriptor 0 and standard output is file descriptor 1, and there is only one file descriptor with a given number.
I want to create a socket connected directly to the gpu. I would like to send data from a server to the gpu without spending a copy/moving time from host to device. Is it possible?
If you have suitable network hardware and are willing to write your own device driver for your network adaptor, thenmaybe.SeveralInfiniband and iWARP adapter vendors can have engineered such support for their products. But realistically, no.
How can I stop the execution of a thread until a file is created ?I would like to avoid doing it in a busy loop, and use something with a behavior similar to select(). Is something like this possible?I only found ways to check if a file exists at a given time.
You are probably looking forinotify(7). At the botton of the man page linked, there's example showing how to monitor for various events.
Is there any limit as to how many elements a2D integer arraycan contain inC?PS : I was expecting there would be some space limitations in declaring an array but could not find any such reference in the internet.
It depends on yourRAMor the memory available for you. i:e:My program used to crash when I declared a global arraya[100000][10000], but this declaration is fine with the system now I have.
How can I stop the execution of a thread until a file is created ?I would like to avoid doing it in a busy loop, and use something with a behavior similar to select(). Is something like this possible?I only found ways to check if a file exists at a given time.
You are probably looking forinotify(7). At the botton of the man page linked, there's example showing how to monitor for various events.
Is there any limit as to how many elements a2D integer arraycan contain inC?PS : I was expecting there would be some space limitations in declaring an array but could not find any such reference in the internet.
It depends on yourRAMor the memory available for you. i:e:My program used to crash when I declared a global arraya[100000][10000], but this declaration is fine with the system now I have.
I came across this line of code written in C that confuses me coming from a JavaScript background. ``` short s; if ((s = data[q])) return s; ``` Is this assigningstodata[q], and if it equals true/1, return s?
Yes, an assignment...well assigns...but it's also an expression. Any value not equalling zero will be evaluated as true and zero as false. it would be the same as ``` if ((s = data[q]) != 0) return s; ```
Consider inline assembly like this: ``` uint64_t flags; asm ("pushf\n\tpop %0" : "=rm"(flags) : : /* ??? */); ``` Nonwithstanding the fact that there is probably some kind of intrinsic to get the contents of RFLAGS, how do I indicate to the compiler that my inline assembly clobbers one quadword of memory at the top of stack?
As far as I am concerned, this is currently not possible.
Is ZeroMQ or RabbitMQ asynchronous, even when it is utilized in C programming?
Yes, both ZeroMQ and RabbitMQ support asynchronous modes of operation, and this applies to the C client library implementations for both (as of this writing).
This question already has answers here:C: transitive (double) assignments(6 answers)Closed7 years ago. I came across this code today: ``` for (i = 0; i < level; i++) { a[i] = b[i] = c[i] = 0; } ``` What is the meaning of the code located inside the for loop?
``` a[i] = b[i] = c[i] = 0; ``` is parsed as: ``` a[i] = (b[i] = (c[i] = 0)); ``` and has the same effect as: ``` a[i] = 0; b[i] = 0; c[i] = 0; ```
Can I pass a character array tofopen? For example: ``` fopen(s, "r"); ``` Wheresis declared as a character array and is null terminated.
smust be a pointer to a null terminated character array. Theman pagesconfirm this ``` FILE *fopen(const char *path, const char *mode); ``` You can see that it must be null terminated, since nosizeargument is given.
Is ZeroMQ or RabbitMQ asynchronous, even when it is utilized in C programming?
Yes, both ZeroMQ and RabbitMQ support asynchronous modes of operation, and this applies to the C client library implementations for both (as of this writing).
This question already has answers here:C: transitive (double) assignments(6 answers)Closed7 years ago. I came across this code today: ``` for (i = 0; i < level; i++) { a[i] = b[i] = c[i] = 0; } ``` What is the meaning of the code located inside the for loop?
``` a[i] = b[i] = c[i] = 0; ``` is parsed as: ``` a[i] = (b[i] = (c[i] = 0)); ``` and has the same effect as: ``` a[i] = 0; b[i] = 0; c[i] = 0; ```
Can I pass a character array tofopen? For example: ``` fopen(s, "r"); ``` Wheresis declared as a character array and is null terminated.
smust be a pointer to a null terminated character array. Theman pagesconfirm this ``` FILE *fopen(const char *path, const char *mode); ``` You can see that it must be null terminated, since nosizeargument is given.