question
stringlengths
25
894
answer
stringlengths
4
863
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. I have noticed that using F10 - Ste...
It is annoying, especially if you happen to call several functions just to get parameters into yours. You can use step out (Shift+F11) to quickly get out of uninteresting code. (and then F11 to get into the next one)
``` #include<stdio.h> #include<stdlib.h> #define d 10+10 int main() { printf("%d",d*d); return 0; } ``` I am new to the concept of macros.I found the output for the above program to be 120.What is the logic behind it? Thanks.
``` 10+10*10+10 == 10 + 100 + 10 ``` Is that clear?
For example I have ``` *line[30]; ``` I want to allocate a string 81 characters for each pointer. How can I do that and in which way can I access the second string for example to use it in a printf? Also what about**a, is it an equivalent? I'm a newbie and this may be an easy question, but I'm eager to learn. Than...
I want to allocate a string 81 characters for each pointer Since you know the exact size you want, you can do this statically: ``` char line[30][81]; ``` This gives you 30 arrays of 81 characters. ``` strcpy(line[0], "hello"); strcpy(line[1], "world"); printf("%s\n", line[1]); // prints the second string ```
I'm trying to think of a function in C that would satisfy the following conditions: It accepts an integer greater than 0 as an argument;It rounds that integer up to the nearest value so that only the first digit is not a zero For example: 53 comes out as 60..197 comes out as 200..4937 comes out as 5000.. Is there ...
Avoid string conversions and loops: ``` int num = ... // your number int len = log10(num); float div = pow(10, len); int rounded = ceil(num / div) * div; ```
I would like to know how i can pass a pointer to a function to another function as a parameter, only the function that i wish to pass has multiple parameters. For example, my main function: ``` void main_func(float **D, float **w , int n, Pointer_to_func) ``` The function that i want to pass: ``` float func(int x_1...
Or without a typedef (just for completeness, you generally do want the typedef): ``` void main_func(float **D, float **w , int n, float (*callback)(int, int, int, int, int)); ```
I need to convert a char array to string. Something like this: ``` char array[20]; char string[100]; array[0]='1'; array[1]='7'; array[2]='8'; array[3]='.'; array[4]='9'; ... ``` I would like to get something like that: ``` char string[0]= array // where it was stored 178.9 ....in position [0] ```
You're saying you have this: ``` char array[20]; char string[100]; array[0]='1'; array[1]='7'; array[2]='8'; array[3]='.'; array[4]='9'; ``` And you'd like to have this: ``` string[0]= "178.9"; // where it was stored 178.9 ....in position [0] ``` You can't have that. A char holds 1 character. That's it. A "st...
I wan to define enum with non constant step. I want that the step between 2 enum variables looks like that: ``` enum test { a1 = 1, a2 = 1<<2, a3 = 1<<3, a4, // a4 deduced automatically as 1<<4 a5 // a5 deduced automatically as 1<<5 } ``` Are there a way to define it as indicated in the above example?...
You must do this manually, or possibly with macro chicanery.
This question already has answers here:Closed10 years ago. Possible Duplicate:length of array in function argument I am trying to get the length of an integer array but i am not getting the right answer ``` void main() { int x[]={33,55,77}; printf("%d",getLength(x));//outputs 1 printf("%d",sizeof(x)/siz...
Because arrays aren't pointers, and pointers aren't arrays.sizeof(pointer)is not the same assizeof(the array which the pointer points to).
I want to access several variables of the form: ``` int arr1=1; int arr2=1; int arr3=1; ``` So I wrote ``` #define arr(i) arr##i ``` but following code piece doesnt work as i expect ``` #include <stdio.h> int main(){ int arr1=1; int arr2=1; int arr3=1; int j; for(j=1; j<3; j++) printf("%d",arr(j)); ...
You cannot do this. Variable names don't exist at runtime in C. Your macro will expand toarrj, which is an undefined variable name. Use a proper array: ``` int arr[] = { 1, 1, 1 }; ``` then printarr[j], but loop like this: ``` for(j = 0; j < sizeof arr / sizeof *arr; ++j) printf("%d\n, arr[j]); ```
``` double *f(int n, double v) { double *a, *p; a = malloc(n * sizeof(double)); if (a != NULL) for (p = a; p < a + n; p++) *p = v; return a; } ``` Can you explain me what this function is needed for? Does it copy the content of v in n? If yes, why does it return a? I really don't get it... Thanks in...
It returns a newly allocateddoublearray of sizenfilled with valuev, orNULLif the allocation fails. This loop: ``` for (p = a; p < a + n; p++) *p = v; ``` uses pointer arithmetic. Aspis a pointer to adouble, incrementing it will point to the next double to write.*p = vwrites the double at the specified location....
``` #ifndef HW4Q2_H_INCLUDED #define HW4Q2_H_INCLUDED #define MAX_WORD_LEN 10 struct dict{ int len; char (*dict0)[MAX_WORD_LEN+1]; char (*dict1)[MAX_WORD_LEN+1]; }; void translate(char* currWord, char* newWord, struct dict* myDict, int lang); void createDict(struct dict* myDict); void destroyDict(struct ...
You should play around withcdecl, it helps in parsing things like this. If you substitute a number for theMAX_WORD_LEN+1expression (such as 11), it says: declare dict0 as pointer to array 11 of char So that is what that code means; it declaresdict0as a pointer to achararray with sizeMAX_WORD_LEN + 1, i.e. 11.
Hello i have simply function to read from file ``` while(fscanf(fp," %255[a-zA-Z]",test) == 1) { puste = 1; push(&drzewo,test); } ``` It should read only words which contains only alphabetic characters and that works great. When I have for example a single number in my file my while loop quits; how should I...
Of course it stops, since thefscanf()call will fail to do the conversion you're requiring, and thus return 0. What would you expect it to do? It's often better to read whole lines usingfgets(), and then parse them "manually", that way it's easy to just do nothing and read another line if the desired data is not found...
Does an equivelent to C++'s placement new exist in C? I mean, can an object be constructed at a specified location in C? Canrealloc()be used for that?
Placement new simply skips allocation and constructs an object in preallocated memory. Since C lacks constructors, there is no need for placement new. I suppose the equivalent would be a pointer typecast, because once you have a pointer, you can act as if an object exists. Example of carving objects of differing type...
I need to pipe 3 programs: AddWith5.c AddWith2.c MultiplyWith3.c My code follows this pattern: ``` int main(){ int x; scanf("%i",&x); printf("%i",x*3); return 0; } ``` I need to pipe them so that I get the output for: ((x+5)+2)*3 (f1.txt contains the number 2) Can someone help me? I tried:AddWith...
Pipes are read left to right, so the input must be given to the "head" (the leftmost) program in the pipe: ``` $ AddWith5 < f1.txt | AddWith2 | MultiplyWith3 ``` Also, you don't invoke C files directly, each file needs to be individually compiled into a binary with the above names, first. This has, by the way, noth...
I want to print only n first elements from bst tree so i added global variable counter ``` int a = 0; void print (wezel **korzen,int x) { if((*korzen) != NULL && (a < x)) { print( &((*korzen)->lewe),x ); a++; printf("%s %d\n", (*korzen)->wartosc, (*korzen)->ile); print( &((*ko...
As I mentioned in my comments, you don't check a after the first print: ``` int a = 0; void print (wezel **korzen,int x) { if((*korzen) != NULL && (a < x)) { print( &((*korzen)->lewe),x ); // A has incremented since last check if (a < x) { printf("%s %d\n", (*korzen)->warto...
I have an integer returning from a function: ``` int a = func(); ``` For example,a = 236. I need to treat this as a hexadecimal representation of an integer, and store itsdecimalrepresentation in another variable, so that when printed like so: ``` printf("%x", variable) ``` ...the output should be: ``` 236 ```
All the values will be stored in binary format only. If you want to print the value in decimal formal print using%dformat string or if you want to print the value in hexa decimal then print using%x. Sameway we can assign the values in decimal and hexadecimal format also. ``` int a = 236; int b = 0x236; printf("%d", ...
I have a structure and want to increase an array size whenever SendMessage function calls ``` struct MQStruct { wchar_t *serviceName; int durability; int msgType; int msgHeader; wchar_t *msgId; wchar_t *payload; int payloadSize; int ttl; int priority; }MQStructObj[1]; int...
In C you will have to deal with dynamic memory (i.e allocate the array usingmalloc(), then take care to callfree()when you stop using it etc.) yourself, and possibly userealloc()to grow an allocation. In C++ the problem is already solved for you and you havestd::vector. You may callpush_backto add elements dynamicall...
I was hoping to be able to scan a string with this format ``` "hello world !!!!" ``` to ``` {"hello world", "!!!!"} ``` This 2 strings are separated with more than 1 space. Can I parse this or at least detect 2 consecutive spaces in scanf?
This code could help you ``` #include<stdio.h> #include<stdlib.h> #include<string.h> int main() { char a_buf[5][100] = {0}, sep[3] ,*buf = a_buf[0]; int i = 0; buf = a_buf[0]; while (scanf("%s%2[ ]",buf,sep) > 1) { if (strlen(sep)==1) { buf += strlen(buf); *buf...
I wan to define enum with non constant step. I want that the step between 2 enum variables looks like that: ``` enum test { a1 = 1, a2 = 1<<2, a3 = 1<<3, a4, // a4 deduced automatically as 1<<4 a5 // a5 deduced automatically as 1<<5 } ``` Are there a way to define it as indicated in the above example?...
You must do this manually, or possibly with macro chicanery.
This question already has answers here:Closed10 years ago. Possible Duplicate:length of array in function argument I am trying to get the length of an integer array but i am not getting the right answer ``` void main() { int x[]={33,55,77}; printf("%d",getLength(x));//outputs 1 printf("%d",sizeof(x)/siz...
Because arrays aren't pointers, and pointers aren't arrays.sizeof(pointer)is not the same assizeof(the array which the pointer points to).
I want to access several variables of the form: ``` int arr1=1; int arr2=1; int arr3=1; ``` So I wrote ``` #define arr(i) arr##i ``` but following code piece doesnt work as i expect ``` #include <stdio.h> int main(){ int arr1=1; int arr2=1; int arr3=1; int j; for(j=1; j<3; j++) printf("%d",arr(j)); ...
You cannot do this. Variable names don't exist at runtime in C. Your macro will expand toarrj, which is an undefined variable name. Use a proper array: ``` int arr[] = { 1, 1, 1 }; ``` then printarr[j], but loop like this: ``` for(j = 0; j < sizeof arr / sizeof *arr; ++j) printf("%d\n, arr[j]); ```
``` double *f(int n, double v) { double *a, *p; a = malloc(n * sizeof(double)); if (a != NULL) for (p = a; p < a + n; p++) *p = v; return a; } ``` Can you explain me what this function is needed for? Does it copy the content of v in n? If yes, why does it return a? I really don't get it... Thanks in...
It returns a newly allocateddoublearray of sizenfilled with valuev, orNULLif the allocation fails. This loop: ``` for (p = a; p < a + n; p++) *p = v; ``` uses pointer arithmetic. Aspis a pointer to adouble, incrementing it will point to the next double to write.*p = vwrites the double at the specified location....
``` #ifndef HW4Q2_H_INCLUDED #define HW4Q2_H_INCLUDED #define MAX_WORD_LEN 10 struct dict{ int len; char (*dict0)[MAX_WORD_LEN+1]; char (*dict1)[MAX_WORD_LEN+1]; }; void translate(char* currWord, char* newWord, struct dict* myDict, int lang); void createDict(struct dict* myDict); void destroyDict(struct ...
You should play around withcdecl, it helps in parsing things like this. If you substitute a number for theMAX_WORD_LEN+1expression (such as 11), it says: declare dict0 as pointer to array 11 of char So that is what that code means; it declaresdict0as a pointer to achararray with sizeMAX_WORD_LEN + 1, i.e. 11.
Hello i have simply function to read from file ``` while(fscanf(fp," %255[a-zA-Z]",test) == 1) { puste = 1; push(&drzewo,test); } ``` It should read only words which contains only alphabetic characters and that works great. When I have for example a single number in my file my while loop quits; how should I...
Of course it stops, since thefscanf()call will fail to do the conversion you're requiring, and thus return 0. What would you expect it to do? It's often better to read whole lines usingfgets(), and then parse them "manually", that way it's easy to just do nothing and read another line if the desired data is not found...
Does an equivelent to C++'s placement new exist in C? I mean, can an object be constructed at a specified location in C? Canrealloc()be used for that?
Placement new simply skips allocation and constructs an object in preallocated memory. Since C lacks constructors, there is no need for placement new. I suppose the equivalent would be a pointer typecast, because once you have a pointer, you can act as if an object exists. Example of carving objects of differing type...
I need to pipe 3 programs: AddWith5.c AddWith2.c MultiplyWith3.c My code follows this pattern: ``` int main(){ int x; scanf("%i",&x); printf("%i",x*3); return 0; } ``` I need to pipe them so that I get the output for: ((x+5)+2)*3 (f1.txt contains the number 2) Can someone help me? I tried:AddWith...
Pipes are read left to right, so the input must be given to the "head" (the leftmost) program in the pipe: ``` $ AddWith5 < f1.txt | AddWith2 | MultiplyWith3 ``` Also, you don't invoke C files directly, each file needs to be individually compiled into a binary with the above names, first. This has, by the way, noth...
I want to print only n first elements from bst tree so i added global variable counter ``` int a = 0; void print (wezel **korzen,int x) { if((*korzen) != NULL && (a < x)) { print( &((*korzen)->lewe),x ); a++; printf("%s %d\n", (*korzen)->wartosc, (*korzen)->ile); print( &((*ko...
As I mentioned in my comments, you don't check a after the first print: ``` int a = 0; void print (wezel **korzen,int x) { if((*korzen) != NULL && (a < x)) { print( &((*korzen)->lewe),x ); // A has incremented since last check if (a < x) { printf("%s %d\n", (*korzen)->warto...
I have an integer returning from a function: ``` int a = func(); ``` For example,a = 236. I need to treat this as a hexadecimal representation of an integer, and store itsdecimalrepresentation in another variable, so that when printed like so: ``` printf("%x", variable) ``` ...the output should be: ``` 236 ```
All the values will be stored in binary format only. If you want to print the value in decimal formal print using%dformat string or if you want to print the value in hexa decimal then print using%x. Sameway we can assign the values in decimal and hexadecimal format also. ``` int a = 236; int b = 0x236; printf("%d", ...
I have a structure and want to increase an array size whenever SendMessage function calls ``` struct MQStruct { wchar_t *serviceName; int durability; int msgType; int msgHeader; wchar_t *msgId; wchar_t *payload; int payloadSize; int ttl; int priority; }MQStructObj[1]; int...
In C you will have to deal with dynamic memory (i.e allocate the array usingmalloc(), then take care to callfree()when you stop using it etc.) yourself, and possibly userealloc()to grow an allocation. In C++ the problem is already solved for you and you havestd::vector. You may callpush_backto add elements dynamicall...
I was hoping to be able to scan a string with this format ``` "hello world !!!!" ``` to ``` {"hello world", "!!!!"} ``` This 2 strings are separated with more than 1 space. Can I parse this or at least detect 2 consecutive spaces in scanf?
This code could help you ``` #include<stdio.h> #include<stdlib.h> #include<string.h> int main() { char a_buf[5][100] = {0}, sep[3] ,*buf = a_buf[0]; int i = 0; buf = a_buf[0]; while (scanf("%s%2[ ]",buf,sep) > 1) { if (strlen(sep)==1) { buf += strlen(buf); *buf...
Is C/C++ one language or two languages? I heard C++ was just C with classes. Is that right?
C++diverged from C in 1982-1983, and that's a long time in computer years. But, there are many C libraries with C++ compatibility, including the C standard library itself, and a steady stream of programs are ported across from C to C++. Many C programmers only know or use the features that are compatible with C++. Th...
How does one say that their C program should accept a file list? For example my programblahshould accepthello.txtby the following call in the console: ``` blah hello.txt ``` I am not sure how to parse an argument and label it as a filepath (getopt doesn't talk about this).
getopt()permutesargv[]so that all the non-options are shuffled to the end, so you simply callgetopt()to parse all the options and then loop throughargv[optind]up toargv[argc]. Those should be your file names, of course you need to check that those files actually exist, etc. C has no primitives for files. Here is some ...
Why does a255value represented by a signed char, get converted to-1with an integer? I see amov sblinstruction being used byx86to convert a signedcharto a signedint, but why does it convert in the way it does now?
Assuming an 8-bit char, an object of typesigned charcan never have a value 255. When you assign 255 to such an object, it gets converted in an implementation-defined manner (which, in reality, is always reduction modulo 256 into the range). Thus, italreadyhas value -1 at this point. Converting that to typeintmakes no ...
I'm reading a packet but I need to strip the first four bytes and the last byte from the packet to get what I need, how would you go about doing this in C? ``` /* Build an input buffer of the incoming message. */ while ( (len=read(clntSocket, line, MAXBUF)) != 0) { msg = (char *)malloc(len + 1); ...
You can change the address ofstrncpysource: ``` while ( (len=read(clntSocket, line, MAXBUF)) != 0) { msg = (char *)calloc(len -3, 1); // calloc instead of malloc + memset strncpy(msg, line+4, len); } } ``` PS: I assumed that line ischar*.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. I would like to create a C program ...
You might want to check outgetoptand/orgetopt_long.
I need a crossplatform way of calling std::cin in non blocking way. I know it's possible with threads, but maybe there is a better option? Threds seem to be overkill for this.
Standard C and C++ do not provide any means to do non blocking I/O. Typically, the C and C++ runtime environment does not see any input at all until the user has pressed the<ENTER>key. So, the only options are really to use a separate thread to read the input, or to use platform-specific methods to do the non-blockin...
Why does a255value represented by a signed char, get converted to-1with an integer? I see amov sblinstruction being used byx86to convert a signedcharto a signedint, but why does it convert in the way it does now?
Assuming an 8-bit char, an object of typesigned charcan never have a value 255. When you assign 255 to such an object, it gets converted in an implementation-defined manner (which, in reality, is always reduction modulo 256 into the range). Thus, italreadyhas value -1 at this point. Converting that to typeintmakes no ...
I'm reading a packet but I need to strip the first four bytes and the last byte from the packet to get what I need, how would you go about doing this in C? ``` /* Build an input buffer of the incoming message. */ while ( (len=read(clntSocket, line, MAXBUF)) != 0) { msg = (char *)malloc(len + 1); ...
You can change the address ofstrncpysource: ``` while ( (len=read(clntSocket, line, MAXBUF)) != 0) { msg = (char *)calloc(len -3, 1); // calloc instead of malloc + memset strncpy(msg, line+4, len); } } ``` PS: I assumed that line ischar*.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. I would like to create a C program ...
You might want to check outgetoptand/orgetopt_long.
I need a crossplatform way of calling std::cin in non blocking way. I know it's possible with threads, but maybe there is a better option? Threds seem to be overkill for this.
Standard C and C++ do not provide any means to do non blocking I/O. Typically, the C and C++ runtime environment does not see any input at all until the user has pressed the<ENTER>key. So, the only options are really to use a separate thread to read the input, or to use platform-specific methods to do the non-blockin...
So, the linuxtopcommand has the real time-like loop with console output (nothing fancy), but it uses non-blocking console input which doesn't display typed character in the command line. How it's done? Is there any library for it, do they use threads? I need to write an linux app with the same style (used via ssh) and...
One solution is to use an implementation ofcurses. I don't know howtopdoes it.
I came across this when I was compiling a simple program: ``` #include <X11/Xlib.h> #include <stdio.h> #include <stdlib.h> Display* display; int main(){ display = XOpenDisplay(""); if (display == NULL) { printf("Cannot connect\n"); exit (-1); } else{ printf("Succes...
You may need to add symbolic link to X11 folder by: sudo ln -s /opt/X11/include/X11 /usr/local/include/X11 In my case, I had to make include directory underusr/local.
How can I copy data from an int (int port1 = 52010) to a pair of unsigned chars (unsigned char port2[2]? I don't know how to deal with the division.
You typically use masking and shifting. ``` const unsigned short port = 52010; uint8_t port2[2]; ``` Big-endian: ``` port2[0] = port >> 8; port2[1] = port & 255; ``` little-endian: ``` port2[0] = port & 255; port2[1] = port >> 8; ``` For things like port numbers as used in IP networking, you typically always go ...
Is kqueue (on OS X) useful for reading/writing regular files? I know that epoll isnotuseful for regular files on Linux, so I'm wondering if the same is true for kqueue. EDIT: I don't mean reading/writing files, obviously read() and write() are for that. I meant, "is kqueue actually useful for detecting when a file ...
Kernel Queues are mechanisms which"allow you to intercept kernel-level events to receive notifications about changes to sockets, processes, the file system and other aspects of the system." I've used them in the past todetect when when actions happen on a file(or within a hot folder). I don't believe they can be use...
In my C program, I am printing a string to the command terminal usingprintf("%d %s %s\n", node->id, node->date, node->input);but I need to now use the write functionwrite(STDOUT_FILENO, cmdline, strlen(cmdline));... How can I format the string like I did using printf?
Usesprintf/snprintfto format the string into a character buffer, and thenwritethat.
This question already has answers here:Closed10 years ago. Possible Duplicate:Using fflush(stdin) My code is: ``` scanf("%d", &_choice); fflush(stdin); gets(input); ``` I usefflush(stdin);to remove the'\n'character that was left afterscanf. However, I found out that it doesn't work, andgetsautomatically takes the...
Becausefflushis for output streams. And at any rate,fflushis not for "removing\ncharacters"...
I'm taking a security course and am having trouble understanding this code due to a lack of understanding of the C programming language. ``` printf ("%08x.%08x.%08x.%08x|%s|"); ``` I was told that this code should move along the stack until a pointer to a function is found. I thought the.was just an indicator of p...
The symbols have no special meaning here since they are outside of a format specifier, they are simply output literally. Note however that you haven't provided all the arguments that printf expects so it will instead print 5 values that happen to be on the stack.
In C, what's the difference between astatic const intand aconst intin terms of memory alocated? ``` void f(int *a) { static const int b = 10; const int c = 20; *a = b + c; } ``` Willbonly consumesizeof(int)? Andc, will it consumesizeof(int)for the20value, andsizeof(int), plus a copy instruction duringfe...
The language standard says nothing about this. However, it's likely that the compiler will convert your code to this: ``` void f(int *a) { *a = 30; } ``` and therefore allocate no memory at all (except in instruction space, obviously).
I know how to create a structure array inside a function: ``` typedef struct item { int test; }; void func (void) { int arraysize = 5; item ar[arraysize]; } ``` But how do I to the same when the array is declared globally: ``` typedef struct item { int test; }; item ar[]; void func (void) { ...
Variable length arrays are only allowed in C for arrays with automatic storage duration. Arrays declared at file scope have static storage duration so cannot be variable length arrays. You can usemallocto dynamically allocate memory for an array object whose size is unknow at compilation time.
Why is size of this char variable equal 1? ``` int main(){ char s1[] = "hello"; fprintf(stderr, "(*s1) : %i\n", sizeof(*s1) ) // prints out 1 } ```
NOTA: the original question has changed a little bit at first it was:why is the size of this char pointer 1 sizeof(*s1) is the same as sizeof(s1[0])which is the size of acharobject and not the size of acharpointer. The size of an object of typecharis always1in C. To get the size of thecharpointer use this express...
Could anyone tell me how to check the data type of anndarraythat has been passed to C code? In the concrete example I would like to call a different function if the datatype of the array isfloat32ordouble/float64. So something like ``` if( Dtype(MyArray) == NPY_FLOAT ) { DoSomething_float( MyArray ); } else { ...
you are almost there, as you are looking forPyArray_TYPE: ``` int typ=PyArray_TYPE(MyArray); switch(typ) { case NPY_FLOAT: DoSomething_single(MyArray); break; case NPY_DOUBLE: DoSomething_double(MyArray); break; default: error("unknown type %d of MyArray\n", typ); } ```
http://d.pr/f/FIjfPlease check up main.c. I assigned a string aschar *s3 = "0,9,8,7,6,5,4,3,2,1";and there will be a SIGSEGV at running. When I de-annotate this line, then there is no SIGSEGV. So why does this string assignment lead to SIGSEGV?
Most likely you are modifying a string literal resulting inUndefined Behavior(UB). s3points to a string literal stored in read only implementation defined memory and any attempt to modify this string literal results in Undefined Behavior. In fact you are lucky that your code crashes because UB does not necessarily ma...
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed10 years ago.Improve this question I have a set of projects with pure C and Cobol code, I am looking for a continuous integration tool, but i have never used...
I use jenkins for C continuous integration. Jenkins jobs can run bash scripts, so at a minimum you can have the script bemake. If make returns non-zero, the build will fail. There is additional stuff you can do to like have gcov/lcov reports collected when you have it up and running as well.
How do I run an executable file likea.outusing the standard C library functionsexec(). Thanks in advance.
Whatever isexec, it is not C standard. If you are speaking aboutexecve(POSIX), look at the documentation. ``` int execve(const char *filename, char *const argv[], char *const envp[]); ``` So: ``` #include <unistd.h> char *args[] = { "./a.out", /* other arguments */, NULL }; execve("a.out", args, NULL); ```
In my program I'm reading words from a .txt file and I will be inserting them into both a linked list and a hash table. If two '\n' characters are read in a row after a word then the second word the program will read will be '\n', however I then overwrite it with '\0', so essentially the string contains only '\0'. I...
In C a character array with first element being\0is anempty string, i.e. of length zero. There's not much sense in keeping empty strings in containers, if that's what you are asking.
This may be a strange question, but I would like to programmatically model a UHF TV receiver. Anyone can give me some pointers? I have been looking at the code from emulators, but they are too specific for my purposes right now. To be more specific: Given some (probably synthesized) UHF analogue signal (in either NTS...
Take a look at xanalogtv fromXScreenSaver, it generates an analog signal, which it then decodes and displays.
Is it possible to convert AVR Assembler code into original code written in C language ? If yes, what is the name of the software to use ?
Well, this task is quite AI-complete. This is basically the point of reverse engineering: given some disassembled code, understand what it does, and possibly represent it in a high-level programming language. There aretools that attempt to automate this process, but generally it's not quite easy, sometimes not even po...
I am trying to set flag tcp_nodelay on a unix domain socket. Can we set it or does it even make sense to set tcp_nodelay for UNIX domain sockets, specifically on Linux? please advise. thanks
Unix domain sockets don't use Nagle (and obviously don't use TCP either). Also, the fact that it's calledtcp_nodelayindicates it's a TCP-only thing.
Is kqueue (on OS X) useful for reading/writing regular files? I know that epoll isnotuseful for regular files on Linux, so I'm wondering if the same is true for kqueue. EDIT: I don't mean reading/writing files, obviously read() and write() are for that. I meant, "is kqueue actually useful for detecting when a file ...
Kernel Queues are mechanisms which"allow you to intercept kernel-level events to receive notifications about changes to sockets, processes, the file system and other aspects of the system." I've used them in the past todetect when when actions happen on a file(or within a hot folder). I don't believe they can be use...
In my C program, I am printing a string to the command terminal usingprintf("%d %s %s\n", node->id, node->date, node->input);but I need to now use the write functionwrite(STDOUT_FILENO, cmdline, strlen(cmdline));... How can I format the string like I did using printf?
Usesprintf/snprintfto format the string into a character buffer, and thenwritethat.
This question already has answers here:Closed10 years ago. Possible Duplicate:Using fflush(stdin) My code is: ``` scanf("%d", &_choice); fflush(stdin); gets(input); ``` I usefflush(stdin);to remove the'\n'character that was left afterscanf. However, I found out that it doesn't work, andgetsautomatically takes the...
Becausefflushis for output streams. And at any rate,fflushis not for "removing\ncharacters"...
I'm taking a security course and am having trouble understanding this code due to a lack of understanding of the C programming language. ``` printf ("%08x.%08x.%08x.%08x|%s|"); ``` I was told that this code should move along the stack until a pointer to a function is found. I thought the.was just an indicator of p...
The symbols have no special meaning here since they are outside of a format specifier, they are simply output literally. Note however that you haven't provided all the arguments that printf expects so it will instead print 5 values that happen to be on the stack.
In C, what's the difference between astatic const intand aconst intin terms of memory alocated? ``` void f(int *a) { static const int b = 10; const int c = 20; *a = b + c; } ``` Willbonly consumesizeof(int)? Andc, will it consumesizeof(int)for the20value, andsizeof(int), plus a copy instruction duringfe...
The language standard says nothing about this. However, it's likely that the compiler will convert your code to this: ``` void f(int *a) { *a = 30; } ``` and therefore allocate no memory at all (except in instruction space, obviously).
I know how to create a structure array inside a function: ``` typedef struct item { int test; }; void func (void) { int arraysize = 5; item ar[arraysize]; } ``` But how do I to the same when the array is declared globally: ``` typedef struct item { int test; }; item ar[]; void func (void) { ...
Variable length arrays are only allowed in C for arrays with automatic storage duration. Arrays declared at file scope have static storage duration so cannot be variable length arrays. You can usemallocto dynamically allocate memory for an array object whose size is unknow at compilation time.
Why is size of this char variable equal 1? ``` int main(){ char s1[] = "hello"; fprintf(stderr, "(*s1) : %i\n", sizeof(*s1) ) // prints out 1 } ```
NOTA: the original question has changed a little bit at first it was:why is the size of this char pointer 1 sizeof(*s1) is the same as sizeof(s1[0])which is the size of acharobject and not the size of acharpointer. The size of an object of typecharis always1in C. To get the size of thecharpointer use this express...
Could anyone tell me how to check the data type of anndarraythat has been passed to C code? In the concrete example I would like to call a different function if the datatype of the array isfloat32ordouble/float64. So something like ``` if( Dtype(MyArray) == NPY_FLOAT ) { DoSomething_float( MyArray ); } else { ...
you are almost there, as you are looking forPyArray_TYPE: ``` int typ=PyArray_TYPE(MyArray); switch(typ) { case NPY_FLOAT: DoSomething_single(MyArray); break; case NPY_DOUBLE: DoSomething_double(MyArray); break; default: error("unknown type %d of MyArray\n", typ); } ```
http://d.pr/f/FIjfPlease check up main.c. I assigned a string aschar *s3 = "0,9,8,7,6,5,4,3,2,1";and there will be a SIGSEGV at running. When I de-annotate this line, then there is no SIGSEGV. So why does this string assignment lead to SIGSEGV?
Most likely you are modifying a string literal resulting inUndefined Behavior(UB). s3points to a string literal stored in read only implementation defined memory and any attempt to modify this string literal results in Undefined Behavior. In fact you are lucky that your code crashes because UB does not necessarily ma...
When calling a loop being performed in a C shared-library (dynamic library), Python will not receive a KeyboardInterrupt, and nothing will respond (or handle) CTRL+C. What do I do?
Unless you usePyDLLorPYFUNCTYPE; the GIL is released during the ctypes calls. Therefore the Python interpreter should handle SIGINT by raisingKeyboardInterruptin the main thread if the C code doesn't install its own signal handler. To allow the Python code to run in the main thread; you could put the ctypes call into...
I am confused about themynamearray's lifetime,is it still alive out of theifstatement?Do we get the same answer in c and c++? ``` int main (int argc, char* argv[]) { char* host; if (1 == argc) { /*code below is copied from a book*/ char myname[256]; gethostname(myname, 255); host...
mynamearray's lifetime[;] is it still alive out of the if statement? No ``` Do we get the same answer in C and C++? ``` Yes It is ugly, bad code and has UB, usestd::stringforhost
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. I am having trouble with executing ...
After it begins to execute, is your program using relative paths to input files that might be different? Are you an administrator on the computer and/or running eclipse as administrator? You could try running the command prompt as administrator to confirm that it isn't a permissions issue.
I came across this syntax, not sure what it means. ``` for( ; ; ) { //do stuff like read from a handle etc. } ``` I am still on my learning curve in C so vote down if you want if it's a lame question.
It's an infinite loop. Same aswhile(1) Really the only important thing to look at is that for loops look likefor (initialize vars; continue condition; counters). Since there's no continue condition it just keeps going (unless there's a break or return statement in there somewhere).
``` #include<stdio.h> int main() { int a=5,*b,*c; b=&a; c=b; *b++=*c++; printf(" %d %d %d\n",&a,b,c); } ``` Here if adress of a is x, then value of b and c is both becoming x+4. But shouldn't two ++ operator increase atleast one value by 8
No. Don't confuse the value of a pointer with the value that it pointsto. The expression*b++means: retrieve the value that b pointsto, and then increment the value of b.
how is it possible to get an ipv6 address from a addrinfo struct under windows xp? is there any other possibility than WSAAddressToString (has anyone ever successfully used that one?) ? ``` getaddrinfo(server_ip, port, &hints, &result) addr = (struct sockaddr_in6*) rp->ai_addr; WSAAddressToString((struct sockaddr*) r...
Try: WSAAddressToString(rp->ai_addr, rp->ai_addrlen, NULL, ipbuf, &iplen); You're passing an addrinfo as a sockaddr in your example. (I assume rp is iterating over the results or something.)
I have run into a strange bug where a multiplication is giving the wrong result. Below is a simplified version which gives the same result on my system. ``` #include <stdio.h> int main() { printf("%u\n", 1111111111U*10U); } ``` I am compiling with GCC 4.7.1 on OpenSUSE 12.2 (3.4.11-2.16-default x86_64) and this ...
10 * 1.1 billion exceeds the range of an unsigned int on your system, thus you're seeing the overflowed result. On a 32-bit system, the maximum value an unsigned int can hold is 4294967295 (4.29 billion).
I have a C file heapsort.c which Im trying to compile on a 64 bit linux machine to output the corresponding assembly code. Im using the following command: ``` gcc -02 -S heapsort.c ``` when I type this Im getting this error message ``` gcc:error: unrecognized option '-02' ``` I tried googling this error but nothin...
The flag is-O2, not-02. That's a letterOfor "optimization", not a number0. You might want to look into using a font that makes the difference more obvious.
I've tried to play an mp3 file or stream retrieved via http with the following command ``` gst-launch httpsrc location=http://domain.com/music.mp3 ! mad ! osssink ``` but a get the following error ``` ERREUR : le pipeline n'a pas pu être construit : pas d'élément « httpsrc ». ``` Which says that the pipeline could...
The element you want to use is called souphttpsrc. You can run gst-inspect | grep http to see all installed elements matching http.
Was wondering if the next statement could lead to a protection fault and other horrible stuff if value of next is NULL(node being a linked list). ``` if (!node->next || node->next->some_field != some_value) { ``` Im assuming the second part of the OR is not evaluated once the first part is true. Am I wrong in assumi...
In the ISO-IEC-9899-1999 Standard (C99), Section 6.5.14: The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int. 4 Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; there is a sequence point after the evalua...
``` system ("cd .."); ``` This doesn't produce any error but also doesn't do anything meaningful. Why?
Thesystem()function makes afork()that creates a process being a copy of the initial one. Thecurrent directorydepends on the environment of a process (it is stored within the environment variables of a process). Thus when thechildprocess, having its own environment, makes acd, that affects only thechildprocess, not th...
I am unable to pass stdcall function name "TestFunction" as parameter into ExecuteLocalThread and to use in beginthreadex ``` unsigned __stdcall TestFunction(void* timerPointer) { unsigned result =0; printf("thread is running\n"); return result; } void ExecuteLocalThread(unsigned int (_stdcall *_StartAdd...
Try: ``` heartBeatThread = (HANDLE)_beginthreadex(NULL, 0 , _StartAddress/*&TestFunction*/, (void*)this, CREATE_SUSPENDED, &hbThreadID); ```
I'd like to write a single instruction to switch two values into a variable at every instruction execution; this is the generic case: having two valuesx1, x2andiinitialized tox1orx2, switch i value betweenx1andx2at every instruction execution, i.e.i= x1, x2, x1 ...;or, if i is initialized to x2,i = x2, x1, x2, ...; E...
This is what you are looking for? ``` i=(x1+x2)-i ```
``` // Trying to read file void readFilee(char *namefile){ FILE *f_in = fopen(namefile,"r"); char x; int i = 0; if(!f_in){ printf("Error"); exit(0); } /* read to EOF */ while(1){ x = getc(f_in); if(x == '\n') continue; archivo[i] = x; if(x == EOF) break;...
add ``` archivo[i] = '\0'; ``` after the while loop terminate. This will add null charachter at the end of your stringarchivo also may be the memory space of yourarchivoarray is not sufficient to get the whole content of the file and so it could cause a buffer overflow so it could cause a crash
I came across this syntax, not sure what it means. ``` for( ; ; ) { //do stuff like read from a handle etc. } ``` I am still on my learning curve in C so vote down if you want if it's a lame question.
It's an infinite loop. Same aswhile(1) Really the only important thing to look at is that for loops look likefor (initialize vars; continue condition; counters). Since there's no continue condition it just keeps going (unless there's a break or return statement in there somewhere).
``` #include<stdio.h> int main() { int a=5,*b,*c; b=&a; c=b; *b++=*c++; printf(" %d %d %d\n",&a,b,c); } ``` Here if adress of a is x, then value of b and c is both becoming x+4. But shouldn't two ++ operator increase atleast one value by 8
No. Don't confuse the value of a pointer with the value that it pointsto. The expression*b++means: retrieve the value that b pointsto, and then increment the value of b.
how is it possible to get an ipv6 address from a addrinfo struct under windows xp? is there any other possibility than WSAAddressToString (has anyone ever successfully used that one?) ? ``` getaddrinfo(server_ip, port, &hints, &result) addr = (struct sockaddr_in6*) rp->ai_addr; WSAAddressToString((struct sockaddr*) r...
Try: WSAAddressToString(rp->ai_addr, rp->ai_addrlen, NULL, ipbuf, &iplen); You're passing an addrinfo as a sockaddr in your example. (I assume rp is iterating over the results or something.)
I have run into a strange bug where a multiplication is giving the wrong result. Below is a simplified version which gives the same result on my system. ``` #include <stdio.h> int main() { printf("%u\n", 1111111111U*10U); } ``` I am compiling with GCC 4.7.1 on OpenSUSE 12.2 (3.4.11-2.16-default x86_64) and this ...
10 * 1.1 billion exceeds the range of an unsigned int on your system, thus you're seeing the overflowed result. On a 32-bit system, the maximum value an unsigned int can hold is 4294967295 (4.29 billion).
I have a C file heapsort.c which Im trying to compile on a 64 bit linux machine to output the corresponding assembly code. Im using the following command: ``` gcc -02 -S heapsort.c ``` when I type this Im getting this error message ``` gcc:error: unrecognized option '-02' ``` I tried googling this error but nothin...
The flag is-O2, not-02. That's a letterOfor "optimization", not a number0. You might want to look into using a font that makes the difference more obvious.
I've tried to play an mp3 file or stream retrieved via http with the following command ``` gst-launch httpsrc location=http://domain.com/music.mp3 ! mad ! osssink ``` but a get the following error ``` ERREUR : le pipeline n'a pas pu être construit : pas d'élément « httpsrc ». ``` Which says that the pipeline could...
The element you want to use is called souphttpsrc. You can run gst-inspect | grep http to see all installed elements matching http.
Was wondering if the next statement could lead to a protection fault and other horrible stuff if value of next is NULL(node being a linked list). ``` if (!node->next || node->next->some_field != some_value) { ``` Im assuming the second part of the OR is not evaluated once the first part is true. Am I wrong in assumi...
In the ISO-IEC-9899-1999 Standard (C99), Section 6.5.14: The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int. 4 Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; there is a sequence point after the evalua...
``` system ("cd .."); ``` This doesn't produce any error but also doesn't do anything meaningful. Why?
Thesystem()function makes afork()that creates a process being a copy of the initial one. Thecurrent directorydepends on the environment of a process (it is stored within the environment variables of a process). Thus when thechildprocess, having its own environment, makes acd, that affects only thechildprocess, not th...
I am unable to pass stdcall function name "TestFunction" as parameter into ExecuteLocalThread and to use in beginthreadex ``` unsigned __stdcall TestFunction(void* timerPointer) { unsigned result =0; printf("thread is running\n"); return result; } void ExecuteLocalThread(unsigned int (_stdcall *_StartAdd...
Try: ``` heartBeatThread = (HANDLE)_beginthreadex(NULL, 0 , _StartAddress/*&TestFunction*/, (void*)this, CREATE_SUSPENDED, &hbThreadID); ```
I'd like to write a single instruction to switch two values into a variable at every instruction execution; this is the generic case: having two valuesx1, x2andiinitialized tox1orx2, switch i value betweenx1andx2at every instruction execution, i.e.i= x1, x2, x1 ...;or, if i is initialized to x2,i = x2, x1, x2, ...; E...
This is what you are looking for? ``` i=(x1+x2)-i ```
``` // Trying to read file void readFilee(char *namefile){ FILE *f_in = fopen(namefile,"r"); char x; int i = 0; if(!f_in){ printf("Error"); exit(0); } /* read to EOF */ while(1){ x = getc(f_in); if(x == '\n') continue; archivo[i] = x; if(x == EOF) break;...
add ``` archivo[i] = '\0'; ``` after the while loop terminate. This will add null charachter at the end of your stringarchivo also may be the memory space of yourarchivoarray is not sufficient to get the whole content of the file and so it could cause a buffer overflow so it could cause a crash
Here is the code: ``` #include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { int r; int i; for (i = 0; i < 100; i++) { r = rand() % 100 + 1; printf("%d\n", r); } return 0; } ``` I've been trying to random number but one day, I forgot to putsrand()in, but th...
If srand is not called, rand acts as if srand(1) has been called. http://www.acm.uiuc.edu/webmonkeys/book/c_guide/2.13.html#rand
The below is the error i'm getting while making a zImage.. Can anyone help me in this? Thanks ``` make: arm-linux-gcc: Command not found CHK include/linux/version.h make[1]: `include/asm-arm/mach-types.h' is up to date. CHK include/linux/utsrelease.h SYMLINK include/asm -> include/asm-arm CC kern...
It looks like you do not have the GNU arm tool chain i.earm-linux-gcc If you do not have it installed install Sourcery Codebench Lite. If you have binaries, set thebindirectory path in PATH variable.You can do it byexport PATH=$PATH:/path/to/arm/binaries/
I am trying to check the least and most significant byte of an int separately. I want to check if any bit in the least significant byte is one. I want to return 1 if true and 0 if false. My attempt: ``` int lsb_one(int x) { return ( (x & 0xffff) != 0 ); } ``` I want to check if any bit in the most significant byt...
Try: ``` int lsb_one(int x) { return ((x & 0xff) != 0 ); } int msb_zero(int x) { return ((x & 0xff000000) != 0xff000000); } ``` Note that the second version is platform dependent, assuming that int is a 32-bit value.
I am studying the C language, and I saw a new extension that I had not seen before. What do files with the extension likelibrary.h.inmean? Is it as the simple header with extension ".h"? What's the difference?
These files are usually the input forautoconfwhich will generate final .h files. Here's an example from PCRE: ``` #define PCRE_MAJOR @PCRE_MAJOR@ #define PCRE_MINOR @PCRE_MINOR@ #define PCRE_PRERELEASE @PCRE_PRERELEASE@ #define PCRE_DATE @PCRE_DATE@ ``` Autoconf will replace all vari...
I am still learning C and had a question related to something I see fairly often. Please correct me if I'm wrong, is statement 1 the equivalent of statement 2? (struct sockaddr *) &echoServAddrstruct sockaddr echoServAddr If I understand this correctly, we are casting&echoServAddrto a struct framed the same assockad...
Assuming these are both function arguments. These are different. First one is passing structure by reference. Second one is passing structure as is - the whole data is copied. Bind acceptsconst struct sockaddr *as it's second argument, so that's correct code.
I'm capturing images from a Cam using OpenCV C API and send them using TCP sockets. The server is running C++ (QT) and receive the frame. The process is working fine and I can see the images on the server. The weird problem is when I close both programs and rerun the client and the server, I can see the previous fr...
I had the same problem before. the frame size is pretty much and you read from the buffer in a random way (just guessing) , you have to make a timer or an acknowledge between the camera and OpenCV. Just try to control the way the camera is capturing frames.
``` int main ( ) { int a = 1 ; static int b = a ; } ``` This piece of code gives error ingcc 4.3.2as error : initializer element is not constant. But it runs fine ong++ 4.3.2. Someone Please Explain why this is not giving error in g++ 4.3.2.
Because it is valid in C++ (and not valid in C). (C++11, 6.7p4) "Constant initialization (3.6.2) of a block-scope entity with static storage duration, if applicable, is performed before its block is first entered. [...] Otherwise such a variable is initialized the first time ...
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he...
With the use ofmalloc(3)andfree(3)to do dynamic memory management. It's still done today. ``` void f(int n) { int *nInts = malloc(n * sizeof(int)); /* do stuff with 'nInts' */ free(nInts); } ```