question
stringlengths
25
894
answer
stringlengths
4
863
``` int menu(int code) { char item[7][30]={"Lunch/Dinner Set ","Breakfast Set","Kiddies Set", "Promotion","Drink","French Fries","Dessert"}; int code_menu[7]={1,2,3,4,5,6,7}; float price[7]={8.00,5.00,6.00,3.00,2.00,3.00,3.50}; int cnt; printf("\n\tCode\t\tItem\t\t\tPr...
I suspect, you meant: ``` printf("\t%d\t\t%s\t\t\tRM%.2f\n", code_menu[cnt], item[cnt], price[cnt]); ```
When I do my exercise I have a problem to simulate CPU time scheduling in C language that I define CPU as a struct like that ``` struct CPU { int state; // state = 1 : CPU is FREE // state = 0 : CPU is BUSY } ``` Users type the number CPU they want to use for time scheduling ( I call it's CPU...
You need an array ``` struct CPU { int state; // 0: BUSY, 1: FREE }; struct CPU cpu[10]; cpu[0].state = 1; // set cpu[0] as free for (k = 1; k < 10; k++) cpu[k].state = 0; // set others as busy ```
When I insert in my source code the following block of instructions: ``` while(qx < xmin || qx > xmax){ if(qx > xmax) qx = 2 * xmax - qx; if(qx < xmin) qx = 2 * xmin - qx; } ``` the compiler does not return any error, but the execution does not come to an end.qxis a float value,xmaxandxminare...
You should use a debugger or aprintfin the loop body to see what the value of qx is becoming and fix your logic. Since you never told us what you're trying to compute, this is about the only possible answer. One thing it could be is floating point precision. Ifqxis afloat, it has at most 9 digits of precision. So i...
I'm trying to setenv a new environement variable with setenv(). But I noticided that setenv() function set my new environement variable only if I use the environement "extern char **environ" But I want to use the argument of the main() : "char **envp". Here's the code I tried to do for setting in envp, but as you w...
setenv() is documented to not be allowed to change the optionalenvpargument to main. If you need to iterate through all the environment variables, use theextern char **environvariable. See alsothis question.
If on linux I try to compile c code in the standard way ``` gcc -myprog.c ``` the generated binary uses only the base CPU features, since the modern CPUs have a lot of special features to increase the performances, like AVX, AVX2, SSE3, SSE4 etc. according the model Since I want targeting only a specific CPU type (...
Look at the -march and -mtunegcc flags
I wrote a program on C , where a client sent one time some information to a server. I used TCP sockets.And some time the server calculated and should to sent result to the client. How can I detect if connection on The server or the client was broken?
You may want to try TCP keepalives. ``` # cat /proc/sys/net/ipv4/tcp_keepalive_time 7200 # cat /proc/sys/net/ipv4/tcp_keepalive_intvl 75 # cat /proc/sys/net/ipv4/tcp_keepalive_probes 9` ``` In the above example, TCP keep-alive timer kicks in after the idle time of 7200 seconds. If the keep-alive messages...
``` int test = 1; cout << (long *) &test <<endl; //=0x7fff7370cefc cout << (long) test <<endl; //= 1 ``` Can someone explain what is happening in the first case? I get that long > int, thus the jibberish number, but what exactly is happening?
In this case: ``` cout << (long *) &test <<endl; //=0x7fff7370cefc ``` you in fact aregiving the value, of the address oftestvariable, to be converted into a long pointer valueand then printed. Which is exactly what you should get.
Why can the compiler know how much strings there are but not how much chars they contain? For example, this works: ``` char songs[][30]{ "A string", "Another string" }; ``` And this one doesn't: ``` char songs[][]{ "A string", "Another string" }; ```
If you're fine with constant strings, then you don't. ``` const char *strings[] = { "foo", "bar", "baz", "quux", }; ``` The only time when you'd need to give it the length of the strings is if you were trying to make a two dimensional array ofchars, like ``` char strings[][5] = { "foo", "bar...
I am using an Arduino to parse UDP packages sent from an application on my local network. The messages contain 36 bytes of information. The first four bytes represent one (single-precision) float, the next four bytes another one, etc. The Arduino function udp.read() reads the data as chars, and I end up with an array...
You could just read directly into the buffer ``` float data[9]; udp.read((char*)data, sizeof(data)); ```
I know that code will not run but how can i fix this? ( I am new to c) ``` char name[20] printf("Ender the name of text file you want to open ex: word.txt"); scanf("%s", name); ptr = fopen("name", "r"); // There is the problem ```
By callingfopen("name","r"), you are attempting to open a file called "name" for reading. Assuming that you haveFILE* ptrdeclared somewhere up there... Change this: ``` ptr = fopen("name","r"); ``` To this: ``` ptr = fopen(name,"r"); ```
What editon of Visual Studio 2013 do I need to have a native 64-bitcl.exe(amd64one, notx86_amd64)? I am running Windows 7 64-bit with Visual Studio 2013 Express (Windows Desktop Development)
With Visual C++ Express the x64 native compiler is not provided. You need at least the "Professional" edition. http://msdn.microsoft.com/en-us/library/hs24szh9(v=vs.120).aspx Anyhow, you can build 64 bit executables just fine using the x86-x64 cross compiler running on WOW64.
I want to have something like a cross platformsnprintffunction, so I'm trying to use this (perhaps there are other solutions, but I'm wondering exactly that): ``` void string_print(char *str, size_t size, const char *format, ...) { va_list args; va_start(args, format); #ifdef _WIN32 sprintf_s(str, size, f...
You need to use vsnprintf/vsnprintf_s functions with vararg lists. vsnprintf(str, size, format, args);
i have a hex value say for example 0x0a010203 and i want to convert it to a string such that after conversion it should be like "10.1.2.3",How to extract the individual fields from the hex value ?
Fill astruct in_addrand useinet_ntoa()("Internet address to ASCII string"): ``` #include <arpa/inet.h> struct in_addr addr; addr.s_addr = htonl(0x0a010203); // s_addr must be in network byte order char *s = inet_ntoa(addr); // --> "10.1.2.3" ``` Note that the string returned byinet_ntoa()may point to static data t...
What editon of Visual Studio 2013 do I need to have a native 64-bitcl.exe(amd64one, notx86_amd64)? I am running Windows 7 64-bit with Visual Studio 2013 Express (Windows Desktop Development)
With Visual C++ Express the x64 native compiler is not provided. You need at least the "Professional" edition. http://msdn.microsoft.com/en-us/library/hs24szh9(v=vs.120).aspx Anyhow, you can build 64 bit executables just fine using the x86-x64 cross compiler running on WOW64.
I want to have something like a cross platformsnprintffunction, so I'm trying to use this (perhaps there are other solutions, but I'm wondering exactly that): ``` void string_print(char *str, size_t size, const char *format, ...) { va_list args; va_start(args, format); #ifdef _WIN32 sprintf_s(str, size, f...
You need to use vsnprintf/vsnprintf_s functions with vararg lists. vsnprintf(str, size, format, args);
i have a hex value say for example 0x0a010203 and i want to convert it to a string such that after conversion it should be like "10.1.2.3",How to extract the individual fields from the hex value ?
Fill astruct in_addrand useinet_ntoa()("Internet address to ASCII string"): ``` #include <arpa/inet.h> struct in_addr addr; addr.s_addr = htonl(0x0a010203); // s_addr must be in network byte order char *s = inet_ntoa(addr); // --> "10.1.2.3" ``` Note that the string returned byinet_ntoa()may point to static data t...
I am using the following C library file to try and send 9 floating point values over UART:https://github.com/microbuilder/LPC1343CodeBase/blob/master/core/uart/uart.c In following the example in the comments, I came up with the following code: ``` #define UARTBUFFERSIZE 36 float testVals[9] = {0.1, 0.2, 0.3, 0.5, 0...
Just cast it touint8_t*, it is safe. Your size for floats is set correctly 9 floats -> 9 x 4 bytes.
I've seen this definition GCC_UNUSED used in quite a few places (curses, CDK). I tried searching for it but I couldn't find anything. Does anyone know what it means?
Usually it's a macro definition, something like: ``` #ifdef __GNUC__ # define GCC_UNUSED __attribute__((unused)) #else # define GCC_UNUSED #endif ``` Theunusedattribute, attached to a variable, means that the variable is meant to be possibly unused. GCC will not produce a warning for this variable.
This question already has answers here:Difference between static memory allocation and dynamic memory allocation(7 answers)Closed9 years ago. Let's say I declare an array by doing this: ``` int array[] = {1, 2, 3, 4}; ``` By what I understand, you can also create the same array using pointers and malloc: ``` int* ...
The first one resides in the current function's call stack. The second one resides in the heap. The first one goes out of scope when the function returns, the second persists untilfree()is called on the address. More differences, but I defer to the duplicate found by lethal-guitar instead of adding to my answer.
I have two file descriptors created withsocket()and both are connected to separate hosts. I want anything received on the first socket to be immediately sent on the second and vice versa. I know can achieve this manually with a combination ofselect(),send()andrecv(), but is there a more direct way to tell the kernel ...
No. You can use a tool likenetcatwhich does this for you (so you don't have to write the code) but evennetcatcontains a loop that copies the data.
See the following code for example. How can I model different return values of a function in a UML Activity-Diagram? ``` typedef enum {CLOSED, OPEN, UNKNOWN} sw_state_t; sw_state_t read_input(int index) { uint8_t sw_state; if (spi_read(&sw_state) == STATUS_OK) { if (sw_state & (1 << index)) ...
Use a data object, as they are output of activities. Then link the object with the activity Looking at your diagram, just before each relevant ActivityFinal (return OPEN, CLOSED, UNKNOWN) add an action to return the corresponding object the following way. Then connect each object with the OutputParameter.
I was doing some training course, and this question still has my attention. Question: Declare an array of type float named math_constants. The array should be big enough to hold 2 numbers. Why is ``` float math_constants[2]; ``` Correct? And why is ``` float math_constants[1]; ``` Wrong? It might be a newbie...
The number within square brackets is the size of the array, i.e., the number of elements in the array. This is different from the fact that indexing of the elements starts from0.
I am creating n threads. I would like to create n variables b1,b2,b3,.,bi,..bn. How can I do this in C? I mean to choose the name of the global variable according to the number of the thread. thanks
Taken fromNapoleonBlownapart's comment to the OP: "You can't. Variable names only exist at compile time, while threads only exist at runtime." Use an array, with as much elements as you have threads. Then use the thread's number as index to the arrary See some pseudo code below: ``` #define THREAD_MAXIMUM (42) int...
I'm sure this has been asked many times before but this kind of thing is pretty difficult to search for.Say foo and bar are both pointers to separate arrays, what does this line do? ``` *foo++ = *bar++; ``` At what point does each pointer get incremented, and is it an assignment of pointers or values?Thank you
``` *foo++ = *bar++; ``` copies whatbarpoints at over whatfoopoints at. Then it increments both pointers to the next element.
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question appears to be off-topic becauseit lacks sufficient information to diagnose the problem.Describe your problem in more detail orinclude a minimal examplein the question itself.Closed9 years ago.Improve this q...
Left of->should be pointer type, while normal variables/instances for.. If you have astruct foo myFoo, you should usemyFoo.or(&myFoo)->.If you have astruct foo *myFoo, you should usemyFoo->or(*myFoo)..
I am using the following C library file to try and send 9 floating point values over UART:https://github.com/microbuilder/LPC1343CodeBase/blob/master/core/uart/uart.c In following the example in the comments, I came up with the following code: ``` #define UARTBUFFERSIZE 36 float testVals[9] = {0.1, 0.2, 0.3, 0.5, 0...
Just cast it touint8_t*, it is safe. Your size for floats is set correctly 9 floats -> 9 x 4 bytes.
I've seen this definition GCC_UNUSED used in quite a few places (curses, CDK). I tried searching for it but I couldn't find anything. Does anyone know what it means?
Usually it's a macro definition, something like: ``` #ifdef __GNUC__ # define GCC_UNUSED __attribute__((unused)) #else # define GCC_UNUSED #endif ``` Theunusedattribute, attached to a variable, means that the variable is meant to be possibly unused. GCC will not produce a warning for this variable.
This question already has answers here:Difference between static memory allocation and dynamic memory allocation(7 answers)Closed9 years ago. Let's say I declare an array by doing this: ``` int array[] = {1, 2, 3, 4}; ``` By what I understand, you can also create the same array using pointers and malloc: ``` int* ...
The first one resides in the current function's call stack. The second one resides in the heap. The first one goes out of scope when the function returns, the second persists untilfree()is called on the address. More differences, but I defer to the duplicate found by lethal-guitar instead of adding to my answer.
I really searched a lot to find out the answer but didn't find anything. I created a comboboxtext using glade3 and inserted three text values. The comboboxtext is in a form and when the user presses the ok button of the form I want to store in const *char the text value he chose. What is the function that gets the t...
Use ``` gtk_combo_box_text_get_active_text (GtkComboBoxText *cmb); ``` Since you did not set gtk_combo_box_set_active_id(), you cannot pull the active_id. Anyway, the "id" is used if you use GtkTreeModel to fill up the combo box.
I wanted to print\0usingprintf. First I foundprintf("ab\0c")is not right because I can only get "ab". Then I found a way to print "ab\0c" usingprintf("ab\\0c"). But that brings a new problem. What if I want to print"ab\\0c"? I want to print it in only one sentence. Do you have any good way to do this?
Printinga single backslash (as opposed to using it as an escape sequence) needs a double backslash to undo the escaping., so basically If you want to printab\0cyou needprintf("ab\\0c")(2 times 1 is 2)If you want to printab\\0cyou needprintf("ab\\\\0c")(2 times 2 is 4)...
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.Closed9 years ago.Improve this question I am comparing two strings each coming from arrays. ``` while(countX<10){ if(strcmp(scanWord[countX], ...
When you're reading the line, remove the newline: ``` char *line = fgets(currentWord[countX], 20, stdin); if (line) { int len = strlen(line); if (line[len-1] == '\n') { line[len-1] = 0; } } ```
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question appears to be off-topic becauseit lacks sufficient information to diagnose the problem.Describe your problem in more detail orinclude a minimal examplein the question itself.Closed9 years ago.Improve this q...
Try using #ifdef. For example: ``` #ifdef __CYGWIN__ // Cygwin specific code #else // Other code #endif ```
I wanted to print\0usingprintf. First I foundprintf("ab\0c")is not right because I can only get "ab". Then I found a way to print "ab\0c" usingprintf("ab\\0c"). But that brings a new problem. What if I want to print"ab\\0c"? I want to print it in only one sentence. Do you have any good way to do this?
Printinga single backslash (as opposed to using it as an escape sequence) needs a double backslash to undo the escaping., so basically If you want to printab\0cyou needprintf("ab\\0c")(2 times 1 is 2)If you want to printab\\0cyou needprintf("ab\\\\0c")(2 times 2 is 4)...
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.Closed9 years ago.Improve this question I am comparing two strings each coming from arrays. ``` while(countX<10){ if(strcmp(scanWord[countX], ...
When you're reading the line, remove the newline: ``` char *line = fgets(currentWord[countX], 20, stdin); if (line) { int len = strlen(line); if (line[len-1] == '\n') { line[len-1] = 0; } } ```
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question appears to be off-topic becauseit lacks sufficient information to diagnose the problem.Describe your problem in more detail orinclude a minimal examplein the question itself.Closed9 years ago.Improve this q...
Try using #ifdef. For example: ``` #ifdef __CYGWIN__ // Cygwin specific code #else // Other code #endif ```
I searched about this but I didn't find a clear answer for this problem in C language. Imagine that I have anint a = 123and anotherint b = 456. How do I combine them in order to getcombine(a, b) == 123456?
You can multiplyaby 10-to-the-power-of-N, where N is the number of digits inb, then add that number tob. Less efficiently, you can convert both to strings, concatenate them, then parse that string into an integer. In either case, there is a possibility of integer overflow. Ifbis allowed to be negative, you will hav...
I know that I can use ``` scanf("%d %d %d",&a,&b,&c): ``` But what if the user first determines how many input there'd be in the line?
You are reading the number of inputs and then repeatedly (in a loop) read each input, eg: ``` #include <stdio.h> #include <stdlib.h> int main(int ac, char **av) { int numInputs; int *input; printf("Total number of inputs: "); scanf("%d", &numInputs); input = malloc(numInputs...
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.Closed9 years ago.Improve this question I came across this piece of code, but am not able to entirely make sense of it: ``` (((x)[y] << 8) | (x)[(...
It extracts the 16-bit big-endian value starting at indexyfrom arrayx.
I tried to implement the following calculation: ``` #include <stdio.h> #include <math.h> int main(){ float sum = 0; int c = -4; float x1 = 136.67; float x2 = 2.38; sum = c / (pow(abs(x1 - x2), 2)); printf("%f %f %f",sum,x1,x2); return 0; } ``` But the value ofsumafter the execution tu...
absis declared in<stdlib.h>. It takes anintargument and returns anintresult. The missing#include <stdlib.h>is likely to cause problems as well. You're callingabswith a floating-point argument; without a visible declaration, the compiler will probably assume that it takes adoubleargument, resulting in incorrect code. ...
I'm trying to create a database with a table using sqlite3 on my C program, however the database is always created as empty, though it was created non-empty using the sqlite shell, here is my code below: ``` int main(void) { printf("hello\n"); sqlite3 *sqdb; sqlite3_initialize(); const char* db = "te...
sqlite3_prepare_v2()alone just compiles the SQL but does not run it. Callsqlite3_step()on the compiled statement to run it, or usesqlite3_exec()that combines prepare+step+finalize into one function call.
I know that I can use ``` scanf("%d %d %d",&a,&b,&c): ``` But what if the user first determines how many input there'd be in the line?
You are reading the number of inputs and then repeatedly (in a loop) read each input, eg: ``` #include <stdio.h> #include <stdlib.h> int main(int ac, char **av) { int numInputs; int *input; printf("Total number of inputs: "); scanf("%d", &numInputs); input = malloc(numInputs...
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.Closed9 years ago.Improve this question I came across this piece of code, but am not able to entirely make sense of it: ``` (((x)[y] << 8) | (x)[(...
It extracts the 16-bit big-endian value starting at indexyfrom arrayx.
I tried to implement the following calculation: ``` #include <stdio.h> #include <math.h> int main(){ float sum = 0; int c = -4; float x1 = 136.67; float x2 = 2.38; sum = c / (pow(abs(x1 - x2), 2)); printf("%f %f %f",sum,x1,x2); return 0; } ``` But the value ofsumafter the execution tu...
absis declared in<stdlib.h>. It takes anintargument and returns anintresult. The missing#include <stdlib.h>is likely to cause problems as well. You're callingabswith a floating-point argument; without a visible declaration, the compiler will probably assume that it takes adoubleargument, resulting in incorrect code. ...
I'm trying to create a database with a table using sqlite3 on my C program, however the database is always created as empty, though it was created non-empty using the sqlite shell, here is my code below: ``` int main(void) { printf("hello\n"); sqlite3 *sqdb; sqlite3_initialize(); const char* db = "te...
sqlite3_prepare_v2()alone just compiles the SQL but does not run it. Callsqlite3_step()on the compiled statement to run it, or usesqlite3_exec()that combines prepare+step+finalize into one function call.
I converted my C++ dll to C dll: ``` #ifdef __cplusplus extern "C" { #endif MY_EXPORT int my_func(); MY_EXPORT void my_func(int n); #ifdef __cplusplus } #endif ``` Everything worked fine withoutextern Cdeclaration. With this declaration I got error C2733: second C linkage of overloaded function 'my_func'...
C does not allow to overload functions. That is C does not support overloading. It is a feature of C++.
I got this code that works for the left mouse click on a button but how would I use to get the right mouse click signal: ``` g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(button-action), NULL); ```
A simple way to listen foranymouse clicks, be it left or right would be this: ``` g_signal_connect( G_OBJECT(button) "button-press-event", G_CALLBACK(btn_press_callback), NULL ); ``` Then, for the callback function: ``` gboolean btn_press_callback(GtkWidget *btn, GdkEventButton *event, gpointer user...
A message like this appears, when i run this code. Project.exe has stopped working Some of my other code works, but this seems to throw me an error. ``` #include<stdio.h> #include<conio.h> void main() { int n1, n2, sum; puts("first number"); scanf("%d", n1); fflush(stdin); puts("second number...
scanftakes the address of the variable in which it stores the input value. You need to change yourscanfcalls to ``` scanf("%d", &n1); scanf("%d", &n2); // ^ note the & operator ``` Also, note that it's undefined behaviour to callfflushon an input stream. So,fflush(stdin)is not correct. You need to manually ...
I have to program a shell in C and need to handle globing in it and I am only allowed to use the function glob. But when I try to use it, it only gives me one result back. ``` #include <glob.h> #include <stdlib.h> int main(int ac, char **av) { glob_t s; unsigned long i = -1; if (glob(av[1], 0, NULL, &...
In the command line ``` ./a.out *.c ``` the shell expands the glob pattern, so your program sees ``` {"./a.out", "replace_glob.c", "test.c", NULL} ``` as itsargv. You need to quote the pattern for the program to see it: ``` ./a.out '*.c' ```
I want to change main so that it calls one function before doing anything else. So I written code like this ``` #include <stdio.h> void test() { printf("\nTEST\n"); #undef main main(1,NULL); } int main(int argc, char** argv) { printf("\nHello World\n"); } ``` and compiled it like ``` cc -g -Dmain=test...
If you want call other function, before main, gcc provides__attribute__ for example: ``` int test(void) __attribute__ ((constructor)); int test() { printf("\nTEST\n"); return 0; } int main(int argc, char** argv) { printf("\nHello World\n"); return 0; } ```
Is it possible to usechdir()or some other command to change the directory in a thread without affecting the cwd of the other threads ? I'm usingpthread.h. *I'm trying to write a server program that handles multiple client connections and requests. One of the available commands to the client is the'cd'command.
No, as mentioned by others the current working directory is a per-process property, not per-thread. You can "emulate" a per-thread (or per client, or however you structure your application) current working directory by storing a file descriptor for the "per-thread CWD" and the using the various *at() syscalls specifie...
I need to use make-3.8.2 version for compiling code. I have modified makefile in following way. ``` export PATH := /home/make-3.82/bin:$(PATH) ``` I am able to change PATH variable But it Invoke current make version which is make-3.7.6. if I set manually in terminal than it's work fine which is also correct as it t...
I have doing following way in makefile. ``` ifneq ($(MAKE_VERSION), 3.82) $(error Please add /home/make-3.82/bin in PATH enviroment and re run) endif ```
I have the following asm code that gets linked into my cpp project: ``` Some_Variable EQU 0x0F00F0F0 ... ``` Now I would like to access Some_Variable from C code. I was not lucky withextern uint32_t Some_Variable. How do you exactly do this? Is this even possible?
One way to do this is indeed using variable that has constant value assigned to it. Not sure about your assembler but for nasm you can do the following: ``` Some_Variable equ 0x0F00F0F0 global _somevar _somevar dd Some_Variable ``` And then in C: ``` extern int somevar ``` Most assemblers have similar keywords so...
I have a text file. I am writing a program to read from the file usingfgetcand put in a two dimensional buffer. After printing the contents of file, it's printing some junk until end of buffer despite having put the check for EOF and ERROR as shown below. How can I get it done? ``` unsigned char ch; while(ch=fge...
EOFis an Integer with the value-1. When you doch=fgetc(fp)in the while loop, you read into anunsigned char, that can by definition not be signed, so it can't be equal to-1. A solution could be to read into an integer and to cast it after having checked forEOF. ``` int ch; while(ch=fgetc(fp)) { if(ch == EOF) b...
I have question about the EPOCH time. I need to calculate the time difference between two packets. and I am not so sure how: ``` printf("Epoch Time: %d:%d seconds\n", header->ts.tv_sec, header->ts.tv_usec); the first packet shows: 1396191661:164162 the second packet shows: 1396191661:164193 ``` I need that varia...
Just add the difference between seconds: ``` udiff = (second.tv_sec - first.tv_sec) * 1000000 + (second.tv_usec - first.tv_usec) ``` You just have to check that the difference between two packets is less than ~2000 seconds to stay in the size of a 32-bitsint.
Is there a way to find the packed size of a structure defined and declared without packed attribute in GCC compiler? Example: ``` struct Name { int a; char ch; } ``` any function or macro likeget_packed_size(Name)should return 5
Define your struct using a macro that provides the required information. For example (though there are other possible implementations): ``` #define DEFINE_STRUCT_WITH_KNOWN_PACKED_SIZE(StructName, StructBody)\ struct StructName StructBody\ struct __attribute__ ((__packed__)) StructName##_packed StructBody #define GE...
A message like this appears, when i run this code. Project.exe has stopped working Some of my other code works, but this seems to throw me an error. ``` #include<stdio.h> #include<conio.h> void main() { int n1, n2, sum; puts("first number"); scanf("%d", n1); fflush(stdin); puts("second number...
scanftakes the address of the variable in which it stores the input value. You need to change yourscanfcalls to ``` scanf("%d", &n1); scanf("%d", &n2); // ^ note the & operator ``` Also, note that it's undefined behaviour to callfflushon an input stream. So,fflush(stdin)is not correct. You need to manually ...
I have to program a shell in C and need to handle globing in it and I am only allowed to use the function glob. But when I try to use it, it only gives me one result back. ``` #include <glob.h> #include <stdlib.h> int main(int ac, char **av) { glob_t s; unsigned long i = -1; if (glob(av[1], 0, NULL, &...
In the command line ``` ./a.out *.c ``` the shell expands the glob pattern, so your program sees ``` {"./a.out", "replace_glob.c", "test.c", NULL} ``` as itsargv. You need to quote the pattern for the program to see it: ``` ./a.out '*.c' ```
I want to change main so that it calls one function before doing anything else. So I written code like this ``` #include <stdio.h> void test() { printf("\nTEST\n"); #undef main main(1,NULL); } int main(int argc, char** argv) { printf("\nHello World\n"); } ``` and compiled it like ``` cc -g -Dmain=test...
If you want call other function, before main, gcc provides__attribute__ for example: ``` int test(void) __attribute__ ((constructor)); int test() { printf("\nTEST\n"); return 0; } int main(int argc, char** argv) { printf("\nHello World\n"); return 0; } ```
Is it possible to usechdir()or some other command to change the directory in a thread without affecting the cwd of the other threads ? I'm usingpthread.h. *I'm trying to write a server program that handles multiple client connections and requests. One of the available commands to the client is the'cd'command.
No, as mentioned by others the current working directory is a per-process property, not per-thread. You can "emulate" a per-thread (or per client, or however you structure your application) current working directory by storing a file descriptor for the "per-thread CWD" and the using the various *at() syscalls specifie...
I need to use make-3.8.2 version for compiling code. I have modified makefile in following way. ``` export PATH := /home/make-3.82/bin:$(PATH) ``` I am able to change PATH variable But it Invoke current make version which is make-3.7.6. if I set manually in terminal than it's work fine which is also correct as it t...
I have doing following way in makefile. ``` ifneq ($(MAKE_VERSION), 3.82) $(error Please add /home/make-3.82/bin in PATH enviroment and re run) endif ```
I have the following asm code that gets linked into my cpp project: ``` Some_Variable EQU 0x0F00F0F0 ... ``` Now I would like to access Some_Variable from C code. I was not lucky withextern uint32_t Some_Variable. How do you exactly do this? Is this even possible?
One way to do this is indeed using variable that has constant value assigned to it. Not sure about your assembler but for nasm you can do the following: ``` Some_Variable equ 0x0F00F0F0 global _somevar _somevar dd Some_Variable ``` And then in C: ``` extern int somevar ``` Most assemblers have similar keywords so...
I have a text file. I am writing a program to read from the file usingfgetcand put in a two dimensional buffer. After printing the contents of file, it's printing some junk until end of buffer despite having put the check for EOF and ERROR as shown below. How can I get it done? ``` unsigned char ch; while(ch=fge...
EOFis an Integer with the value-1. When you doch=fgetc(fp)in the while loop, you read into anunsigned char, that can by definition not be signed, so it can't be equal to-1. A solution could be to read into an integer and to cast it after having checked forEOF. ``` int ch; while(ch=fgetc(fp)) { if(ch == EOF) b...
I have question about the EPOCH time. I need to calculate the time difference between two packets. and I am not so sure how: ``` printf("Epoch Time: %d:%d seconds\n", header->ts.tv_sec, header->ts.tv_usec); the first packet shows: 1396191661:164162 the second packet shows: 1396191661:164193 ``` I need that varia...
Just add the difference between seconds: ``` udiff = (second.tv_sec - first.tv_sec) * 1000000 + (second.tv_usec - first.tv_usec) ``` You just have to check that the difference between two packets is less than ~2000 seconds to stay in the size of a 32-bitsint.
Is there a way to find the packed size of a structure defined and declared without packed attribute in GCC compiler? Example: ``` struct Name { int a; char ch; } ``` any function or macro likeget_packed_size(Name)should return 5
Define your struct using a macro that provides the required information. For example (though there are other possible implementations): ``` #define DEFINE_STRUCT_WITH_KNOWN_PACKED_SIZE(StructName, StructBody)\ struct StructName StructBody\ struct __attribute__ ((__packed__)) StructName##_packed StructBody #define GE...
If I am given a char array of size 8, where I know the the first 3 bytes are the id, the next byte is the message, and the last 3 bytes are the values. How could I use bit manipulation in order to extract the message. Example: a char array contains 9990111 (one integer per position), where 999 is the id, 0 is the mes...
Given: the array contains {'9','9','9','0','1','1','1'} Then you can convert withsscanf(): ``` char buffer[8] = { '9', '9', '9', '0', '1', '1', '1', '\0' }; //char buffer[] = "9990111"; // More conventional but equivalent notation int id; int message; int value; if (sscanf(buffer, "%3d%1d%3d", &id, &message, &val...
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.Closed9 years ago.Improve this question I can't find out the problem, it doesn't give me the right answer, for example: I put 1234567890, it gives ...
The basic problem is that you do not initialize the array before counting digits. ``` int m[10] = {0}; ``` Also you should handle non digit values so that the program doesn't crash e.g. ``` while((n=getchar())!='\n') { if ( isdigit(n) ) { ++m[n-'0']; } } ``` ( isdigit() is available if you include ctype....
I have a program that grabs a user input number and adds the appropriate ending (1st, 11th, 312th, etc) So I gave it to my friend to find bugs/ break it. The code is ``` int number; printf("\n\nNumber to end?: "); scanf("%d",&number); getchar(); numberEnder(number); ``` when 098856854345712355 was i...
INT_MAX is typically (2^31) -1 which is ~2 billion... ... if you look at98856854345712355 & 0xffffffffyou will find that it is 115573475
I'm working on a C project. My project is to create a binary tree, this is my struct: ``` struct Node { char * word; int count; struct Node* left; struct Node* right; }; ``` My question is how to print the struct, do I useprintf()for each one of the field or there is a way to create atoString()method like in...
No real magic: ``` struct Node node = {"Adam", 1, NULL, NULL}; struct Node *nodePtr = &node; printf("word[%s] count[%d] left[%p] right[%p]\n", node.word, node.count, node.left, node.right); printf("word[%s] count[%d] left[%p] right[%p]\n", nodePtr->word, nodePtr->count, nodePtr->left, nodePtr->right); ```
``` int (*ptr)(); ``` Can someone ELI5 what this code snippet does? I find it almost impossible to visually or logically make sense of it. Also how and when is it used?
It's a pointer, named ptr, to a function that returns an int and takes no arguments (i.e.,int ()). The syntax isn't beautiful, but it's like a function signature, except the second part identifies that this is a pointer to such a function, with a certain name (ptr in this case). This tutorialmight be of help in unde...
In other words, sets the last 5 bits of integer variable x to zero, also it must be in a portable form. I was trying to do it with the << operator but that only moves the bits to the left, rather than changing the last 5 bits to zero. 11001011 should be changed to 11000000
Create a mask that blanks out that lastnintegers if it is bitwise-ANDed with your int: ``` x &= ~ ((1 << n) - 1); ``` The expression1 << nshifts 1 bynplaces and is effectively two to the power ofn. So for 5, you get 32 or0x00000020. Subtract one and you get a number that as thenlowest bits set, in your case0x0000001...
Using ``` gcc -m32 myprog.c ``` should compile in 32 bit version the filemyprog.c. Unfortunately I get this error: ``` In file included from /usr/include/stdio.h:27:0, from myprog.c:1: /usr/include/features.h:374:25: fatal error: sys/cdefs.h: No such file or directory #include <sys/cdefs.h> ``` H...
To compile 32 bit binaries on 64 bit Linux version, you have to Installlibx32gccdevelopment package and 32 bit GNU C Library try this ``` sudo apt-get install libx32gcc-4.8-dev ``` and ``` sudo apt-get install libc6-dev-i386 ```
I am trying to read the contents of a file as below: ``` int frameFD = 0; int readResult; char buff[BUFFER_SIZE]; frameFD = open(MY_FILE, O_RDWR); readResult = read(MY_FILE, buff, BUFFER_SIZE); ``` theBUFFER_SIZEis 256. I am getting an error saying 'error: invalid conversion from 'const char*' to 'i...
read() uses the file descriptor, not the file name: readResult = read(frameFD , buff, BUFFER_SIZE);
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.Closed9 years ago.Improve this question I require to convert strings to decimals in C. The strings are of the form -0.841986 and 60.751800. Would ...
Have a look at the functionsstrtod()(converting a C string to adouble),strtof(converting a C string tofloat) andstrtold()(converting a C string to along double)
In my program I see some resident size increase. I suppose it is because of heap fragmentation. So I am planning to use#pragma pack 1. Will it reduce the heap fragmentation? Will it be having some other overheads? Shall I go for it or not?
There is a well proved technique calledMemory pools. It is designed especially to reduce memory fragmentation and help with memory leaks. And it should be used in case where memory fragmentation became the bottleneck of the program functionality. 'pragma pack 1' isn't helpful to avoid heap fragmentation. 'pragma pac...
i have a question: exists any system call for generate a core dump? I know which a core dump could be generated by a signal, but i want know if it's possible generated from system call
``` void createdump(void) { if(!fork()) { //child process // Crash the app abort() || (*((void*)0) = 42); } } ``` What ever place you wan't to dump call the function. This will create a child and crash it. So you can get dump even without exiting your program
Here is a sample code: ``` #include <stdio.h> int main() { int n = 5; float v[n]; float sum; int i; for(i = 0; i < n; i++) { v[i] = i + 1; printf("v[%d]=%f\n", i, v[i]); } for(i = 0; i < n; i++) { sum += v[i]; //uninitialized using } printf("sum=%f\n", s...
Use the -O (optimize) option; value tracking is only performed on optimized code. ``` $ gcc -Wall -O x.c x.c: In function ‘main’: x.c:15: warning: ‘sum’ is used uninitialized in this function ```
Is it possible to programatically print out stack trace of all running threads without attaching GDB? The application is running on an embedded system with Linux. I've found avery similar threadbut the solution uses a special GDB command.
This has been solved with the help ofthis threadandthis thread. Quoting: Signal Handling with the help of backtrace can solve your purpose.I mean if you have a PID of the Thread, you can raise a signal for that thread. and in the handler you can use the backtrace. since the handler would be executing in that par...
This question already has an answer here:Segmentation Fault, large arrays(1 answer)Closed9 years ago. in my C program, when I am taking an array like this ``` int a[100000][100000]; ``` I am getting segmentation fault. Now if I am using array of size less than 1000 * 1000 , like this ``` int a[1000][1000]; ``` I ...
Dynamically allocate it withmalloc. By declaring it statically you use the stack, which has a maximum size that the heap (used in dynamic allocations) does not. ``` int *pointer = malloc (sizeof (*pointer) * (100000*100000)); ``` Then, to access it, use indices to represent thexandycoordinates.
Consider I have the following structure: ``` struct BigStruct { char data1[999]; char data2[999]; ... char dataN[999]; } ``` and somewhere in the code I have a non-static variable of the type with initialization: ``` struct BigStruct foo = { .data1 = {0}, .data2 = {0}, ... .dataN = {0}, } ``` Looks li...
It depends on your software architecture and your target. If you are writing kernel code you don't want to use a lot of stack space;Linux kernel stacks are small. User programs often have a 1 Mb or larger stack, so unless you have a lot of recursive routines, allocating a couple of kB on the stack usually isn't a pr...
Hello the problem I am having with this question is making a function that uses only the binary tree head pointer and the desired level(height) of the tree, something like: ``` int countLevel(tree_type tree, int n) ``` I've been thinking about it for some time now and I can't seem to find a solution without having t...
Something like this should work, assuming tree_type is a node pointer: ``` int countLevel(tree_type tree, int n) { if (tree == 0) return 0; if (n == 0) return 1; return countlevel(tree->left, n - 1) + countlevel(tree->right, n - 1); } ```
Suppose that there are three lines in a header file such as: ``` #define line1 #define line2 #define line3 ``` I would like to be sure that line1 should be defined when all of the lines are commented. I also would like to know any two or three lines should not be active (not commented) at the same time. For example ...
Make sureline1is defined when nothing else is: ``` #if !defined(line1) && !defined(line2) && !defined(line3) #define line1 #endif ``` Generate an error if more than one line is defined: ``` #if (defined(line1) && defined(line2)) || (defined(line1) && defined(line3)) || (defined(line2) && defined(line3)) #error "You...
``` int ar[] = { 1, 2, 3, }; ``` Is this code legal? (My intention is that) ``` int ar[] = { 1, 2, 3 }; ```
Yes, stray commas are allowed in initializer lists in both C89 and GNU89. Quite useful in macros that take optional/variadic parameters. See section 3.5.7 in theANSI C standardfor where this is defined. ``` 3.5.7 Initialization Syntax initializer: assignment-expression { initiali...
I have a 8 bytes integer buffer carrying data bytes, and a 32 bytes variable to save these data. How can I swap data bytes to variable except use pointer? (use pointer will case some unknown issue). Ex. ``` buffer[0] = 0; buffer[1] = 1; buffer[2] = 2; buffer[3] = 3; ``` How to shiftbuffer[0]to variable bit[31:24],b...
``` uint32_t variable; buffer[0] = 0; buffer[1] = 1; buffer[2] = 2; buffer[3] = 3; variable = ((buffer[0] << 24)| (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]); ``` When I used a 32bit varible the data type declearation i used was uint32_t ,please make sure that you use it otherwise use your declarations for uint...
Here is a sample code: ``` #include <stdio.h> int main() { int n = 5; float v[n]; float sum; int i; for(i = 0; i < n; i++) { v[i] = i + 1; printf("v[%d]=%f\n", i, v[i]); } for(i = 0; i < n; i++) { sum += v[i]; //uninitialized using } printf("sum=%f\n", s...
Use the -O (optimize) option; value tracking is only performed on optimized code. ``` $ gcc -Wall -O x.c x.c: In function ‘main’: x.c:15: warning: ‘sum’ is used uninitialized in this function ```
Is it possible to programatically print out stack trace of all running threads without attaching GDB? The application is running on an embedded system with Linux. I've found avery similar threadbut the solution uses a special GDB command.
This has been solved with the help ofthis threadandthis thread. Quoting: Signal Handling with the help of backtrace can solve your purpose.I mean if you have a PID of the Thread, you can raise a signal for that thread. and in the handler you can use the backtrace. since the handler would be executing in that par...
This question already has an answer here:Segmentation Fault, large arrays(1 answer)Closed9 years ago. in my C program, when I am taking an array like this ``` int a[100000][100000]; ``` I am getting segmentation fault. Now if I am using array of size less than 1000 * 1000 , like this ``` int a[1000][1000]; ``` I ...
Dynamically allocate it withmalloc. By declaring it statically you use the stack, which has a maximum size that the heap (used in dynamic allocations) does not. ``` int *pointer = malloc (sizeof (*pointer) * (100000*100000)); ``` Then, to access it, use indices to represent thexandycoordinates.
Consider I have the following structure: ``` struct BigStruct { char data1[999]; char data2[999]; ... char dataN[999]; } ``` and somewhere in the code I have a non-static variable of the type with initialization: ``` struct BigStruct foo = { .data1 = {0}, .data2 = {0}, ... .dataN = {0}, } ``` Looks li...
It depends on your software architecture and your target. If you are writing kernel code you don't want to use a lot of stack space;Linux kernel stacks are small. User programs often have a 1 Mb or larger stack, so unless you have a lot of recursive routines, allocating a couple of kB on the stack usually isn't a pr...
Hello the problem I am having with this question is making a function that uses only the binary tree head pointer and the desired level(height) of the tree, something like: ``` int countLevel(tree_type tree, int n) ``` I've been thinking about it for some time now and I can't seem to find a solution without having t...
Something like this should work, assuming tree_type is a node pointer: ``` int countLevel(tree_type tree, int n) { if (tree == 0) return 0; if (n == 0) return 1; return countlevel(tree->left, n - 1) + countlevel(tree->right, n - 1); } ```
Suppose that there are three lines in a header file such as: ``` #define line1 #define line2 #define line3 ``` I would like to be sure that line1 should be defined when all of the lines are commented. I also would like to know any two or three lines should not be active (not commented) at the same time. For example ...
Make sureline1is defined when nothing else is: ``` #if !defined(line1) && !defined(line2) && !defined(line3) #define line1 #endif ``` Generate an error if more than one line is defined: ``` #if (defined(line1) && defined(line2)) || (defined(line1) && defined(line3)) || (defined(line2) && defined(line3)) #error "You...
``` int ar[] = { 1, 2, 3, }; ``` Is this code legal? (My intention is that) ``` int ar[] = { 1, 2, 3 }; ```
Yes, stray commas are allowed in initializer lists in both C89 and GNU89. Quite useful in macros that take optional/variadic parameters. See section 3.5.7 in theANSI C standardfor where this is defined. ``` 3.5.7 Initialization Syntax initializer: assignment-expression { initiali...
I have a 8 bytes integer buffer carrying data bytes, and a 32 bytes variable to save these data. How can I swap data bytes to variable except use pointer? (use pointer will case some unknown issue). Ex. ``` buffer[0] = 0; buffer[1] = 1; buffer[2] = 2; buffer[3] = 3; ``` How to shiftbuffer[0]to variable bit[31:24],b...
``` uint32_t variable; buffer[0] = 0; buffer[1] = 1; buffer[2] = 2; buffer[3] = 3; variable = ((buffer[0] << 24)| (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]); ``` When I used a 32bit varible the data type declearation i used was uint32_t ,please make sure that you use it otherwise use your declarations for uint...
I am using fputc (in C/C++) to output some data into a file, and the file size matters to me in my project. But the size of resutling file seems incorrect, a simple code example: ``` FILE *fp = fopen( "123.txt", "w" ); for( int i=0; i<64; i++ ) fputc( i, fp ); fclose( fp ); ``` After excuting this code, the file...
I'd guess you're doing this on Windows. Since you opened the file in translated (text) mode, new-lines are converted to a carriage-return/line-feed pairs. The character code 10 happens to be treated as a new-line, so you end up with an extra byte compared to what you wrote. If you open the file in binary mode instea...
This question already has an answer here:fgets prompt limited to 1024 Bytes(1 answer)Closed7 years ago. I want to read from user's input string of size 16000bytes.fgetsonly reads 1024 bytes. What can I use instead? I am writing in c and this is my code right now. Is it that I am not using malloc? ``` char str[16392...
Do not replacefgets()with a worse option.fgets()has no limit. ``` #include <stdio.h> #include <stdlib.h> char *buffer; size_t size; size = 10000000; /* 10m */ buffer = malloc(size); if (!buffer) /* error */; if (fgets(buffer, size, stdin) == NULL) /* error */; // ... free(buffer); ```...
I solved a synchron. project in C by threads (using pthread.h), but I found out I need to do it with processes. Is that going to be difficult to redo? I have approx. 4 hours, should I even try? I don't know much about processes.
This depends on the problem and how you communicate between the threads. If the threads are independent and don't require any communication, you can just use processes instead of threads. If there is a lot of communication and locking, it will be more difficult, of course. Then you must look intoInter-process communi...
I'm playing around with binary files inC, and I can't work out one thing - why does the file end in this byte00001010(that equals a 10)? My code is in essence the following (simplified). ``` FILE *test = fopen("file.b", "ab"); int value = 1; fwrite(&value, sizeof(int), 1, test); fclose(test); ``` After running the ...
10 is a newline. vim automatically appends a newline (if the file didn't end in a newline) when you filter it through xxd. Since you are treating it as a binary file you should tell vim it is a binary file withvim -bso the newline isn't added automatically. Take a look at:h binary
Say I have a program like this: ``` int main(int argc, char **argv){ printf("The name of the program is %s, and the string passed is:\n %s \n\n", argv[0], argv[1]); return 0; } ``` I realize there should be error checking and whatnot, but what I'd really like to know is how to pass a whole string as the firs...
Just use quotes ``` ./file_name "This is the long string argument that comes in argv[1]" | | +--- argv[0] ``` Edit: aruisdante:single and double quotes are treated depending on the shell, double quotes might do unexpected things PS: My answer comes from Windows platform, where use of single quote,...
This question already has answers here:What does the question mark character ('?') mean?(8 answers)Closed9 years ago. Can someone help me to understand how this line work ? I know what it do but the '?' and ':' are not clear for me.. ``` C code: (buff[i - 1] == '\n') ? my_printf("%s", buff) : my_printf("%s\n", buff...
It means: If first part is true, do the second part or else do the third part. In your case, if last character of buff (buff[i-1]) is equal with end line ('\n'), print the buff. But if buff doesn't end with end line ('\n'), you print buff and then end line ("%s\n")
I solved a synchron. project in C by threads (using pthread.h), but I found out I need to do it with processes. Is that going to be difficult to redo? I have approx. 4 hours, should I even try? I don't know much about processes.
This depends on the problem and how you communicate between the threads. If the threads are independent and don't require any communication, you can just use processes instead of threads. If there is a lot of communication and locking, it will be more difficult, of course. Then you must look intoInter-process communi...
I'm playing around with binary files inC, and I can't work out one thing - why does the file end in this byte00001010(that equals a 10)? My code is in essence the following (simplified). ``` FILE *test = fopen("file.b", "ab"); int value = 1; fwrite(&value, sizeof(int), 1, test); fclose(test); ``` After running the ...
10 is a newline. vim automatically appends a newline (if the file didn't end in a newline) when you filter it through xxd. Since you are treating it as a binary file you should tell vim it is a binary file withvim -bso the newline isn't added automatically. Take a look at:h binary
Say I have a program like this: ``` int main(int argc, char **argv){ printf("The name of the program is %s, and the string passed is:\n %s \n\n", argv[0], argv[1]); return 0; } ``` I realize there should be error checking and whatnot, but what I'd really like to know is how to pass a whole string as the firs...
Just use quotes ``` ./file_name "This is the long string argument that comes in argv[1]" | | +--- argv[0] ``` Edit: aruisdante:single and double quotes are treated depending on the shell, double quotes might do unexpected things PS: My answer comes from Windows platform, where use of single quote,...