question
stringlengths
25
894
answer
stringlengths
4
863
I'm trying to write a C standard library from scratch on OSX with gcc. When I try to include a header file from my library in my test program, I get the error that it isn't defined. I try to use the -nostdlib flag but I still can't include my file. My test program: ``` #include <math.h> #include <bool.h> #include <c...
Header files aren't compiled into a static library. They have to be available to both library and program. Therefore, when compiling your program, make sure to specify the-Ioptions to let the compiler find your library's header files.
``` #include<iostream> using namespace std; int main() { signed int ar[3]={-5,4,1}; unsigned ar[0]=5; cout<<ar[0]; return 0; } ``` I have to do in such a way that the resultant array is in descending order so that maximum element would be 5 so 5 will be on top , the ab...
If an element in the array is less than zero, multiply it by -1. Don't turn it into an unsigned number, that's probably not going to do what you think it does. Also, as mentioned, what you are doing in your code snippet isn't even modifying the element in the array, it's trying to declare a new array. So basically you...
``` struct node { int x; struct node *next; }; void allocateMemory(struct node *some_node) { some_node = malloc(sizeof(struct node)); } ``` In another function: ``` struct node add(struct node *root, struct node *thisNode, int value) ``` I try to call this: ``` allocateMemory(thisNode->next); ``` I g...
Here in that code : ``` void allocateMemory(struct node *some_node) { some_node = malloc(sizeof(struct node)); } ``` You can write : ``` void allocateMemory(struct node **some_node) { *some_node = malloc(sizeof(struct node)); } ``` And while calling : ``` allocateMemory(&thisNode->next); ```
sorry if my question sounds confused. Here is my code ``` void display_Item_At_Location(char in[][SIZE_OF_ARRAY]) { int loc; int i; printf("Which line would you like to display?\n"); scanf("%d", &loc); for(i = 0; i < SIZE_OF_ARRAY; i++) { printf("%c", in[loc][i]); } retur...
If your strings are NULL-terminated, you could skip theforloop and just do: ``` fprintf(stdout, "%s\n", in[loc - 1]); ``` for a given valuelocwithin index bounds (assuminglocvalue is 1-indexed).
I need to extract the the bits 2,3, and 4 from an uint8 and interpret it as an in. For example if I have 0x1A and 0x1C as mask: 0x1A 0001 1010 Value 0x1c 0001 1100 mask if I do 0x1A & 0x1C I get 0001 1000 which is 24 in base when instead I need just the three bits that are masked 110 (6 in base 10)
Use thebitwise shift operator>>to shift the value 2 bits to the right. Either mask and then shift: ``` result = (value & 0x1C) >> 2; ``` Or shift and then mask (note the mask must be shifted too): ``` result = (value >> 2) & 7; ``` Makes no difference; both approaches will transform the 8-bit valuea7a6a5a4a3a2a1a...
is there any ways to press keys mouse/keyboard with sdl in C? if yes, how? if no, do you know any ways to do that in C?
Create anSDL_eventstructure and fill in the fields as documented inhttp://wiki.libsdl.org/SDL_KeyboardEventandhttp://wiki.libsdl.org/SDL_Keysymthen useSDL_Pushevent()to put the event into the event queue:http://wiki.libsdl.org/SDL_PushEvent ``` SDL_Event event; event.type = SDL_KEYDOWN; event.timestamp = lastEvent...
Here is a code asked to me in an online test. Consider this code. ``` int i = -1, j = -1; (i=0)&&(j=0); (i++)&&(++j); printf("%d, %d\n", i, j); ``` The above code will print ``` 1, -1 ``` Can somebody explain why the output is coming out to be1, -1and not1, 1.
C implements short-circuit evaluation on a few operators. One of these is&&. This means that if the left hand side of the&&evaluates tofalse, then the right hand side will not be evaluated. Additionally, there is a difference between++iandi++.i++will returniand storei+1. On the other hand,++iwill returni+1and storei+...
I am trying to find a way, if it is possible, to copy the values that are pointed by a host array of pointersptsthat points to some elements of another host arrays(float2type). The values that need to be dereferenced fromptswith the->operator are in random positions in thesarray. Is there a way to copy these values p...
If the values you want to copy are in random locations, and you want to copy only those values to the device, you will need to write a separate loop in host code that aggregates those values first into a single contiguous buffer. You can then copy that buffer using an ordinary approach likecudaMemcpy.
This question already has answers here:strange output in comparison of float with float literal(8 answers)Closed9 years ago. I found many questions.But none helps me ``` float x = 0.1; x == 0.1 ``` The above code returns false. since i try to compare double precision value with single precision x. ``` float ...
``` x == 0.1 ``` 0.1is not of typefloatbut of typedouble.floatanddoubledon't have the same precision.0.1fis of typefloat. Why it works with0.5is because0.5has an exact representation in bothfloatanddouble(in binary IEEE-754) types.
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 could anyone explain me please what does this piece of code mean? ``` int **d= (int**)malloc((m+1)*sizeof(...
``` int** d; //pointer to a pointer to an integer ```
I am trying to compile a simple c++ program but the include file is not being added to the compile command. Here is the code ``` #include <stdlib.h> #include "GLES2/gl2.h" int main() { return 0; } ``` SConstruct ``` env = Environment() cpp_path = ''' . include ''' env.Append(CPPPATH = Split(cpp_path))...
Found the problem. Had to do this instead ``` env.Program("test_gcc_scons.c") ```
``` int firstInt =10; int *pointerFirstInt = &firstInt; printf("The address of firstInt is: %u", &firstInt); printf("\n"); printf("The address of firstInt is: %p", pointerFirstInt); printf("\n"); ``` The above code returns the following: ``` The address of firstInt is: 1606416332 The address of firstInt is: 0x7fff...
The reason for this is lies here: C11: 7.21.6: If a conversion specification is invalid,the behavior is undefined.288)If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
strlenreturns the number of characters that precede the terminating null character. An implementation ofstrlenmight look like this: ``` size_t strlen(const char * str) { const char *s; for (s = str; *s; ++s) {} return(s - str); } ``` This particular implementation dereferencess, wheresmay contain indeter...
Calling the standard functionstrlencauses undefined behaviour.DR 451clarifies this: library functions will exhibit undefined behavior when used on indeterminate values For a more in-depth discussionsee this thread.
I useLinuxand compile the C programs usinginbuilt gcc compiler. While creating a program that is for the Windows platform I had to use certain predefined functions listed in<windows.h>. Similarly there are other functions whose libraries are not predefined inGCCcompiler. So how to add those customized libraries to the...
I guess you mean static libraries when you say libraries. You can include the library file path in your gcc command so that gcc can link your library or you can create a makefile and use 'make'. if you don't know how to use 'make' I recomend you to learn it.
This program accepts a finite amount of integers and outputs them using a macro provided by va_arg. (stdargs) ``` #include <stdlib.h> #include <stdarg.h> #include <stdio.h> void main() { foo(5,3,4); } void foo(int i,...){ va_list argp; va_start(argp,i); int p; while ((p = va_arg(argp,int))!= NULL)printf("%d",p)...
You need to pass an explicit last value and stop on that, becauseva_argis not able to detect the end of the arguments. ``` #include <stdarg.h> #include <stdio.h> void foo(int i, ...) { va_list argp; va_start(argp, i); do { printf("%d\n", i); } while ((i = va_arg(argp, int)) != -1); va_end(argp); } int...
When I mean identifier I mean a name appended after the semi-column of the struct- as seen below: ``` item struct [<tag_identifier>] { <type_specifier> <identifier>; <type_specifier> <identifier>; } [<identifier>[, <identifier> ``` Take a look at this struct and notice 'List' appended at th...
``` typedef struct list{ int value; struct list *next; } List; ``` declaresstruct listtype and declaresListas a type alias for typestruct list. ``` typedef struct list{ int value; struct list *next; }; ``` declaresstruct listtype but does not declare any type alias. It is valid but the use oftypedefi...
``` int main() { int a,i; char b; for(i=0;i<3;i++) scanf("%c %d",&a,&b); ``` } The program only scans twice (each for char and int) and then terminates. OUTPUT r 3 4 t Now program is terminating rather than scanning two more times(one char and one int)
``` scanf(" %c %d",&a,&b); ``` solves the problem
Why changing string characters causes segmentation fault(core dumped): ``` char *str = "string"; str[0] = 'S'; //segmentation fault(core dumped) ```
The solution is simple, declare your string in the following way instead ``` char str[] = "string"; ``` The reason why you should do this is because of theUndefined behavior. Creating a string with pointers will make your string locate at theread onlymemory part, so you cannot modify it, whereas another way will als...
I want to calculate(a*b*c*d/e)%mwhere mya,b,c,d,eare of order10^18.eperfectly dividesa*b*c*d. The problem is that I cannot multiply them, as I won't be able to store them as they would be of the range(10^72). Again, I can't take modulus first either? What should I do?
Using the modular arithmetic properties and thatedividea*b*c*d. Also assuming thatm*mdon't overflow in the type of data used. Asmodular arithmeticstate: ifa1 = b1 mod nanda2 = b2 mod nthen: ``` a1 + a2 = b1 + b2 mod n a1 - a2 = b1 - b2 mod n a1 * a2 = b1 * b2 mod n ``` Thedivisionis not here. By this you couldnotu...
strlenreturns the number of characters that precede the terminating null character. An implementation ofstrlenmight look like this: ``` size_t strlen(const char * str) { const char *s; for (s = str; *s; ++s) {} return(s - str); } ``` This particular implementation dereferencess, wheresmay contain indeter...
Calling the standard functionstrlencauses undefined behaviour.DR 451clarifies this: library functions will exhibit undefined behavior when used on indeterminate values For a more in-depth discussionsee this thread.
I useLinuxand compile the C programs usinginbuilt gcc compiler. While creating a program that is for the Windows platform I had to use certain predefined functions listed in<windows.h>. Similarly there are other functions whose libraries are not predefined inGCCcompiler. So how to add those customized libraries to the...
I guess you mean static libraries when you say libraries. You can include the library file path in your gcc command so that gcc can link your library or you can create a makefile and use 'make'. if you don't know how to use 'make' I recomend you to learn it.
This program accepts a finite amount of integers and outputs them using a macro provided by va_arg. (stdargs) ``` #include <stdlib.h> #include <stdarg.h> #include <stdio.h> void main() { foo(5,3,4); } void foo(int i,...){ va_list argp; va_start(argp,i); int p; while ((p = va_arg(argp,int))!= NULL)printf("%d",p)...
You need to pass an explicit last value and stop on that, becauseva_argis not able to detect the end of the arguments. ``` #include <stdarg.h> #include <stdio.h> void foo(int i, ...) { va_list argp; va_start(argp, i); do { printf("%d\n", i); } while ((i = va_arg(argp, int)) != -1); va_end(argp); } int...
When I mean identifier I mean a name appended after the semi-column of the struct- as seen below: ``` item struct [<tag_identifier>] { <type_specifier> <identifier>; <type_specifier> <identifier>; } [<identifier>[, <identifier> ``` Take a look at this struct and notice 'List' appended at th...
``` typedef struct list{ int value; struct list *next; } List; ``` declaresstruct listtype and declaresListas a type alias for typestruct list. ``` typedef struct list{ int value; struct list *next; }; ``` declaresstruct listtype but does not declare any type alias. It is valid but the use oftypedefi...
``` int main() { int a,i; char b; for(i=0;i<3;i++) scanf("%c %d",&a,&b); ``` } The program only scans twice (each for char and int) and then terminates. OUTPUT r 3 4 t Now program is terminating rather than scanning two more times(one char and one int)
``` scanf(" %c %d",&a,&b); ``` solves the problem
Okay, so I'm writing working on pointers here and I'm not sure how this piece of code works. ``` typedef struct linkedlist { void *obj; struct linkedlist *next; } linkedlist; linkedlist *p; //some code here int *newpointer = (*(int *)(p->next)->obj); //code chunk in question ``` If I need to typecast the v...
``` int *newpointer = (*(int *)(p->next)->obj); //code chunk in question ``` If I need to typecast the void pointer 'obj' in the struct pointed to by p->next (assume it already exists) and copy it to 'newpointer' int pointer, am I doing it right? No. The compiler would have told you that. You don't need all those pa...
I want to print file permission in octal format. I've used the stat system call and a stat structure to retrieve the permission field. All I want to do is print it with the last 4 digits but the field has 6 digits. That is, ``` struct stat s1; stat(somefile, &s1); printf("%o", s1->st_mode); ``` will print out six...
if i understood the question: you need to get only the last 4 digits getting rid of all the rest, then ``` int a = 234348; int b = a & 07777; printf("a = %o\nb = %04o\n", a, b); ``` will output : ``` a = 711554 b = 1554 ``` In your case : ``` printf("%04o", (s1->st_mode & 07777)); ```
I'm looking for the best IDE forC++and foundQtis the best approach anyway. Can I useQt Creatoras an IDE forC++? Obviously this is my learning time and would learn to create GUIs and user interfaces withC++in future. Thanks.
Sure, you can. Here below I show you the screenshot of QtCreator's "New project" form: As you can see you can easily select to create a standard "C++" project (making use ofqmake) or also a standard "C++" project (making use ofcmake). Your plain C++ project can be a simple console application (making use ofcinandc...
Is there a way to tell whereFoocomes from, without grepping every#include? ``` #include "Baz.h" #include "Quuz.h" int main() { Foo n; } ```
I think the easiest way is also the stupidest way: to define it again and get the error ``` #include <iostream> using namespace std; typedef int cout; //<--- just for test int main(){ cout<<"Hi!"<<endl; return 0; } ``` Now when compiling (using gcc) I've got the errors: ``` tt.cpp:8: error: reference to ‘cout...
Is it possible to put all the arguments in a array list and pass to new function? How would I start working that? For example: ``` int arr(char *argv[]); int main(int argc, char *argv[]){ //how do I start? Run the for-loop to get all the arguments from the command line. Then how do I pass to arr function. } int...
``` int arr(char *argv[]); int main(int argc, char *argv[]){ arr(argv+1); return 0; } int arr(char *argv[]){ while(*argv) puts(*argv++); return 1; } ```
How would I convert string to integer without using atoi from arguments given? Here's what I've tried: ``` int main(int argc, char *argv[]){ for(int i = 1; i < argc; i++){ const char *p = argv[i]; int j = 0; while(isdigit(*p)){ j = j * 10 + *p - '0'; p++; ...
You're printing all the intermediate results. Save the printout until after you've completed the while loop. ``` while(isdigit(*p)){ j = j * 10 + *p - '0'; p++; } printf("%d\n", j); ```
I am trying to make a program that ouputs the ENTIRE string from scanf if the string contains a certain word. Why is it that if the input from scanf has spaces in it, the program only outputs the special word and not the entire string if the input contains the word? ``` #include <stdio.h> #include <stdlib.h> #include...
Instead ofscanf(), usefgets()to get the entire line.scanf()will ignore whitespace while looking for a string token (and even then will only read to the next bit of whitespace on the line),fgets()will get everything up to and including the EOL character on the line.
Simply trying to find the median of an array of numbers and I have the following: ``` double median( int* array, int length) { double median; qsort(array, length, sizeof(int), cmpfunc); if((length%2) == 0) { median = (array[(length/2)] + array[(length/2)-...
To printfdoubleuse%finstead of%dformat specifier.
I'm having a problem, couldn't find the solution in the internet. I'm trying to compile and run this code:couchbase example Compiling with: gcc -Wall -g -o main main.c -lcouchbase (It compiles fine). running with: ./main couchbase://127.0.0.1:8092/user1 pass after callinglcb_get_bootstrap_status(instance), it say...
Port 8092 is not the correct port, in fact it is the view API (CAPI, couch API, map reduce etc.) port. You should typically not place the port unless your server is configured to listen on a non standard port in the first place.
Is it possible to put all the arguments in a array list and pass to new function? How would I start working that? For example: ``` int arr(char *argv[]); int main(int argc, char *argv[]){ //how do I start? Run the for-loop to get all the arguments from the command line. Then how do I pass to arr function. } int...
``` int arr(char *argv[]); int main(int argc, char *argv[]){ arr(argv+1); return 0; } int arr(char *argv[]){ while(*argv) puts(*argv++); return 1; } ```
How would I convert string to integer without using atoi from arguments given? Here's what I've tried: ``` int main(int argc, char *argv[]){ for(int i = 1; i < argc; i++){ const char *p = argv[i]; int j = 0; while(isdigit(*p)){ j = j * 10 + *p - '0'; p++; ...
You're printing all the intermediate results. Save the printout until after you've completed the while loop. ``` while(isdigit(*p)){ j = j * 10 + *p - '0'; p++; } printf("%d\n", j); ```
I am trying to make a program that ouputs the ENTIRE string from scanf if the string contains a certain word. Why is it that if the input from scanf has spaces in it, the program only outputs the special word and not the entire string if the input contains the word? ``` #include <stdio.h> #include <stdlib.h> #include...
Instead ofscanf(), usefgets()to get the entire line.scanf()will ignore whitespace while looking for a string token (and even then will only read to the next bit of whitespace on the line),fgets()will get everything up to and including the EOL character on the line.
Simply trying to find the median of an array of numbers and I have the following: ``` double median( int* array, int length) { double median; qsort(array, length, sizeof(int), cmpfunc); if((length%2) == 0) { median = (array[(length/2)] + array[(length/2)-...
To printfdoubleuse%finstead of%dformat specifier.
I'm having a problem, couldn't find the solution in the internet. I'm trying to compile and run this code:couchbase example Compiling with: gcc -Wall -g -o main main.c -lcouchbase (It compiles fine). running with: ./main couchbase://127.0.0.1:8092/user1 pass after callinglcb_get_bootstrap_status(instance), it say...
Port 8092 is not the correct port, in fact it is the view API (CAPI, couch API, map reduce etc.) port. You should typically not place the port unless your server is configured to listen on a non standard port in the first place.
Imagine this: ``` #define PUTVALUE 0x000000000000000F #define SetStr(s) literate(s) #define literate(s) #s ... foo (PUTVALUE, SetStr(PUTVALUE)); ``` How can I make work this, wherefoowants as first parameter a 64 bit integer, and as second parameter a const string with a hexadecimal representation of that integer ...
Oh I figgured just out an awesome way to do so: ``` foo (INT64_C(PUTVALUE), SetStr(PUTVALUE)); ``` Is doing exactly that job.
In the code below: ``` #include <stdio.h> int main(){ char *name; int age; char *gen; printf("Your name:"); scanf("%s",name); printf("Your age:"); scanf("%d",&age); printf("Your gender:"); scanf("%s",gen); printf("*****************\n"); printf("%s is a %d years old %s \n",name,age,gen);...
``` char *name; char *gen; ``` are just char pointer and point nothing. So need to allocate memory for it. You can allocate memory for it like ``` char *name = malloc(100); char *gen = malloc(100); ``` OR define char array with predefined length ``` char name[100]; char gen[100]; ```
Is there a function in C language to calculate directely without using a loop the multiplication of a matrix by a scalar value ?
No. Generally, C only implements type operations. An array is a sequential arrangement of data of a type. Thus it does not have intrinsic operations that collection types may have in other languages, only those that may be performed on each data of whatever type the data is of. i.e.int myArray[5];is an array of integ...
please could you help me understand what's __format in printf prototype for? extern int printf (const char *__restrict __format, ...); How can I find set of these in documentation? Thanks!
as per the ISO/IEC 9899:1999 declaration, int printf(const char * restrict format, ... ); using the__is a variable nomenclature.
I use KEIL to compile a program. The program uses the code asm("NOP"); Unfortunately KEIL compiler does not accept the statement. The idea is to introduce a delay by using NOP (no operation) assembly code. What is the actual equivalent of this in C ? Does this vary with the embedded controller that I use?
There's an intrinsicnopin most compilers, Keil should have this as well - try__nop() See -https://www.keil.com/support/man/docs/armcc/armcc_chr1359124998347.htm Intrinsic functions are usually safer than directly adding assembly code for compatibility reasons.
What is the difference between the following declarations in C? static int foo(){}int static foo(){} As I understand the first format is used and subscribed in text books while the second nonetheless seems to work as well. Are the declarations equivalent?
They are the same but the first form is preferred: (C99, 6.11.5p1) "The placement of a storage-class specifier other than at the beginning of the declaration specifiers in a declaration is an obsolescent feature"
I am working in a space limited environment. I collect an array of unsigned 32 bit ints via DMA, but I need to work on them as single precision floats using DSP extensions in the MCU. Copying the array is not possible - it takes up almost all existing SRAM. Is there a neat way to do this? [Note] The data values are o...
You can just do it like this: ``` uint32_t a[N]; float *f = (float *)a; for (i = 0; i < N; ++i) { f[i] = (float)a[i]; } ``` Note that this breaks strict aliasing rules so you should compile with-fno-strict-aliasingor equivalent.
I need to make it so that the content of two structs will be inside a single buffer the size of the two structs. I need to use memcpy to do so. This is my current code: ``` struct Header header; struct Data_Format DF; char *buffer[28]; header.Start = 0x7E; header.Options = 0x00; DF.Address = 0x007CB; DF.Result = ...
Try this: ``` char buffer[sizeof(header)+sizeof(DF)]; ... memcpy(buffer,&header,sizeof(header)); memcpy(buffer+sizeof(header),&DF,sizeof(DF)); ```
I am running this example (from Kernighan and Ritchie's C book section 1.5.2) on a mac OS X machine terminal: ``` #include <stdio.h> int main() { int c, nl; nl = 0; while((c = getchar()) != EOF) if(c == '\n') ++nl; printf("%d\n", nl); } ``` I run the app and enter the EOF chara...
I bet the terminal is showing a^D(normal caret notation) and leaving the cursor on the caret, then your program is printing0\nbecausenlis 0 overwriting the caret. Adding asleep(5)before the finalprintfshould confirm this.
I want to extract file nameLicense.xmlfrom the string through functionsscanf_s ``` Content-Disposition: form-data; name="file"; filename="C:\share\file1\License.xml" ``` Currently, I just know to match the whole file name by ``` char file_name[256] = {""}; sscanf_s( line, "Content-Disposition: form-data; name=\"fil...
``` char *line ="Content-Disposition: form-data; name=\"file\"; filename=\"C:\\share\\file1\\License.xml\""; char file_name[256] = {""}; char *p; sscanf_s( line, "%*s %*s %*s filename=\"%[^\"]\"", file_name, sizeof(file_name)); p = strrchr(file_name, '\\')+1; memmove(file_name, p, strlen(p)+1); puts(file_name);//Licen...
I'm dealing with a dynamically allocated matrix. In particular I have this code (in C): ``` int i, n, m; char **matrix; matrix = (char **)calloc((n, sizeof(char *)); for (i = 0; i <= n; ++i) { matrix[i] = (char *)calloc(m, sizeof(char)) } ``` If 'n' is little enough the program works well but if I increase it dr...
INT_MAXis 2gb of ram. You're using up that much ram for each row, hence your matrix exceeds your ram capacity.
I am learning C and part of my exercise is dealing with bitwise operators. I am trying to create a function that prints out a 2's complement for a char input. Here is what I have so far: ``` #include <stdio.h> #include <stdlib.h> void find_binary(char ch) { long bit_index = 0; unsigned long sz = s...
The expression ``` int bit = (1 << bit_index) & ch; ``` produces a zero or a power of two with the corresponding bit set. To bring it into the 0..1 range, either shiftchright and mask with1, or convert your expression as follows: ``` int bit = ((1 << bit_index) & ch) != 0; ```
In the code below: ``` #include <stdio.h> struct { int Member1 : 3; int Member2 : 1; }d2; int main(){ d2.Member1 = 7; printf("%d\n",d2.Member1); return 0; } ``` The result is-1, why is it? What's the binary value of thed2now?
Because you did not specify ifd2.Member1is signed or unsigned, it is up to the compiler and apparently the one you are using chose to make it a signed field, and therefore has the range -4 to 3. 7 is out of range, so it overflows. Maked2.Member1anunsigned intinstead, and use%uin yourprintf()call instead of%d. (Demo....
I am trying to figure out how to detect the negative numbers in argc (in c). Code: ``` int main(int argc, char *argv[]){ printf("\n"); for(int i = 0; i < argc; i++){ printf("%s\n", argv[i]); //print what typed in the command line (arguments) //do an if statement here? if less than zero, any h...
Just add this condition beforeprintfstatement in the loop ``` if(argv[i][0] == '-') { printf("Sorry, you have negative value. \n"); exit (0); } ```
Is memsetting a pointer in an array ok or am I just overwriting the pointers to the elements here? Is it better when I memset the whole memory area or the elements in the array? For example: ``` .... struct pollfd fds[2]; int tmp = 0; for(; tmp < sizeof(fds[0])/sizeof(fds); tmp ++) { memset(fds[tmp], 0x00, siz...
Not sure whether you have already tested your code. But the arguments tomemsetare incorrect. First method: Use ``` memset(&fds[tmp], 0x00, sizeof(fds[tmp])); // ^ Missing & ``` instead of ``` memset(fds[tmp], 0x00, sizeof(fds[tmp])); ``` Second method: Use ``` memset(fds, 0x00, sizeof(fds)); ...
I am learning C and part of my exercise is dealing with bitwise operators. I am trying to create a function that prints out a 2's complement for a char input. Here is what I have so far: ``` #include <stdio.h> #include <stdlib.h> void find_binary(char ch) { long bit_index = 0; unsigned long sz = s...
The expression ``` int bit = (1 << bit_index) & ch; ``` produces a zero or a power of two with the corresponding bit set. To bring it into the 0..1 range, either shiftchright and mask with1, or convert your expression as follows: ``` int bit = ((1 << bit_index) & ch) != 0; ```
In the code below: ``` #include <stdio.h> struct { int Member1 : 3; int Member2 : 1; }d2; int main(){ d2.Member1 = 7; printf("%d\n",d2.Member1); return 0; } ``` The result is-1, why is it? What's the binary value of thed2now?
Because you did not specify ifd2.Member1is signed or unsigned, it is up to the compiler and apparently the one you are using chose to make it a signed field, and therefore has the range -4 to 3. 7 is out of range, so it overflows. Maked2.Member1anunsigned intinstead, and use%uin yourprintf()call instead of%d. (Demo....
I am trying to figure out how to detect the negative numbers in argc (in c). Code: ``` int main(int argc, char *argv[]){ printf("\n"); for(int i = 0; i < argc; i++){ printf("%s\n", argv[i]); //print what typed in the command line (arguments) //do an if statement here? if less than zero, any h...
Just add this condition beforeprintfstatement in the loop ``` if(argv[i][0] == '-') { printf("Sorry, you have negative value. \n"); exit (0); } ```
Is memsetting a pointer in an array ok or am I just overwriting the pointers to the elements here? Is it better when I memset the whole memory area or the elements in the array? For example: ``` .... struct pollfd fds[2]; int tmp = 0; for(; tmp < sizeof(fds[0])/sizeof(fds); tmp ++) { memset(fds[tmp], 0x00, siz...
Not sure whether you have already tested your code. But the arguments tomemsetare incorrect. First method: Use ``` memset(&fds[tmp], 0x00, sizeof(fds[tmp])); // ^ Missing & ``` instead of ``` memset(fds[tmp], 0x00, sizeof(fds[tmp])); ``` Second method: Use ``` memset(fds, 0x00, sizeof(fds)); ...
Following code is supposed to return the upper case string of the source. It works but does not convert the string. Could not figure out what was wrong. ``` char *StrUpper (char *s) { int i = 0; char *t = &s [i]; while (*t) { if ((*t > 0x5a) && (*t < 0x7b)) t = (t - 32); t = &s [i++]; ...
A string literal is a constant pointer to an array of constant characters. In other words, string literals areread only. Trying to modify constant data leads toundefined behavior. And if your program haveundefined behavior, nothing about its behavior can be trusted at all.
I have a code that looks somewhat like this: ``` int num = 5; int *ptr = &num; void **xptr = &ptr; printf ("values:%d\n",**(int *)xptr); ``` Why can't i de-reference a void double pointer,which points to an int pointer ? The below two examples work. Snippet:1 ``` int *ptr = &num; int **xptr = &ptr; printf ("value...
void **is not a generic pointer unlikevoid *. Anyvoid **value you play with must be the address of an actualvoid *value somewhere. Compiler should raise a warning forvoid **xptr = &ptr;: ``` [Warning] initialization from incompatible pointer type [enabled by default] ``` You can do it as follows ``` int num = 5; vo...
I have charbyte[0] = '1' (H'0x31)andbyte[1] = 'C'(H'0x43) I am using one more buffer to more buffchar hex_buff[0].i want to have hex content in thishex_buff[0] = 0x1C(i.e combination of byte[0] and byte[1]) I was using below code but i realized that my code is valid for the hex values 0-9 only ``` char s_nibble1 =...
What keeps you from usingstrtol()? ``` char bytes[] = "1C"; char buff[1]; buff[0] = strtol(bytes, NULL, 16); /* Sets buff[0] to 0x1c aka 28. */ ``` To add this as perchux's comment:strtol()only operates on0-terminated character arrays. Which does not necessarily needs to be the case for the OP's question.
I am a beginner in programming but I am more familiar with python and bash and if I want to use bash in python I would just useimport osand to use bash I would useos.system("#code#"). How do I do that in C? I am using linux mint 17.
i think you can use the system() call to execute the shell script. something like this ``` int main() { system("echo hello"); //system("your shell script") } ``` so u can store your shell script in a file, open the file in c, read it line by line and execute it..
I am practicing some C questions came across a scenario where a recursive function calls itself with an expression as an argument. ``` Pow(double x, unsigned n){ ..... ..... return Pow(x*x,n/2); } ``` My question is whether the arguments are passed when evaluating the expression (x*x, as in call by value) or...
All the arguments of a function in C are evaluated right before the function is called. Evaluations and calls in your example: ``` Pow(5, 12) = Pow(5 * 5, 6) = Pow(25, 6) = Pow(25 * 25, 3) = Pow(625, 3) = Pow(625 * 625, 1) * 625 ```
I want to do something similar to this in C language: ``` # This example is in Python language var1 = 10 var2 = 45 var3 = 76 text = "Numbers are: %d, %d, %d." % (var1, var2, var3) ``` Is this possible in C? I want to say a solution for pure C, not C++. EDIT: I don't want to print the string directly, I only want...
Usesnprintf() ``` int var1 = 10; int var2 = 45; int var3 = 76; char text[100]; snprintf(text, sizeof text, "Numbers are: %d, %d, %d.", var1, var2, var3); ```
I'm joining two simple strings usingglib-2.0. Here is my code: ``` int main() { gchar *a = "12"; gchar *b = "1231212"; printf("a: %s\n", a); printf("b: %s\n", b); gchar *c = g_strjoin(",", a, b); printf("c: %s\n", c); return EXIT_SUCCESS; } ``` It crashes atg_strjoin(",", a, b). Core f...
Asg_strjoin()can join an arbitrary number of strings, the list has to be terminated withNULL: ``` gchar *c = g_strjoin(",", a, b, NULL ); ```
This question already has answers here:What does this do? [duplicate](4 answers)Closed9 years ago. I got a line in the generic code of stm32f0 so often and I can't get it clearly. what does it mean by the line below. I know its complicated to understand this way. But my point is thequestion mark(?)in the define. Can ...
it is a short form of condition, you can write ``` int k = (i > j) ? i : j; ``` this will asign i to k ifi > jelse it will asign j. this is the way we choose between two options inside a macro
I have a few defines in C: ``` #define My_CheckButton_1 "Check1" #define My_CheckButton_2 "Check2" #define My_CheckButton_3 "Check3" ``` I would like to add all the My_CheckButton_x to an enum, so I can run on all of them in a loop. How can I do it? Thanks
An enum has integral type in C, so you will not get the string value if you move them to an enum, but an integral value. If you need the string values, you will need a function to do the enum-to-string conversion. It is not the same, but maybe using an array could be an alternative: ``` static const char *My_CheckBut...
I am trying to profile a program usinggprof. The point is that for some cases the program does not finish by itself but by using the Linux execution time limit. In this case the file 'gmon.out' is not generated. I was wondering if there exists a way to get some kind of profiling information even in the case that the ...
If you know for sure, that you don't have a sginal handling for a certain signal, let's saySIGTERM, you could add a signal handler that callsexit(). Then you could terminate your program withkill -SIGTERM pidandgmon.outshould be created.
I want to store a string in char array I am trying to do so by using amemcpy()but I am getting asegmentation fault. Can someone explain why? And what could be the correct way of doing this. What would be better to usechar * name;orchar name[100];? ``` #include <stdio.h> struct A { char * name; }; typedef struct ...
You have to allocate memory for structure and it's member and then after you can do copy data in it. ``` A *a = malloc(sizeof(A)); a->name=malloc(100); //change the size other then 100 what ever you want. ```
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed9 years ago.Improve this question I have this code in ...
In Windows search MSDN for LoadLibrary or LoadLibraryEx. In Linux do aman dlopenin your console or search online.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed8 years ago.Improve this question Which of the following system calls can return EINTR or EAGAIN/EWOULDBLOCK? ``` getsockn...
I have found the answer. This question should not have been deleted. As a rule only syscalls which are "slow" return EINTR. Slow things are terminal I/O and things which wait (select, wait, sleep, pause, etc).
``` #include <stdio.h> #include <stdlib.h> const int N = 5; int main() { int vett[N] = {1, 2, 3, 4, 5}; return 0; } ``` What is the problem in this part of code? the compiler report me these error and warnings: ``` error: variable-sized object may not be initialized warning: excess elements in array initia...
Unlike C++, even withconst int N = 5,Nis not considered as a constant expression in C. Soint vett[N]is not a normal (fixed length) array, it's a variable length array. In this case, you should still use: ``` #define N 5 ```
I have a question reading a txt file containing float value. I have seen some tutorials about reading txt files and all of them soo far are either using fgetc or fgets to read the content of files. I was looking for some similar function for float as the contents of my file is float. Is there a some way to read file c...
Read each line usingfgets, then depending on how the lines are formatted you could usesscanf()to parse the values, orstrtod().
while reading the book Computer System a programmer perspective.I have found that if i take most negative value in the range of a data type for example : ``` char a = -128; a = - a; ``` The variable a will still have the value -128 and i understand that but when i do ``` char a = 50; char b = -128; char r = a - b; ...
char a = -128;meanschar a = 0x80;, so at the promotion to int it will be0xFFFFFF80.-0xFFFFFF80=0x00000080and that is casted to an char0x80which is the same as the start value. ``` char a = -128; char b = 50; char r = a - b; ``` 0xFFFFFF800xFFFFFFCE=0xFFFFFF4E so4Ewill be written inr, which is +78. live demo:https:...
I am trying to profile a program usinggprof. The point is that for some cases the program does not finish by itself but by using the Linux execution time limit. In this case the file 'gmon.out' is not generated. I was wondering if there exists a way to get some kind of profiling information even in the case that the ...
If you know for sure, that you don't have a sginal handling for a certain signal, let's saySIGTERM, you could add a signal handler that callsexit(). Then you could terminate your program withkill -SIGTERM pidandgmon.outshould be created.
I want to store a string in char array I am trying to do so by using amemcpy()but I am getting asegmentation fault. Can someone explain why? And what could be the correct way of doing this. What would be better to usechar * name;orchar name[100];? ``` #include <stdio.h> struct A { char * name; }; typedef struct ...
You have to allocate memory for structure and it's member and then after you can do copy data in it. ``` A *a = malloc(sizeof(A)); a->name=malloc(100); //change the size other then 100 what ever you want. ```
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed9 years ago.Improve this question I have this code in ...
In Windows search MSDN for LoadLibrary or LoadLibraryEx. In Linux do aman dlopenin your console or search online.
I do use to work in Eclipse cause i find it pretty good, but every day i am encountering this problem..."'Cleaning all projects has encountered a problem'. Errors occured during the build." when I hit the "clean projects" button. I have win 7 64 bit. The only solution for this issue to work is to restart my computer....
It's hard to tell for sure, but your application might have some unreleased resources which 'clean' command can't remove. Did executable process terminate? If not, you whould have this error. You could try to remove binaries from build folder manually and see what file causes and error.
This question already has answers here:!! c operator, is a two NOT?(4 answers)Closed9 years ago. While going over infrastructure code, I found this: ``` return !!(fin.flags & FIN_ACCEPT); ``` Does this has a meaning other than two logical nots in succession?
!is logical negation.!!is logical negation applied twice. It is typically used to normalise a boolean expression value to be either0or1.
In the book these is a simple C function: ``` char *month_name(int n) { static char *name[] = { "Illegal month", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; return (n < 1 || n > 12) ? name[0] : name[n]; } ``` What does t...
Its a ternary operator.. ``` condition? a: b ``` this means if condition is true then expression a wil be processed, if its false then b will be processed. In your code, it will check if n is not within the range 1-12 (the number of months). if it is not within the range then it will return name[0] (i.e. illegal mo...
``` #include<stdio.h> int main() { int i,l,*A;char C; A=(int*)malloc(5*4); for(i=0;i<5;i++) scanf("%d",A+i); scanf("%c",&C); scanf("%d",&l); printf("%d%c\n",l,C); return 0; } ``` Input: 5 4 3 3 9 r 1 I expect the output to be 1r. But I am getti...
In your example,%creads the space before ther, and the subsequentscanf("%d")fails to read an integer (since it's presented withr 1). To verify this, examine the return value ofscanf(): it isthe number of items successfully matched and stored, so the finalscanf()will return zero. P.S. In themalloc()(or anywhere else ...
When Idlsym()some library, all the global symbols from my main executable can be accessed if referenced in the code of the library. How can this be avoided? At least no flag fordlsym()seems to offer such feature.
Try making all symbols in your main executable hidden by default. That is, compile with-fvisibility=hiddenand possibly more options as described here:How to apply gcc -fvisibility option to symbols in static libraries? This should make your main executable export no symbols, so there will be nothing for the library ...
I'm writing window managing code in C. When certain flags are set, I want to have a maximized window that cannot be resized by dragging the window by the title bar. Is there a way to 'lock' a maximized window in its maximized state?
Try this ``` case WM_SYSCOMMAND: if(IsMaximized(hwnd) && ((wParam & 0xFFF0) == SC_RESTORE || (wParam & 0xFFF0) == SC_MOVE)){ return 0; } break; ``` Edit The complete code ``` switch(message){ //handle the messages ... ... case WM_SYSCOMMAND: ... break; .... ...
Suppose I have a string "str". My for loop is as follows: ``` for(i=0;i<strlen(str);i++){ //do stuff } ``` question: When the condition is checked ,i < strlen(str), is the strlen(str) part calculated each time the loop runs ? Or it gets stored and is computed for the first time only?
The condition expression in a loop will get evaluated at each and every iteration - ithasto be that way until (ideally) the expression becomes false. So yes:strlen(str)will be calculated over and over again. If the string doesn't change at all, it'll be better if you store its length in a local variable. ``` int n = ...
I am trying to compile a simple hello world program but codeblocks(v 13.12) is always showing meIt seems that this file has not been built yet.Do you want to build it now? I'd used codeblocks(v 13.12) before but never found this problem. I don't know how to solve it. Anybody please help me. Image after creating a ...
You'd see this behavior if you didn't go through the process of creating a Codeblocks C project. You have to use File menu/New/Project in CodeBlocks. Since it is a console app to print out hello world select "Console Application". Then select C or C++, and then fill in the information about the project. Once the proj...
I am trying to computen! % musing recursion inC. This is thecodeI am using ``` #include<stdio.h> #define m 1000000007 long long int fact(long long int n) { if(n == 1) return (1); long long int n2 = (long long int)(fact(n-1)); long long int k = (n*n2)%m; return k; } int main() { printf("%...
try gdb, but likely its because you are reaching your max recursion depth, in other words running out of "memory" either literally or based on current rule sets for your os.
Suppose I have a string "str". My for loop is as follows: ``` for(i=0;i<strlen(str);i++){ //do stuff } ``` question: When the condition is checked ,i < strlen(str), is the strlen(str) part calculated each time the loop runs ? Or it gets stored and is computed for the first time only?
The condition expression in a loop will get evaluated at each and every iteration - ithasto be that way until (ideally) the expression becomes false. So yes:strlen(str)will be calculated over and over again. If the string doesn't change at all, it'll be better if you store its length in a local variable. ``` int n = ...
I am trying to compile a simple hello world program but codeblocks(v 13.12) is always showing meIt seems that this file has not been built yet.Do you want to build it now? I'd used codeblocks(v 13.12) before but never found this problem. I don't know how to solve it. Anybody please help me. Image after creating a ...
You'd see this behavior if you didn't go through the process of creating a Codeblocks C project. You have to use File menu/New/Project in CodeBlocks. Since it is a console app to print out hello world select "Console Application". Then select C or C++, and then fill in the information about the project. Once the proj...
I am trying to computen! % musing recursion inC. This is thecodeI am using ``` #include<stdio.h> #define m 1000000007 long long int fact(long long int n) { if(n == 1) return (1); long long int n2 = (long long int)(fact(n-1)); long long int k = (n*n2)%m; return k; } int main() { printf("%...
try gdb, but likely its because you are reaching your max recursion depth, in other words running out of "memory" either literally or based on current rule sets for your os.
I developed a program that makes parameters tracking. I want to inform a server with a http messageover udpwhen a parameter value changes. I want to use libcurl for that. Does libcurl able to send a http message over UDP?
No it doesn't. For HTTP, libcurl only supports TCP or Unix domain socket. It could possibly be something to add in a future. (libcurl supports UDP transfers for a few other protocols.) HTTP/3 HTTP/3 is done over QUIC which is done over UDP, so strictly speaking if you use curl to do a HTTP/3 transfer it will use UD...
i have a file "test.txt" which has a list of numbers, like this ``` 1 3 4 2 3 40 312 53 243 321 423 ...etc ``` I also have an executable which is a sorting algorithm, for example heapsort. when i type ./heapsort it asks me for input untill i press CTRL+D. How can i make that the ./heapsort input is test.txt? I...
Execute you program like this: ``` ./heapsort < test.txt ``` This redirect the standard input to your file. Also you may consider change your program to stop asking for inputs after a certain value or when reach the end of the file.
Scanfshould return the number of characters taken as inputted..but strangely returning only 1 all the time. ``` scanf ("%d",&num_test_cases); for (i=0;i<num_test_cases;i++) { level=scanf ("%s",ch); printf ("\n %s\n",ch); printf ("%lld\n",level); } ``` Sample Input : ``` 4 lrl rll r lllr ``` Output...
In C,scanf()returns number of items successfully read... Actually,printf()returns the number of characters successfully written on the output! So,as your scanf is accepting only 1 input for each iteration,hence,levelvariable in your program is returning 1 as a result in each iteration!
We are trying to useFourier-Motztkinto solve an equation system, to do that we need to sort our matrix by the last element in each row. First we want to have all our rows where the last element is positive, then the negative ones and at last the zeros. When we run the program using valgrind we get an error message th...
Based on how you are usingT, I am assuming that you allocatedrows*colsints for a matrix. So wheni=rows-1the expressionT[i*cols+cols]becomesT[rows*cols], which is off the end of your allocated memory. That expression should beT[i*cols+cols-1]to read the last element of the row. You are actually reading the first ele...
This question already has answers here:Handling large numbers in C++?(10 answers)Closed9 years ago. Is it possible to take an input of range greater than what C/C++ provides? Is it possible to accept an input range greater than that of unsigned long long and even larger up to the range of 10^1000? If it is possible i...
There's no bigint in C or C++, however library like this one can provide it:https://code.google.com/p/infint/
I concatenate my full app version using these macros: ``` #define MAJOR 3 #define BUILD 432 #define CONCATENATE_DIRECT(s1, s2) s1##s2 #define CONCATENATE(s1, s2) CONCATENATE_DIRECT(s1, s2) #define VERSION CONCATENATE(CONCATENATE(MAJOR, .), BUILD) ``` The output should be 3.432 and it worked perfectly until I recen...
I have several different preprocessor flags set and one of them was-traditional. This is the one that messed up things. After removing it everything went back to normal again. The # and ## operators are not available in traditional C. See morehere
Does gcc (latest versions: 4.8, 4.9) have an "assume" clause similar to__assume()built-in supported by icc? E.g.,__assume( n % 8 == 0 );
As of gcc 4.8.2, there is no equivalent of __assume() in gcc. I don't know why -- it would be very useful. mafso suggested: ``` #define __assume(cond) do { if (!(cond)) __builtin_unreachable(); } while (0) ``` This is an old trick, known at least as far back as 2010 and probably longer. The compiler usually optim...
Why addition of two pointers not supported in c or c++. When I do, ``` int *ptr,*ptr1; int sum = ptr + ptr1; ``` C or C++ throws an error. While it supports, ``` int diff = ptr - ptr1; ```
Pointers contain addresses. Adding two addresses makes no sense, because you have no idea what you would point to. Subtracting two addresses lets you compute the offset between these two addresses, which may be very useful in some situations. Edit: To address the common wish for finding the mid consider this (purely ...
``` struct tree{ #ifdef A #define TREE_GET(x,y) &x->y #else #define TREE_GET(x,y) x->y #endif }; ``` I want to know whether macro A was defined . Is there any command I can use in gdb .
In compilation time we pass the -gdwarf-2 and -g3 flags to ensure the compiler includes information about preprocessor macros in the debugging information. For example,g++ -gdwarf-2 -g3 program.cpp -o program C Preprocessor Macros
Both methods work but which one is the faster/performant in the caseptr == NULL? ``` void voo() { str *ptr = NULL; // try to malloc memory and do something // leaving methode and free the memory if(ptr != NULL) { free(ptr); ptr = NULL; } } ``` Do I need anifquery at all if I leave t...
From C standard, 7.20.3.2/2, ifptrisNULLthenfree(ptr)does nothing. It's therefore pointless for you to check this, from both performance and superfluous code perspectives.
Does gcc (latest versions: 4.8, 4.9) have an "assume" clause similar to__assume()built-in supported by icc? E.g.,__assume( n % 8 == 0 );
As of gcc 4.8.2, there is no equivalent of __assume() in gcc. I don't know why -- it would be very useful. mafso suggested: ``` #define __assume(cond) do { if (!(cond)) __builtin_unreachable(); } while (0) ``` This is an old trick, known at least as far back as 2010 and probably longer. The compiler usually optim...
Why addition of two pointers not supported in c or c++. When I do, ``` int *ptr,*ptr1; int sum = ptr + ptr1; ``` C or C++ throws an error. While it supports, ``` int diff = ptr - ptr1; ```
Pointers contain addresses. Adding two addresses makes no sense, because you have no idea what you would point to. Subtracting two addresses lets you compute the offset between these two addresses, which may be very useful in some situations. Edit: To address the common wish for finding the mid consider this (purely ...