question
stringlengths
25
894
answer
stringlengths
4
863
I tried the following code in gcc: ``` #include<stdio.h> int main() { int a=3,2,1;//////////////////////ERROR!////////////////////////// printf("%d", a); return 0; } ``` I expected it to compile successfully as: a series of integer expressions seperated by commas will be evaluated from left to right and...
That's parsed as a three-part variable declaration, with two invalid variables. You need to wrap the entire initializer in parentheses so that it's parsed as a single expression: ``` int a=(3,2,1); ```
I am trying to convertASCIIhexadecimal value (0x61 or 61) to it'scharvalue (61 = a, etc..)withoutatoi,scanf,strcat. I am savinggetchar()to temp variable, then I save first one (6) in array, then save second one (1) in array, now i want take these two and convert them to their ASCII value. ``` 68656c6c6f0d0a = hello ...
Not sure exactly what you are trying to do but this may help. ``` int main(int argc, char **argv) { int hex[6] = {0x68, 0x65, 0x6C, 0x6C, 0x6F}; int i = 0; for(i = 0; i <6; i++) { printf("%c", hex[i]); } printf("\n"); } ```
I made this piece of code written in C which takes too long to run. Is there any way to improve it? What i want to do is to sum the values of each row and save the value in a vector. In this code, i1 is the value containing the row locations of a matrix, the columns and the associated value. i1 is not sorted. ``` wh...
Asb = a + const, you could simply usediag[i1[c][0] + const] += i1[c][2]and reduce the complexity from O(N2) to O(N).
Here is an example: ``` #define get_i() i int i; int i2; ``` i2 = get_i(); In the case above ^^^get_i()acts like a function that returns something(the value ofiin this case). ``` #define set_i(value) do{i = (value);}while(0) set_i(i2); ``` This ^^^ above acts like a function that DO NOT return. My question is, ...
You can use comma operator for that. The value of the last operand will be the value of an entire expression. ``` #define increse_i2_and_return_i() (i2++, i) ``` The downside of this trick is that you can't create temporary variables in a such macro.
Currently i have validation on my text area which does not allow new lines being entered. It looks like this in the umbraco validation field: ^.{1,3000}$ Any ideas on how to allow new lines and line breaks ?
That regular expression basically says allow ANY character EXCEPT line breaks, between 1 and 3000 times. If you change it to: ``` ^[\s\S]{1,3000}$ ``` It should allow ANY character, including line breaks. The new version says match any character that is either whitespace, or not whitespace, which is effectively any ...
Here is an example: ``` #define get_i() i int i; int i2; ``` i2 = get_i(); In the case above ^^^get_i()acts like a function that returns something(the value ofiin this case). ``` #define set_i(value) do{i = (value);}while(0) set_i(i2); ``` This ^^^ above acts like a function that DO NOT return. My question is, ...
You can use comma operator for that. The value of the last operand will be the value of an entire expression. ``` #define increse_i2_and_return_i() (i2++, i) ``` The downside of this trick is that you can't create temporary variables in a such macro.
Currently i have validation on my text area which does not allow new lines being entered. It looks like this in the umbraco validation field: ^.{1,3000}$ Any ideas on how to allow new lines and line breaks ?
That regular expression basically says allow ANY character EXCEPT line breaks, between 1 and 3000 times. If you change it to: ``` ^[\s\S]{1,3000}$ ``` It should allow ANY character, including line breaks. The new version says match any character that is either whitespace, or not whitespace, which is effectively any ...
I want to findall prime factors of a number, for example8: 2 2 2or12: 2 2 3. So I write this code: ``` #include <stdio.h> int main() { int a, triangularNum, n; scanf("%d", &triangularNum); for (a = 2; a <= n; ++a) { while (n % a == 0) { n = triangularNum; printf...
Your code works just fine if you remove thistriangularNum: ``` #include <stdio.h> int main() { int a, n; scanf("%d", &n); for (a=2; a<=n; ++a) { while(n%a==0) { printf("%d\t", a); n = n/a; } } } ```
I have a function that reads in a file and prints it out as a grid. This is the file (input): ``` 2 2 1.83 5.64 7.36 4.10 ``` But when it prints out the matrix it only returns whole numbers (output): ``` 2 2 1.00 5.00 7.00 4.00 ``` How do I get the function to print out the decimal number? Wante...
Your problem isn'tstrtok, it's this: ``` double newVal = strtol(value, &ptr, 10); ``` strtolconverts the string to along, not adouble, so it's discarding the fractional portion. Usestrtodinstead: ``` double newVal = strtod( value, &ptr ); ```
I found this piece of code and I am trying to figure out how it works, but I don't understand the part after the return statement. Can somebody explain this? ``` int f(int y) { return (y<=1)?1:y*f(y-1); } ```
This: ``` int f(int y) { return (y<=1) ? 1 : y*f(y-1); } ``` is equivalent to this: ``` int f(int y) { if(y <= 1) { return 1; } else { return y*f(y-1); } } ``` which should be clear to you by now, that it's a recursive function that usesThe ternary (conditional) operator in C. The ternary oper...
This question already has answers here:What is the behavior of integer division?(6 answers)Closed6 years ago. I entered the following code (and had no compiling problems or anything): ``` float y = 5/2; printf("%f\n", y); ``` The output was simply:2.00000 My math isn't wrong is it? Or am I wrong on the / operator?...
5is anintand2is anint. Therefore,5/2will use integer division. If you replace5with5.0f(or2with2.0f), making one of theints afloat, you will get floating point division and get the2.5you expect. You can also achieve the same effect by explicitly casting either the numerator or denominator (e.g.((float) 5) / 2).
I seem to have a vague memory that some facility in Linux exists that allows one to fork() a process in such a way that the child is automatically reaped by the system without a zombie being created. What is this mechanism? Or is my memory just wrong?
The portable way to do this is to double-fork: ``` pid = fork(); if (pid>0) { int status; while (waitpid(pid, &status, 0) && !WIFEXITED(status) && !WIFSIGNALED(status)); if (WIFSIGNALED(status) || WEXITSTATUS(status)) goto error; } else if (!pid) { pid = fork(); if (pid) _exit(pid<0); else { ...
I want to findall prime factors of a number, for example8: 2 2 2or12: 2 2 3. So I write this code: ``` #include <stdio.h> int main() { int a, triangularNum, n; scanf("%d", &triangularNum); for (a = 2; a <= n; ++a) { while (n % a == 0) { n = triangularNum; printf...
Your code works just fine if you remove thistriangularNum: ``` #include <stdio.h> int main() { int a, n; scanf("%d", &n); for (a=2; a<=n; ++a) { while(n%a==0) { printf("%d\t", a); n = n/a; } } } ```
I have a function that reads in a file and prints it out as a grid. This is the file (input): ``` 2 2 1.83 5.64 7.36 4.10 ``` But when it prints out the matrix it only returns whole numbers (output): ``` 2 2 1.00 5.00 7.00 4.00 ``` How do I get the function to print out the decimal number? Wante...
Your problem isn'tstrtok, it's this: ``` double newVal = strtol(value, &ptr, 10); ``` strtolconverts the string to along, not adouble, so it's discarding the fractional portion. Usestrtodinstead: ``` double newVal = strtod( value, &ptr ); ```
What does following0x0\1mean in following code? I find this in an embedded C code: ``` uint16 size; ... size += (size & 0x0\1); ``` It's part of Texas Instruments released code. It compiles in IAR ARM IDE.
Non-portable, implementation dependent, non-standard conforming code. It is anybody's guess what the original author has intended but "probably" meanssize += size & 0x1. That is: increment size by 1 in case size is odd (that is, least significant bit is 1).
I have these two equations and I need to convert them to C code where you inputkandx. The thing is I don't get that advanced levels of math, neither did I learn C in the past :D Can anyone show me step by step what built-in functions can be used for this and how exactly should the logic behind the app work? Cheer...
Your formula is wrong. As shownhere(along with the proof of the derivation) the correct formula is You havekandnswapped in your summation. The inputs should then bexandn. The correct code is then: ``` #include <math.h> double sum_of_sin(double x, int n) { if (sin(x/2) == 0.0) { return 0.0; //prevent di...
I have written a python function for gdb to print an array to save me time,to type the same line everytime. ``` define print_array print *($arg0)@(sizeof($arg0)/ sizeof($arg0[0]) end ``` It works like expected, but when I try to print an array of structs, I get the following error : ``` >>> print_array opcode_l...
You seem to be missing a). ``` define print_array print *($arg0)@(sizeof($arg0)/ sizeof($arg0[0])) end ```
What does following0x0\1mean in following code? I find this in an embedded C code: ``` uint16 size; ... size += (size & 0x0\1); ``` It's part of Texas Instruments released code. It compiles in IAR ARM IDE.
Non-portable, implementation dependent, non-standard conforming code. It is anybody's guess what the original author has intended but "probably" meanssize += size & 0x1. That is: increment size by 1 in case size is odd (that is, least significant bit is 1).
I have these two equations and I need to convert them to C code where you inputkandx. The thing is I don't get that advanced levels of math, neither did I learn C in the past :D Can anyone show me step by step what built-in functions can be used for this and how exactly should the logic behind the app work? Cheer...
Your formula is wrong. As shownhere(along with the proof of the derivation) the correct formula is You havekandnswapped in your summation. The inputs should then bexandn. The correct code is then: ``` #include <math.h> double sum_of_sin(double x, int n) { if (sin(x/2) == 0.0) { return 0.0; //prevent di...
I have written a python function for gdb to print an array to save me time,to type the same line everytime. ``` define print_array print *($arg0)@(sizeof($arg0)/ sizeof($arg0[0]) end ``` It works like expected, but when I try to print an array of structs, I get the following error : ``` >>> print_array opcode_l...
You seem to be missing a). ``` define print_array print *($arg0)@(sizeof($arg0)/ sizeof($arg0[0])) end ```
I am trying to fix this compiler warning: ``` warning C4244: '=' : conversion from 'double' to 'myRealVar', possible loss of data ``` myRealVar is defined in a preprocessor block: ``` #ifdef SINGLE_PRECISION typedef float myRealVar; #else typedef double myRealVar; #endif ``` The warning occurs on the line that bas...
You need to cast the1.0as well as the return value fromsqrt, to remove the warning. Both have the typedouble. ``` someVar[a][b] = (myRealVar)1.0 / (myRealVar)sqrt(someVar[a][b]); ```
I have a piece of code that usegethostbyname()function, which is defined this way: ``` struct hostent *gethostbyname(const char *name); ``` My question is very simple, is it possible to directly put the char value like this : ``` gethostbyname("10.11.22.4"); ``` or do I have to do it like: ``` char *tab[10]; get...
As saidherethe type of a string literal "this is a string literal" is an array ofconst char. Arrays decay to pointers, so this means you can use ``` gethostbyname("10.11.22.4"); ``` without declaring it first
I am cross compiling an applicantion for arm in yocto build using bitbake. It's compiling fine but linking fails with below error. ``` /gcc/arm-poky-linux-gnueabi/5.3.0/ld: cannot find crt1.o: No such file or directory ``` It also failed to link other files crti.o and crtbegin.o. I am not sure which dir needs to be ...
Just try a simple puts("Hello world") compiling with cc hello.c (no other options). If still have same issue most likely your toolchain is wrongly installed, else, check the linker options, may you are setting to not find standard libraries. Hope it helps.
I have a version.h header file where I have the version of my application defined: ``` #define VERSION 0x0100 ``` I would like to add it as a suffix to the output file. So instead of having myapp.elf I would like to have myapp_0100.elf. Is there a way to use symbols in the compilation options?
You can do the opposite. Define a variable in Eclipse and use it when compiling. Go to theProject Properties-> C/C++ Build -> Build variables Define a new variableblahwith value0100. Then in the build settings, depending on your project type you can pass the-DVERSION=${blah}to the compiler. It will define the symbol ...
I have a small segment of C code that I am a bit confused about. ``` int *p, *q, arr[4]={5,8,3,7} p = q = arr; ``` Does the pointer assignment mean bothpandqequalarr? Or thatpequalsqwhich equalsarr? This has been bugging me for a while, any help appreciated
The assignment operator (=) is right associative. This means ``` a = b = c; ``` parses as ``` a = (b = c); ``` That is, the value ofcis assigned tob, and the result value of this assignment operation is assigned toa. The=operator is defined to return the value that was assigned, so this effectively sets bothaandb...
I found the followingforloop that I cannot understand why it looks different than the traditional one, i.e.(init; condition; increment): ``` int parent, i, indx; for (; indx; indx = parent) { parent = (indx - 1) / 2; if (h->queue[parent] >= value) break; h->queue[indx] = h->queue[parent]; } ``` Can someo...
In a for loop, each of the initialization, termination, and step expressions can be omitted. If the initialization step is skipped, there's no initialization done. If the step is skipped, no step is performed. If the test is skipped, the loop runs until it's broken out of. Rather than trying to rewrite this loop to i...
I am creating a simple boot loader. My boot loader doesn't support any of Fat file systems. I read in some tutorials that some processors expects the BPB. So, how can I be on safe side by omitting BPB. I saw a source code of legacy Grub and its first stage has no BPB. Help me out.. Thanks
The BPB is an artifact of the FAT bootloader, and it only makes sense for floppy disks, and that only because it's not practical to detect the format geometry of floppy disks. If you are not using floppy disks, you do not need to bother.
In some network code I need to encode packet structures in a buffer to send(2) over a socket but memcpy'ing the encoded buffers into a bigger buffer seems problematic. Here's a small code example illustrating what I am doing: ``` char tbuf[] = "test"; char *buf = malloc(300); memset(buf, '\0', 300); int b...
You are repeatedly copying the null terminator at the end of test.sizeof tbufis 5. So all the C standard library functions will ignore all the other concatenants. The solution: copy one less byte in thememcpy, and be sure to add a null terminator to the final string.
I'm trying to get the user's input and display it in a messagebox. The issue I'm having, is without the 'L' before the string, it comes out as gibberish. My char[] named 'input' stores the string the user enters, but how can I make it so there is an 'L' there? Everything I've tried so far has given me an error,includi...
Probably your environment defines_UNICODEfor compilation process andMessageBoxmacro is expanded toMessageBoxW. Try to replace your code with this: ``` MessageBoxA(NULL, input, "You wrote", MB_OK); ``` This explicitly states that you want to use the ANSI version, that will handle result offgets()properly.
I have a small segment of C code that I am a bit confused about. ``` int *p, *q, arr[4]={5,8,3,7} p = q = arr; ``` Does the pointer assignment mean bothpandqequalarr? Or thatpequalsqwhich equalsarr? This has been bugging me for a while, any help appreciated
The assignment operator (=) is right associative. This means ``` a = b = c; ``` parses as ``` a = (b = c); ``` That is, the value ofcis assigned tob, and the result value of this assignment operation is assigned toa. The=operator is defined to return the value that was assigned, so this effectively sets bothaandb...
I found the followingforloop that I cannot understand why it looks different than the traditional one, i.e.(init; condition; increment): ``` int parent, i, indx; for (; indx; indx = parent) { parent = (indx - 1) / 2; if (h->queue[parent] >= value) break; h->queue[indx] = h->queue[parent]; } ``` Can someo...
In a for loop, each of the initialization, termination, and step expressions can be omitted. If the initialization step is skipped, there's no initialization done. If the step is skipped, no step is performed. If the test is skipped, the loop runs until it's broken out of. Rather than trying to rewrite this loop to i...
I am creating a simple boot loader. My boot loader doesn't support any of Fat file systems. I read in some tutorials that some processors expects the BPB. So, how can I be on safe side by omitting BPB. I saw a source code of legacy Grub and its first stage has no BPB. Help me out.. Thanks
The BPB is an artifact of the FAT bootloader, and it only makes sense for floppy disks, and that only because it's not practical to detect the format geometry of floppy disks. If you are not using floppy disks, you do not need to bother.
In some network code I need to encode packet structures in a buffer to send(2) over a socket but memcpy'ing the encoded buffers into a bigger buffer seems problematic. Here's a small code example illustrating what I am doing: ``` char tbuf[] = "test"; char *buf = malloc(300); memset(buf, '\0', 300); int b...
You are repeatedly copying the null terminator at the end of test.sizeof tbufis 5. So all the C standard library functions will ignore all the other concatenants. The solution: copy one less byte in thememcpy, and be sure to add a null terminator to the final string.
I'm trying to get the user's input and display it in a messagebox. The issue I'm having, is without the 'L' before the string, it comes out as gibberish. My char[] named 'input' stores the string the user enters, but how can I make it so there is an 'L' there? Everything I've tried so far has given me an error,includi...
Probably your environment defines_UNICODEfor compilation process andMessageBoxmacro is expanded toMessageBoxW. Try to replace your code with this: ``` MessageBoxA(NULL, input, "You wrote", MB_OK); ``` This explicitly states that you want to use the ANSI version, that will handle result offgets()properly.
I'm trying to build a VS solution command line, just with the cmd. I can do it by launching the devenv console, then run devenv command etc... This work, but I have to do it with the cmd, because I use nodejs to run it, and I need to get the output. Does anybody has a solution ?
As usual with Visual C++, you open a command prompt window using one of "Tools" shortcuts ("VS2015 x64 Native Tools Command Prompt" or others located inC:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio 2015\Visual Studio Tools\Windows Desktop Command Prompts). In this console window,cdto your code an...
there's a structure of arrays like this. ``` typedef struct { char mother [50]; char father [50]; } family; family divorce [100]; ``` On this array, I input the number + char (length is random) like 123a 253vv 2145eee..., and I'd like to save only number to the another char array. What should I do?
Useisdigit()to determine whether the character is a decimal digit or not. If the char is a digit, populate it in the array. Another way, checkif(ch >= '0' && ch <= '9') arr[i++] = ch;
Clang-format changes this: ``` HANDLE (*get)(); ``` to: ``` HANDLE(*get) (); ``` How can we prevent that? Note that if we haveHandle,hANDLE, or anything else that is not all in caps, this formatting is not applied.
This happens if you haveColumnLimit: 0. With any other value forColumnLimit, the parentheses are kept on the same line. Note that the pre-defined styleWebKitsetsColumnLimit: 0, so maybe you are using theWebKitstyle. Your workaround would be to setColumnLimitto some reasonable non-zero value. Also interesting, once th...
I'm trying to build a VS solution command line, just with the cmd. I can do it by launching the devenv console, then run devenv command etc... This work, but I have to do it with the cmd, because I use nodejs to run it, and I need to get the output. Does anybody has a solution ?
As usual with Visual C++, you open a command prompt window using one of "Tools" shortcuts ("VS2015 x64 Native Tools Command Prompt" or others located inC:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio 2015\Visual Studio Tools\Windows Desktop Command Prompts). In this console window,cdto your code an...
there's a structure of arrays like this. ``` typedef struct { char mother [50]; char father [50]; } family; family divorce [100]; ``` On this array, I input the number + char (length is random) like 123a 253vv 2145eee..., and I'd like to save only number to the another char array. What should I do?
Useisdigit()to determine whether the character is a decimal digit or not. If the char is a digit, populate it in the array. Another way, checkif(ch >= '0' && ch <= '9') arr[i++] = ch;
Clang-format changes this: ``` HANDLE (*get)(); ``` to: ``` HANDLE(*get) (); ``` How can we prevent that? Note that if we haveHandle,hANDLE, or anything else that is not all in caps, this formatting is not applied.
This happens if you haveColumnLimit: 0. With any other value forColumnLimit, the parentheses are kept on the same line. Note that the pre-defined styleWebKitsetsColumnLimit: 0, so maybe you are using theWebKitstyle. Your workaround would be to setColumnLimitto some reasonable non-zero value. Also interesting, once th...
there's a structure of arrays like this. ``` typedef struct { char mother [50]; char father [50]; } family; family divorce [100]; ``` On this array, I input the number + char (length is random) like 123a 253vv 2145eee..., and I'd like to save only number to the another char array. What should I do?
Useisdigit()to determine whether the character is a decimal digit or not. If the char is a digit, populate it in the array. Another way, checkif(ch >= '0' && ch <= '9') arr[i++] = ch;
Clang-format changes this: ``` HANDLE (*get)(); ``` to: ``` HANDLE(*get) (); ``` How can we prevent that? Note that if we haveHandle,hANDLE, or anything else that is not all in caps, this formatting is not applied.
This happens if you haveColumnLimit: 0. With any other value forColumnLimit, the parentheses are kept on the same line. Note that the pre-defined styleWebKitsetsColumnLimit: 0, so maybe you are using theWebKitstyle. Your workaround would be to setColumnLimitto some reasonable non-zero value. Also interesting, once th...
People usually mention ``` while( getchar() != '\n' ) ``` when it comes to clearing the input buffer or overflow. fgetcorgetcalso work. For example: ``` while( fgetc(stdin) != '\n' ) ``` and ``` while( getc(stdin) != '\n' ) ``` Is there any particular reason why people always usegetchar? Is there any disadvant...
People prefergetcharonly in situations when they read from standard input. There is no reason why one wouldn't replace it withgetc/fgetcwhen reading from a file is needed. With this said, the construct is dangerous, because it can lead to an infinite loop in situations when there is no'\n'in the input stream. For exa...
I want to create a function in C that allocates a dynamic matrix; the idea is to allocate an array whose elements are pointers to arrays; if I want to do that in a function, what is the correct code? this ``` f(***matrix) ``` or this ``` f(**matrix)? ``` I would say the first one, but I'm not sure. thank you!
You probably want something like ``` double ** allocate_array(size_t rows, size_t cols) { double **array = malloc(cols * sizeof(*array)); if (array == NULL) return NULL; for (size_t i = 0; i < cols; i++) { array[i] = malloc(rows * sizeof(*array[i])); for (size_t j = 0; j < rows; j++) array...
I have the following code in C ``` #include <stdio.h> int main() { float a = 1.88; a =a - (0.25 * 7 + 0.1 * 1); a = a *100; printf("a = %f\n",a ); int b =(int) (a); printf("b = %d\n", b); } ``` The value of b should be2but I get the following output- ``` a = 3.000000 b = 2 ``` Why is it s...
If you change ``` printf("a = %f\n",a ); ``` to ``` printf("a = %.20f\n",a ); ``` it outputs ``` a = 2.99999952316284179688 ``` As you can see this is not 3. So the conversion truncates it to 2.
I want to have a struct with an embedded array buffer and a pointer, which can either point to the embedded buffer or an external buffer: ``` struct s { char internal_buf[BUF_SIZE]; char *active_buf; }; ``` I would like tostatically initialize(as in a global variable) this structure such that theactive_buffi...
Well, turns out the correct syntax for this is just: ``` struct s inst = { .internal_buf = {0}, .active_buf = inst.internal_buf, // Works, address is known at compile-time }; ```
``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void){ char noun[25]; char plural[28]; fgets(noun,24,stdin); strcpy(plural,noun); int len=strlen(plural); if(plural[len-2]=='h'||plural[len-2]=='s'){ plural[len-1]='e'; plural[len]='s'; plural[le...
fgets is picking up a trailing newline character from stdin when you hit enter. Hence noun ends with a newline char
This question already has answers here:What is the function of "(void) (&_min1 == &_min2)" in the min macro in kernel.h?(6 answers)Closed6 years ago. I was looking through linux kernel source code (kernel.h) and I found this macro forminfunction: ``` #ifndef max #define max(x, y) ({ \ typeof(x) _m...
It prevents accidental type casting ofxory. You can arithmetical compare differently sized integers with the same sign, but you must not compare their pointers. I.e. this code would generate a compiler warning: ``` short a = 47; long b = 11; min(a, b); ``` C.f.Is comparing two void pointers to different objects defi...
I'm implementing a snake game in C. The snake array is made up of 3x3 sprites. The head of the sprite moves in increments of 1. I'm wondering how I would go about storing the location of the head 3 steps previously so I can then set the next sprite in the array equal to that location and so forth down the length of th...
``` move() back3 = back2 back2 = back1 back1 = current current = ?? ``` You could also try a circular buffer with moving pointers. That way you won't have to do all that copying. It's a little harder to implement and debug, though.
When generating a wrapper for a C (not C++) library, the generated C# wrapper code is missing definitions for the typesSWIGTYPE_p_void,SWIGTYPE_p_uint32_tet. al. that are used throughout the generated code. Are there files I need to include in my.ifile to enable cause these to be generated? As command line options to...
It turns out the problem was that SWIG crashed in the middle due to too long filenames for function pointer types with a lot of parameters ...
``` socklen_t clilen; // declaration n = sendto(sockfd1, buffer, sizeof(buffer), 0, (struct sockaddr *)&cli_addr, &clilen); if(n < 0) { printf("\nERROR writing to socket\n"); exit(0); } ``` While compiling my code, it is giving me a warning like..... ``` warning: passing argument 6 of ‘sendto’ makes integer...
Just try ``` n = sendto(sockfd1, buffer, sizeof(buffer), 0, (struct sockaddr *)&cli_addr, clilen); ``` I think the last argument type issocklen_tand it's not a pointer, so you don't need to pass the the address of the variable; just pass the variable itself it will work and will not give any warning like you are get...
Apple doesn't allow root priviledge in iOS so I can't create a raw socket. What I'm looking for is a way to set the flags on a UDP Header in the Fragment-Offset octet's of the header. Does anyone know any way of doing this in iOS that doesn't require root privelidge to change the flags of the UDP Header. Particular...
The relatively newNetwork API(since iOS 12) now allows you to set DF (among other things) without root: https://developer.apple.com/documentation/network/2976768-nw_ip_options_set_disable_fragme?language=objc There are several other configurable flags/settings as well, not just at theTCPand UDP layer, but also theIP...
Can someone please tell me how would we evaluate the inner loop pointer:*++argv[0]. How does it end up getting the second character from the argument? ``` #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { while (--argc > 0 && (*++argv)[0] == '-') { while ((c = *++argv[0])) { ...
The array subscript operator has higher precedence than the prefix ++ and the dereference operator. The latter two operators have the same precedence and are evaluated from right to left. The expression in the second while loop is equivalent to: ``` *(++(argv[0])) ``` The pointer to the string is obtained using the ...
When generating a wrapper for a C (not C++) library, the generated C# wrapper code is missing definitions for the typesSWIGTYPE_p_void,SWIGTYPE_p_uint32_tet. al. that are used throughout the generated code. Are there files I need to include in my.ifile to enable cause these to be generated? As command line options to...
It turns out the problem was that SWIG crashed in the middle due to too long filenames for function pointer types with a lot of parameters ...
``` socklen_t clilen; // declaration n = sendto(sockfd1, buffer, sizeof(buffer), 0, (struct sockaddr *)&cli_addr, &clilen); if(n < 0) { printf("\nERROR writing to socket\n"); exit(0); } ``` While compiling my code, it is giving me a warning like..... ``` warning: passing argument 6 of ‘sendto’ makes integer...
Just try ``` n = sendto(sockfd1, buffer, sizeof(buffer), 0, (struct sockaddr *)&cli_addr, clilen); ``` I think the last argument type issocklen_tand it's not a pointer, so you don't need to pass the the address of the variable; just pass the variable itself it will work and will not give any warning like you are get...
Apple doesn't allow root priviledge in iOS so I can't create a raw socket. What I'm looking for is a way to set the flags on a UDP Header in the Fragment-Offset octet's of the header. Does anyone know any way of doing this in iOS that doesn't require root privelidge to change the flags of the UDP Header. Particular...
The relatively newNetwork API(since iOS 12) now allows you to set DF (among other things) without root: https://developer.apple.com/documentation/network/2976768-nw_ip_options_set_disable_fragme?language=objc There are several other configurable flags/settings as well, not just at theTCPand UDP layer, but also theIP...
Can someone please tell me how would we evaluate the inner loop pointer:*++argv[0]. How does it end up getting the second character from the argument? ``` #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { while (--argc > 0 && (*++argv)[0] == '-') { while ((c = *++argv[0])) { ...
The array subscript operator has higher precedence than the prefix ++ and the dereference operator. The latter two operators have the same precedence and are evaluated from right to left. The expression in the second while loop is equivalent to: ``` *(++(argv[0])) ``` The pointer to the string is obtained using the ...
This question already has answers here:What happens to a declared, uninitialized variable in C? Does it have a value?(9 answers)Closed6 years ago. By running this code ``` char array[6]; int i; for ( i = 0; i < 6; ++i ) printf("%i ", array[i]); ``` Possible output: ``` 64 0 -64 77 67 0 ``` I getalwaysthe last...
No. There's no such thing guaranteed by the C standard for local variables. The values of the uninitialized array hasindeterminate values. So, you can't access them and since you do, your code hasundefined behaviour. But the variables with static storage duration such as global variables,staticqualified variables et...
This question already has answers here:Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?(19 answers)Closed6 years ago. Can anyone explain why this code not work, pls!! Thanks you so much! ``` #include <stdio.h> void changer(char * tp) { int i=0;...
This statement ``` tp[0]='b'; ``` results inundefined behaviourbecausetppoints to astring literal. You are not allowed to modify a string literal in C. Instead you could use an array: ``` char st[] = "aaab"; ``` which you'd be able to modify.
I am trying to understand following piece of code, but I am confused between"\0"and'\0'.I know its silly but kindly help me out ``` #define MAX_HISTORY 20 char *pStr = "\0"; for(x=0;x<MAX_HISTORY;x++){ str_temp = (char *)malloc((strlen(pStr)+1)*sizeof(char)); if (str_temp=='\0'){ re...
They are different. "\0"is a string literal which has two consecutive 0's and is roughly equivalent to: ``` const char a[2] = { '\0', '\0' }; ``` '\0'is anintwith value 0. You can always 0 wherever you need to use'\0'.
In C, how can I write a program to find the maximum value of an integer variable? As far as I know the maximum value of an integer variable is 2147483647 but how can I represent this in a C program ?
As ı know the maximum value of a integer variable is 2147483647 That's a wrong assumption. The maximum value of anintcan vary across systems. For example, on a 16-bit machine maximum value ofintis not 2147483647. You don't need to find it yourself. There are pre-defined macros which you can use from<limits.h>. For e...
This question already has answers here:What's the meaning of the %m formatting specifier?(2 answers)Closed6 years ago. How is the output of this code is "Success"? When I compiled this code it simply outputs "Success" ``` #include <stdio.h> int main(void) { printf("%m"); return 0; } ```
This is a Glibc extension toprintf. It outputs the result ofstrerror(errno)and requires no argument. From theman page: ``` m (Glibc extension.) Print output of strerror(errno). No argu- ment is required. ``` Sinceerrnostarts out at 0 on startup, it prints the message for error code 0, which isSu...
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.Closed6 years ago.Improve this question So Ineed to calculate the determinant matrix on 2x2 matrix,simple one.. If you can, please write the code, ...
You don't need a loop to calculate the determinant of a 2x2 matrix, simply use: ``` int result = (x[0][0] * x[1][1]) - (x[0][1] * x[1][0]); ```
Say I have, ``` char x[0] = '1'; char x[1] = '2'; ``` I need to 'concatenate' these two into an integer variable, ``` int y = 12; ``` How do I do this?
The simplest way, if it's really only two digits and you don't want to "go up" (in complexity) to a string in order to use string-conversion functions, is to just compute it directly using the basic structure of a number. Each digit is worth 10 times more than the one to its right. ``` const char x[2] = { '1', '2' };...
For some reason, my printf and scanf are undeclared apparently. I think it's something to do with my functions which I don't understand very well. ``` #include<stdlib.h> #include<stdlib.h> #include<ctype.h> void testCount (); int eleven = 11; int input = 0; int output = 0; int count = 0; int main (){ printf("W...
You need to#include <stdio.h>to fix the problem withprintf()andscanf(). You have#include <stdlib.h>twice. Also, you should change: ``` void testCount (); ``` to: ``` void testCount (int x); ``` as suggested by @ Keine Lust. And please don't forget to pass a value to your newly mintedtestCount()function!
This question already has answers here:What's the meaning of the %m formatting specifier?(2 answers)Closed6 years ago. How is the output of this code is "Success"? When I compiled this code it simply outputs "Success" ``` #include <stdio.h> int main(void) { printf("%m"); return 0; } ```
This is a Glibc extension toprintf. It outputs the result ofstrerror(errno)and requires no argument. From theman page: ``` m (Glibc extension.) Print output of strerror(errno). No argu- ment is required. ``` Sinceerrnostarts out at 0 on startup, it prints the message for error code 0, which isSu...
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.Closed6 years ago.Improve this question So Ineed to calculate the determinant matrix on 2x2 matrix,simple one.. If you can, please write the code, ...
You don't need a loop to calculate the determinant of a 2x2 matrix, simply use: ``` int result = (x[0][0] * x[1][1]) - (x[0][1] * x[1][0]); ```
Say I have, ``` char x[0] = '1'; char x[1] = '2'; ``` I need to 'concatenate' these two into an integer variable, ``` int y = 12; ``` How do I do this?
The simplest way, if it's really only two digits and you don't want to "go up" (in complexity) to a string in order to use string-conversion functions, is to just compute it directly using the basic structure of a number. Each digit is worth 10 times more than the one to its right. ``` const char x[2] = { '1', '2' };...
For some reason, my printf and scanf are undeclared apparently. I think it's something to do with my functions which I don't understand very well. ``` #include<stdlib.h> #include<stdlib.h> #include<ctype.h> void testCount (); int eleven = 11; int input = 0; int output = 0; int count = 0; int main (){ printf("W...
You need to#include <stdio.h>to fix the problem withprintf()andscanf(). You have#include <stdlib.h>twice. Also, you should change: ``` void testCount (); ``` to: ``` void testCount (int x); ``` as suggested by @ Keine Lust. And please don't forget to pass a value to your newly mintedtestCount()function!
I was trying to define a general function to take input using _Generic in C, This is what I wrote ``` #include <stdio.h> #define readlong(x) scanf("%lld",&x); #define read(x) scanf("%lld",&x); #define scan(x) _Generic((x), \ long long: readlong, \ default: read \ )(x) ``` but when I compile it usinggcc test.c -st...
You can define your helpers to be functions instead of macros. I modifiedscanso that it would pass the address to the matched function. ``` static inline int readlong (long long *x) { return scanf("%lld", x); } static inline int readshort (short *x) { return scanf("%hd", x); } static inline int unknown (void) { retur...
I want to display a full name, but I can't enter more than two parts of a name. The program stuck when enter a name which has more characters than the number which array has. How can I solve this? ``` #include <stdio.h> #include<stdlib.h> int main(){ char x[25]; printf("Enter your name"); scanf("%s",x); printf("You...
I think this can help you. This program doesnt care how many characters, spaces you entered. It only displays first 24 characters and spaces. (1 for string terminator) ``` #include <stdio.h> #include <stdlib.h> int main(){ char x[25]; char *xx=x; puts("Input Name"); fgets(xx,25,stdin); puts(xx); return 0; ...
This question already has answers here:Why dividing two integers doesn't get a float? [duplicate](7 answers)Dividing 1/n always returns 0.0 [duplicate](3 answers)Closed6 years ago. I wanna get 1.666667 by dividing 2*n+1 by 3 (n=2). and it always creates 1.000000 but i want 1.666667. I tried printing (2*n+1)/3 as a fl...
You are doing integer division and then assigning to a float. Use ``` (2.0*n+1)/3 ``` The2.0is a double and the whole expression is then converted to a double, which is assigned to a float giving you the result intended.
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.
This is my code where fp is the opened file ``` unsigned char string[10]; while(fgets(string, 10, fp)) // do stuff with string ``` Now i want to loop each char in the array but how is the array filled when the file only had 5 characters. Does it contain an EOF char or something?
Fromfgets(): fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer. Th...
I have 2 programs (processes). One process writes to shared memory while the other reads it. So, my approach was like this: Initially, value of shared memory is 0. So, process 1 writes only when value is 0. Now process 1 has written some other value to shm and "waits" till value becomes 0. Process 2 reads the shm and ...
Mentioned problem known as Process Synchronization problem and given logic is nothing but Busy Waiting approach of the problem which is very primary solution. ReadProducer-Consumer Problemwhich is similiar to given problem. There are some better solutions to this than Busy Waiting like: Spinlock, Semaphore etc. Yo...
When to use break, and continue in C language? Can I use them both with loop, and without loop? If a condition in a loop is enough to instruct whether to continue or not continue then what are the needs use them? Is it a good practice to use them? Thanks in advance.
You might decide that the current loop iteration shouldn't run any more and want to start new iteration right away. This is whatcontinueis for. You also might decide that the whole loop shouldn't be running anymore, despite the loop condition could still evaluate to true. This is whenbreakcomes in handy.
I want to use the operator->in a recent project (written in C), but I constantly get the errorIllegal member reference for "->". I know that this operator can be used in the recent C and C++ versions. The C standart used by my compiler/linker isC89/C90, i think. Do you guys know in which update the structure dereferen...
It has been in the language since its creation, far earlier than the C89/C90 ANSI/ISO standardization. Your compiler error is most likely related to some mistake in your code and not to the language standard.
when I input a floating point number (eg. 48.3) the result displayed is 48.00 instead of 48.30 and whenever I try to input string with empty space the program ends immediately. I need help, how to fix this problem? ``` int integer; char a[50]; float fnum; char b[50]; printf("Please enter an integer : "); scan...
You're converting stringbinto anintegerby callingatoi. You want to convert it to a floating point number, so useatof: ``` fnum = atof(b); ```
I tried using the nCm function to find all combinations but for large numbers it fails ``` int fact(int num) { if (num == 1 || num == 0) return 1; return num * fact(num-1); } int nCm(int num, int base) { int result; return result = fact(num) / (fact(num - base)*fact(base)); } ``` wherebase =...
If you consider that division for a moment, you'll see that the(n-b)!term is common to both numerator and denominator (i.e.they cancel out). You just need to think ofn!as: ``` n * (n-1) * (n-2) * ... * (n-b+1) * (n-b)! ``` Now you can calculate the result without any division or large intermediate values (which co...
I tried to run this code on Linux to see what would happen: ``` int fn(void) { return 0; } int main(void) { __asm__("jmp fn;"); } ``` I don't see any reason for the execution to be terminated by a SIGSEGV, but that's what I get. I expected the flow to be redirected to_startsince the stack isn't modified in any way i...
return 0generates something like ``` mov $0x0, %eax ret ``` whereretpops the return address from the stackand jumps there. A simplejmpdoesn't push any return address, soretwill pop whatever is on the stack.
This question already has answers here:Confused by squaring macro SQR in c [duplicate](3 answers)Closed6 years ago. ``` #include<stdio.h> #define mul(p,q) p*q int main(){ int a=5; printf("%d",mul(a+3,a-2)); return 0; } ``` I expected this to print 24, but I got 18. Why is that happening?
It's basically, find and replace before compiling. Your code becomes ``` int main(){ int a=5; printf("%d",a+3*a-2); return 0; } ``` instead of#define mul(p,q) p*qyou should do#define mul(p,q) ((p)*(q)). Then your code would become as below and you would get the expected answer. ``` int main(){ int a...
``` int main(){ int n,i=0,c1,c2; char a[1000]; scanf("%d",&n); while(n!=0) { a[i]=n%2; printf("%d",a[i]); // This prints Values Correctly n=n/2; i++; } a[i]='\0'; for(i=0;a[i]!='\0';i++) printf("%d",a[i]); //This prints only the first element of the array } ``` What am I missing here? Why can...
The array, which has the type char, is used to store integers, the array isn't a string. Because you store remained of division by 2, most elements will have the value 0. Remove the line that null terminates the array. The variable i already counts the number of elements entered, so iterate and print until you print ...
when I input a floating point number (eg. 48.3) the result displayed is 48.00 instead of 48.30 and whenever I try to input string with empty space the program ends immediately. I need help, how to fix this problem? ``` int integer; char a[50]; float fnum; char b[50]; printf("Please enter an integer : "); scan...
You're converting stringbinto anintegerby callingatoi. You want to convert it to a floating point number, so useatof: ``` fnum = atof(b); ```
I tried using the nCm function to find all combinations but for large numbers it fails ``` int fact(int num) { if (num == 1 || num == 0) return 1; return num * fact(num-1); } int nCm(int num, int base) { int result; return result = fact(num) / (fact(num - base)*fact(base)); } ``` wherebase =...
If you consider that division for a moment, you'll see that the(n-b)!term is common to both numerator and denominator (i.e.they cancel out). You just need to think ofn!as: ``` n * (n-1) * (n-2) * ... * (n-b+1) * (n-b)! ``` Now you can calculate the result without any division or large intermediate values (which co...
I tried to run this code on Linux to see what would happen: ``` int fn(void) { return 0; } int main(void) { __asm__("jmp fn;"); } ``` I don't see any reason for the execution to be terminated by a SIGSEGV, but that's what I get. I expected the flow to be redirected to_startsince the stack isn't modified in any way i...
return 0generates something like ``` mov $0x0, %eax ret ``` whereretpops the return address from the stackand jumps there. A simplejmpdoesn't push any return address, soretwill pop whatever is on the stack.
This question already has answers here:Confused by squaring macro SQR in c [duplicate](3 answers)Closed6 years ago. ``` #include<stdio.h> #define mul(p,q) p*q int main(){ int a=5; printf("%d",mul(a+3,a-2)); return 0; } ``` I expected this to print 24, but I got 18. Why is that happening?
It's basically, find and replace before compiling. Your code becomes ``` int main(){ int a=5; printf("%d",a+3*a-2); return 0; } ``` instead of#define mul(p,q) p*qyou should do#define mul(p,q) ((p)*(q)). Then your code would become as below and you would get the expected answer. ``` int main(){ int a...
``` int main(){ int n,i=0,c1,c2; char a[1000]; scanf("%d",&n); while(n!=0) { a[i]=n%2; printf("%d",a[i]); // This prints Values Correctly n=n/2; i++; } a[i]='\0'; for(i=0;a[i]!='\0';i++) printf("%d",a[i]); //This prints only the first element of the array } ``` What am I missing here? Why can...
The array, which has the type char, is used to store integers, the array isn't a string. Because you store remained of division by 2, most elements will have the value 0. Remove the line that null terminates the array. The variable i already counts the number of elements entered, so iterate and print until you print ...
In the following code ``` scanf("%s", input); sscanf(input," %s %f ", change, &grades); printf("%s\n", change); printf("%f", grades); ``` grades will be printed as0.00, no matter the input. Why doesn'tsscanfrecognise float format?
The first call toscanfis looking for a sequence of characters delimited by whitespace. If your input looks something like this: ``` test 98.3 ``` Theninputwill only contain the stringtest. If you want to read a full line of text so you can later parse it withsscanf, usefgetsinstead which will read a line: ``` cha...
I am looking for a program to observe the execution stack of a c/c++ program. Currently I am using gdb for this purpose. The following command shows the content of the stack: ``` x/12xg $rsp ``` to execute instruction after instruction I am using ``` stepi ``` Is it possible to combine these to commands so that I...
You can combine commands usingdefine, like: ``` (gdb) define mystep > stepi > x/whatever $rsp > end ``` Nowmystepshould step and then dump some memory.
Consider following code: ``` int main() { char c; for(;(c=getchar())+1;) printf("%c\n",c); } ``` It gets characters what I enter in terminal and prints them. When I remove+1in condition, program works but it doesnt stop whenEOF(Ctrl+D) signal. When I change it to+2same problem. My question is how th...
That is because the int value ofEOFis-1, so what you're doing is loop until the expression(c=getchar())+1) gets the value 0 which is when you readEOF(where value of exrpession is: -1+1=0). Also as wll pointed out in the comments you should declare c as int sincegetchar() returns int.
I am usingexecvin C, but it demands to get the path of the command to get it executed, For example: To executelsI must havechar* command = "/bin/ls";To executegeditI must have char*command = "/usr/bin/gedit"; My question is how to get the string"/bin"or"/usr/bin"in C ?
which command gives the complete path of a command. For example, ``` $ which ls /bin/ls ``` So, you can do something like this in a C program, ``` system ("which ls >x"); // read file x for complete path of ls ```
For this below piece of code ``` int main() { char a=a; printf("%d",a); } ``` Why is the output of the above code 8? If I change%dto%c, it prints nothing.
char a = a;is a self-initialization, which is basically the same as no initialization at all. Therefore, the value of a is undefined. In practice, its value is determined by whatever happened to be stored in memory at the location of the variable before. The numerical value of the letter a in ASCII or Unicode is 97. ...
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 ...
I assume you are missing an include. Try: #include <string.h>
I was trying to make a simple function to check how many bits set to 1 were in an int. What I achieved at first was ``` #include <stdio.h> int bitsOne (int x){ int r=0; while (x > 0){ if (x % 2 == 1) r++; x = x/2; } return r; } ``` I was trying to use the>>operator for this instead ...
Get the bit in the last slot before you do the shift using a mask: ``` int bit = (x & 1); ``` Then do the shift on x.
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 need to read local variables from Python in C/C++. When I try toPyEval_GetLocals, I get a NULL. This happens although Python is initialized. The following is a minimal example. ``` #include <iostream> #include <Python.h> Py_Initialize(); PyRun_SimpleString("a=5"); PyObject *locals = PyEval_GetLocals(); std::cout<<...
Turns out the right way to access variables in the scope is: ``` Py_Initialize(); PyObject *main = PyImport_AddModule("__main__"); PyObject *globals = PyModule_GetDict(main); PyObject *a = PyDict_GetItemString(globals, "a"); std::cout<<globals<<std::endl; //Not NULL Py_Finalize(); ```
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 ...
I assume you are missing an include. Try: #include <string.h>
I was trying to make a simple function to check how many bits set to 1 were in an int. What I achieved at first was ``` #include <stdio.h> int bitsOne (int x){ int r=0; while (x > 0){ if (x % 2 == 1) r++; x = x/2; } return r; } ``` I was trying to use the>>operator for this instead ...
Get the bit in the last slot before you do the shift using a mask: ``` int bit = (x & 1); ``` Then do the shift on x.
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 need to read local variables from Python in C/C++. When I try toPyEval_GetLocals, I get a NULL. This happens although Python is initialized. The following is a minimal example. ``` #include <iostream> #include <Python.h> Py_Initialize(); PyRun_SimpleString("a=5"); PyObject *locals = PyEval_GetLocals(); std::cout<<...
Turns out the right way to access variables in the scope is: ``` Py_Initialize(); PyObject *main = PyImport_AddModule("__main__"); PyObject *globals = PyModule_GetDict(main); PyObject *a = PyDict_GetItemString(globals, "a"); std::cout<<globals<<std::endl; //Not NULL Py_Finalize(); ```