question
stringlengths
25
894
answer
stringlengths
4
863
I'm writing an multithreaded application and I'm wondering about following: When using-D_REENTRANTmacro, do I need to explicitly use_rsuffixed functions? e.g. Shall I usestrtok_reverywhere in the code or can I usestrtokand make sure I pass-D_REENTRANTmacro to the compiler? Thanks a lot
Defining_REENTRANTwon't change the semantics ofstrtok(). You'll need to usestrtok_r().
How do I convert the following macro into a function? ``` #define xtime(x) ((x<<1) ^ (((x>>7) & 1) * 0x1b)) ```
``` template<typename T> T xtime(T x) { return ((x<<1) ^ (((x>>7) & 1) * 0x1b)); } ```
is there some way to define static structure that is already one and only instance of itself? Like the way you can do it with the struc keyword in nasm?
You can use an anonymous structure, like this: ``` struct { int memberA, memberB; } my_struct; my_struct.memberA = 1; my_struct.memberB = 2; printf("%d %d\n", my_struct.memberA, my_struct.memberB); ```
Does loop back interface generates interrupt on NIC/Hardware
The loopback interface is a virtual network interface. It doesn't correspond to any actual hardware, and packets transmitted through it therefore do not generate hardware interrupts. It's possible that linux has some concept of a "soft interrupt", i.e. an inter-thread/process signalling mechanism, and that packets ov...
Basically it's all in the title. I'm calling C code from R via .Call(). The C code is throwing an error, but using traceback() or options(error=recover), the .Call() function is the farthest I can drill down to. Is there a way to view the C call stack when an error is thrown in the C code?
Use gdb (or lldb under clang) to debug C code, perhaps as outlinedhere
I was surprised whengcc -Wallcompiled this without warning. Is this really legitimate C? What are the risks of writing code like this? ``` #include <stdio.h> #include <stdlib.h> typedef struct { int a; int b; } MyStruct; int main(void) { MyStruct *s = malloc(sizeof(*s)); // as opposed to malloc(sizeof(MyStruc...
Not only it's legitimate, it's even preferable to the alternative. This way you let the compiler deduce the actual type instead of doing it manually.
I tried to create mydata.txt and read from it but compiler gives results as ``` 0.000000 0.000000 168 2686832 ``` What is wrong with this code? ``` int main() { double f_1, f_2; int i_1, i_2; FILE *file_pointer; char file_name[SIZE] = "mydata.txt"; file_pointer = fopen(file_name, "w"); fpri...
Dofclose()before the secondfopen().
I have a program where I need to scanf a string, which I know it will be only 2 characters long. (for example: "ex"). what is the proper way to do that? I was going for: ``` char myStr[3]; scanf("%s", myStr); ``` It works just fine, but when I enter a 10-letter word it also works just fine. How come? Does the [3] h...
The proper way to limit the input usingscanf()is ``` if (scanf("%2s", myStr) != 1) /* error */; ``` But consider usingfgets()rather thanscanf() ``` if (fgets(myStr, sizeof myStr, stdin) == NULL) /* error */; ```
I have a simple application: ``` #include <stdio.h> int main(int argc, char **argv) { unsigned int a = 0x2; //= 10b unsigned int b = ~a; // should be 01b printf("%04x : %04x\n", a, b); } ``` I wonder, why does it print0002 : fffffffdinstead of0002 : 0001?
``` fffffffd(hex) -> 11111111111111111111111111111101(binary) 00000002(hex) -> 00000000000000000000000000000010(binary) ``` As you can see, they ARE bitwise negations of each other.
Im trying to find prime numbers and it seems i have made mistake but i cannot find it by myself for hours here is my code: ``` #include<stdio.h> #include<math.h> int main(){ int n,a,b; printf("enter a number=> \n"); scanf("%d",&n); for(a=2;a<=n;a++){ for(b==2;b<=a;b++){ if(a%b==...
Change ``` for(b==2;b<=a;b++) // ^ Replace it with assignment operator '=' ``` to ``` for(b = 2; b*b <=a; b++) // ^ Reduce the unnecessary loop iteration. ```
In every C program I had seen, there will be the main() function. Unlike in other languages, such as Java and C++, it has no data type before it. In C++ and Java there will at least be a void with main(), if not some other data type. Why does main() have no data type with it in C? Also, in Java the constructor has n...
It's user-defined: you define it in each program. If it were a library function, you wouldn't define it, because the library would define it for you. (As an exception to this, the Unix librariesliblandliby, the support libraries forLexandYacc, actually definemain; the idea is that you define a bunch of functions with...
I don't have much experience and I'm on a C project where I need to create & delete folders and the program must run on both Linux and Windows. I saw few solutions but all were either for Windows or Linux but none for both and most uses system(...). Also, if there is an easy way to delete a folder with it's contents...
Here is a common 'create directory' method: ``` void make_directory(const char* name) { #ifdef __linux__ mkdir(name, 777); #else _mkdir(name); #endif } ``` As for removing directories, you are on the right track, ie: for the moment I delete each files one by one and then the folder wi...
This question already has answers here:Why isn't the size of an array parameter the same as within main?(13 answers)Closed9 years ago. I'm working with some arrays in plain C99 and I need to know their size. Does anyone knows why this is happening: ``` int function(char* m){ return sizeof(m) / sizeof(m[0]); } i...
Arrays decay to pointers at the first chance they get, thus infunctionall you have is a pointer, which is 8 bytes in your case.
I have developed a shared library B.so, which depends on A.so. When I write a program test.exe using B.so, but there is a compile error, it said that some symbols(the symbols are in A.so) not found. My build line: ``` gcc test.c -o test.exe -fPIC -I./ -L./ -lB ``` Do we have a method that, how to build test.exe suc...
how to build test.exe successfully,but not link A.so. There are at least two method: export a properLD_LIBRARY_PATHexport LD_LIBRARY_PATH=/path/to/A gcc ... -lBusingldoption-rpath(discovered by the asker @iceKing himself)gcc -Wl,-rpath=/path/to/A ... In both case,ldwill automatically search for libraries depended b...
``` #define SUM(x,y) ((x)+(y)) void print(){ for(int i=0;i<10;i++) printf("sum=%d\n", SUM(i,i+1)); } ``` Is there any benefit in using the macro SUM like above? I read that macros are useful when there is a loop with a function call inside.
For very simple computation, call function may have more overhead than the actual computation itself; in a loop, the situation even worse. However, you need to define your function replacement macro carefully to only evaluate its arguments once. For example, if you have a macro like this ``` #define DOUBLE(i) ((i) +...
I usually usecscopeto browse my code. Whenever I hitC ]the current buffer I am reading changes and the file containing the definition is shown. Suppose I have already a tab in vim with that file already open: is there anyway to jump from my current location directly to that file that is already open? I don't need to...
You could come close to what you want with a combination of options: ``` " use the quickfix list/window for all cscope queries set cscopequickfix=s-,g-,c-,d-,i-,t-,e- " quickfix commands jump to the target buffer where it is displayed set switchbuf=useopen,usetab ``` and a remapping: ``` " override the default <C-...
``` #include<stdio.h> #include<conio.h> int main() { int const anila=10; int *ptr=&anila; clrscr(); printf("%d",*ptr); getch(); return 0; } ``` why the warning occurs in the program? what is suspicious pointer conversion here? and *ptr=&anila; *ptr will have the address of anila. how it ...
anilaisconst, butptris a non-constpointer, think about this code: ``` *ptr = 42; ``` It's trying to modify*ptr, i.e,anilahere, that's why there's a warning.
I am browsing long source code using vim+cscope+ctags. I find it really cumbersome to always press<C-]>and<C-T>as the keys are located far apart. I want to copy these key bindings to<C-Q>and<C-A>so that both the key bindings work in VIM.
It should be : ``` nnoremap <C-q> <C-]> nnoremap <C-a> <C-t> ``` However I would discourage these mappings because they would cause issues. <C-a>in vim is used to increment the number under the cursor by 1,<C-x>similarly is for decrementing a number under the cursor by 1.
This question already has answers here:Why isn't the size of an array parameter the same as within main?(13 answers)Closed9 years ago. I'm working with some arrays in plain C99 and I need to know their size. Does anyone knows why this is happening: ``` int function(char* m){ return sizeof(m) / sizeof(m[0]); } i...
Arrays decay to pointers at the first chance they get, thus infunctionall you have is a pointer, which is 8 bytes in your case.
I have developed a shared library B.so, which depends on A.so. When I write a program test.exe using B.so, but there is a compile error, it said that some symbols(the symbols are in A.so) not found. My build line: ``` gcc test.c -o test.exe -fPIC -I./ -L./ -lB ``` Do we have a method that, how to build test.exe suc...
how to build test.exe successfully,but not link A.so. There are at least two method: export a properLD_LIBRARY_PATHexport LD_LIBRARY_PATH=/path/to/A gcc ... -lBusingldoption-rpath(discovered by the asker @iceKing himself)gcc -Wl,-rpath=/path/to/A ... In both case,ldwill automatically search for libraries depended b...
``` #define SUM(x,y) ((x)+(y)) void print(){ for(int i=0;i<10;i++) printf("sum=%d\n", SUM(i,i+1)); } ``` Is there any benefit in using the macro SUM like above? I read that macros are useful when there is a loop with a function call inside.
For very simple computation, call function may have more overhead than the actual computation itself; in a loop, the situation even worse. However, you need to define your function replacement macro carefully to only evaluate its arguments once. For example, if you have a macro like this ``` #define DOUBLE(i) ((i) +...
I usually usecscopeto browse my code. Whenever I hitC ]the current buffer I am reading changes and the file containing the definition is shown. Suppose I have already a tab in vim with that file already open: is there anyway to jump from my current location directly to that file that is already open? I don't need to...
You could come close to what you want with a combination of options: ``` " use the quickfix list/window for all cscope queries set cscopequickfix=s-,g-,c-,d-,i-,t-,e- " quickfix commands jump to the target buffer where it is displayed set switchbuf=useopen,usetab ``` and a remapping: ``` " override the default <C-...
``` #include<stdio.h> #include<conio.h> int main() { int const anila=10; int *ptr=&anila; clrscr(); printf("%d",*ptr); getch(); return 0; } ``` why the warning occurs in the program? what is suspicious pointer conversion here? and *ptr=&anila; *ptr will have the address of anila. how it ...
anilaisconst, butptris a non-constpointer, think about this code: ``` *ptr = 42; ``` It's trying to modify*ptr, i.e,anilahere, that's why there's a warning.
I am browsing long source code using vim+cscope+ctags. I find it really cumbersome to always press<C-]>and<C-T>as the keys are located far apart. I want to copy these key bindings to<C-Q>and<C-A>so that both the key bindings work in VIM.
It should be : ``` nnoremap <C-q> <C-]> nnoremap <C-a> <C-t> ``` However I would discourage these mappings because they would cause issues. <C-a>in vim is used to increment the number under the cursor by 1,<C-x>similarly is for decrementing a number under the cursor by 1.
By using c language I need to create a text file in/tmpdirectory, but I don't know how to do this. Is there anyone who knows how to create a text file in/tmpfolder?
There'smkstempfunction for this
``` #include<stdio.h> #include<conio.h> int adder(int,int); void main() { int a,b; printf("enter nos"); scanf("%d%d",&a,&b); adder( a,b); printf("sum is %d",adder); getch(); } int adder(int x,int y) { return x+y; } ``` this program is not working.I think the code is right.Can you point out...
adderis a function, what you shouldprintfis its return value. And as @JonathanLeffler said, it's better to add a newline at the end if you want to ensure the output appears timely. So, change ``` adder( a,b); printf("sum is %d",adder); ``` to: ``` int result = adder(a,b); printf("sum is %d\n", result); ``` or to...
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.Closed9 years ago.Improve this question I have a string"heya64 this is21 a good89 day91" I have to sort in such way that , first...
The algorithm to sort this problem is simple, just like you said in your question description, sort characters in each word first, then sort these sorted-word again. Like this: ``` $ echo heya64 this is21 a good89 day91 | perl -anE 'say(join " ", sort(map { join "", sort split // } @F))' 12is 19ady 46aehy 89dgoo a h...
By using c language I need to create a text file in/tmpdirectory, but I don't know how to do this. Is there anyone who knows how to create a text file in/tmpfolder?
There'smkstempfunction for this
``` #include<stdio.h> #include<conio.h> int adder(int,int); void main() { int a,b; printf("enter nos"); scanf("%d%d",&a,&b); adder( a,b); printf("sum is %d",adder); getch(); } int adder(int x,int y) { return x+y; } ``` this program is not working.I think the code is right.Can you point out...
adderis a function, what you shouldprintfis its return value. And as @JonathanLeffler said, it's better to add a newline at the end if you want to ensure the output appears timely. So, change ``` adder( a,b); printf("sum is %d",adder); ``` to: ``` int result = adder(a,b); printf("sum is %d\n", result); ``` or to...
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.Closed9 years ago.Improve this question I have a string"heya64 this is21 a good89 day91" I have to sort in such way that , first...
The algorithm to sort this problem is simple, just like you said in your question description, sort characters in each word first, then sort these sorted-word again. Like this: ``` $ echo heya64 this is21 a good89 day91 | perl -anE 'say(join " ", sort(map { join "", sort split // } @F))' 12is 19ady 46aehy 89dgoo a h...
Here is my code: ``` #include<stdlib.h> #include<stdio.h> int main() { (void)system("cat json.json | ./jq.exe '.location | {street, city}'"); return 0; } ``` I want to save the output from (void)system into a variable but how exactly would I do that?
You will have to create apipeand redirect the output from the system call to that pipe, and then read the data from the pipe -- this is what thepopencall essentially does, which means that you should just convert thesystemcall to apopencall and then read from the file descriptor into the variables you want to populate...
``` #include<stdio.h> #include<conio.h> int main() { char *p=malloc(100); clrscr(); printf("enter your name\n"); scanf("%s",p); printf("%s",p); getch(); return 0; } ``` when compiling this c program "non portable pointer conversion" warning is occuring..What is the reason for the warning?
The warning is solved..why it is occuring? please explain..? You were missing the prototype formalloc, so the compiler assumed a return type ofint. ``` char *p=malloc(100); ``` Assigning anintto achar*gives the warning. Apparantly they are the same size in your compiler, but they aren't the same size everywhere. W...
I am not able to compile this program.can anyone tell me tell me where i am going wrong. ``` int i = 8, j, k; ++i = ++j = ++k = 8; printf("\n %d \t %d \t %d",i,j,k); ``` it is giving the errorerror : lvalue required as left operand of assignment
The segment++iis not an lvalue (so named because they generally can appear on the left side of an assignment). As the standard states (C11 6.3.2.1): An lvalue is an expression (with an object type other than void) that potentially designates an object. iitself is an lvalue, but pre-incrementing it like that means i...
what is the compiler of c that visual studio 6 use? I starting work with c and need to study more about c. In this work, we use visual c++ 6. I know have GCC, but where i can go deep about how compilation works for C language on visual c++ 6?
what is the compiler of c that visual studio 6 use? The Visual C++ IDE runs the cl.exe Microsoft compiler. As to which standard of C compiler it is using, my guess is it's probably a C90 or C95 compiler, only because, from memory, the Visual C++ IDE dates back to the mid/late nineties. To get a more accurate date lo...
Defines the typexand an arrayXof that type. x.h: ``` typedef struct _x {int p, q, r;} x; extern x X[]; ``` Separate file to keep the huge honking arrayX. x.c: ``` #include "x.h" x X[] = {/* lotsa stuff */}; ``` Now I want to useX: main.c: ``` #include "x.h" int main() { int i; for (i = 0; i < sizeof(...
Inx.hadd: ``` extern size_t x_count; ``` Inx.cadd: ``` size_t x_count = sizeof(X)/sizeof(x); ``` Then use the variablex_countin your loop. The division has to be done in the compilation unit that contains the array initializer, so it knows the size of the whole array.
I just downloaded gstreamer 1.2.4 both normal and developer packs fromhere, and performed full installs of both packs. Then I added bin location to path variable, then created c++ solution and addedx86.propsandgstreamer-1.0.props. I wanted to check some basic GES project, but I'm unable to do it since not all depende...
The missing gst-editing-services-1.0.props file was added in 1.2.4.1 version. You can download it from herehttp://gstreamer.freedesktop.org/data/pkg/windows/1.2.4.1/.
I have the following code: ``` int main(int argc, char *argv[]) { char ch[10]; printf("String 10 max. :: "); gets( ch ); printf("String: %s\n", ch); return 0; } ``` When I run this with"12345678"aschit runs well. The strange thing is when I run with"123456789012345678901234567890"! The secondprintf...
Buffer overflow is undefined behaviour. It may crash, but no one guarantee that. In most compilers, the stack grows down, so you probably overridemain's return address, but the call toprintfdoesn't override your string.
I have a python client who packs some data doing this: ``` #MOUNT UDP PACKET (unsigned char type, 5 char ext, 50 char user) pqtUDP = pack('B5s50s', REGISTER, ext, user) ``` And now I'm receiving that on a C client, so to read correct data I suppose I have to unpack it and save it in different vars, no? How can I do ...
Something like this should work in C: ``` // assumes input packet is [const char* data] unsigned char reg; char ext[6]; char user[51]; reg = data[0]; memcpy(ext, data + 1, 5); ext[5] = 0; // set null terminator memcpy(user, data + 6, 50); user[50] = 0; // set null terminator ```
In Visual Studio 2012 (SP4) if I create a new Windows EXE solution, use the Nuget command line to "install-package curl", build the solution, the program executes correctly and displays the simple window as expected. If I add a call tocurl_version()to the code (meaning the cURL, SSL, etc... DLLs are now referenced) -...
Found the problem usingthissolution - basically zLIB v1.2.8.1 references the Windows 8 function CreateFile2
Sayais my number. And I wanta1to be a with all bits on even positions inverted. This is my current solution ``` int a1 = ((a & 0xaaaaaaaa) | (~(a) & 0x55555555)); ``` How can I make this faster?
Use the bitwise xor (^) operator: ``` a1 ^= 0x55555555; ``` this will invert bits 0, 2, 4, and so on.
While browsing through foreign code I came across this: ``` for(i = 0; i < len; i++,j) ``` Can anybody tell me what the "j" does here? I guess it's something simple, but I don't understand the meaning. "j" is declared as a uint16_t and initialized with 0.
The following code is valid ``` for(i=0; i<len; i++,j++); ``` and is equivalent to ``` for(i=0; i<len; i++,j) { j++; } ``` which is further equivalent to ``` //NOTE-there is no j after the i++; for(i=0; i<len; i++) { j++; } ``` So there is no need to write j in your for(statement). The j written...
I have the following code: ``` int main(int argc, char *argv[]) { char ch[10]; printf("String 10 max. :: "); gets( ch ); printf("String: %s\n", ch); return 0; } ``` When I run this with"12345678"aschit runs well. The strange thing is when I run with"123456789012345678901234567890"! The secondprintf...
Buffer overflow is undefined behaviour. It may crash, but no one guarantee that. In most compilers, the stack grows down, so you probably overridemain's return address, but the call toprintfdoesn't override your string.
I have a python client who packs some data doing this: ``` #MOUNT UDP PACKET (unsigned char type, 5 char ext, 50 char user) pqtUDP = pack('B5s50s', REGISTER, ext, user) ``` And now I'm receiving that on a C client, so to read correct data I suppose I have to unpack it and save it in different vars, no? How can I do ...
Something like this should work in C: ``` // assumes input packet is [const char* data] unsigned char reg; char ext[6]; char user[51]; reg = data[0]; memcpy(ext, data + 1, 5); ext[5] = 0; // set null terminator memcpy(user, data + 6, 50); user[50] = 0; // set null terminator ```
In Visual Studio 2012 (SP4) if I create a new Windows EXE solution, use the Nuget command line to "install-package curl", build the solution, the program executes correctly and displays the simple window as expected. If I add a call tocurl_version()to the code (meaning the cURL, SSL, etc... DLLs are now referenced) -...
Found the problem usingthissolution - basically zLIB v1.2.8.1 references the Windows 8 function CreateFile2
Sayais my number. And I wanta1to be a with all bits on even positions inverted. This is my current solution ``` int a1 = ((a & 0xaaaaaaaa) | (~(a) & 0x55555555)); ``` How can I make this faster?
Use the bitwise xor (^) operator: ``` a1 ^= 0x55555555; ``` this will invert bits 0, 2, 4, and so on.
While browsing through foreign code I came across this: ``` for(i = 0; i < len; i++,j) ``` Can anybody tell me what the "j" does here? I guess it's something simple, but I don't understand the meaning. "j" is declared as a uint16_t and initialized with 0.
The following code is valid ``` for(i=0; i<len; i++,j++); ``` and is equivalent to ``` for(i=0; i<len; i++,j) { j++; } ``` which is further equivalent to ``` //NOTE-there is no j after the i++; for(i=0; i<len; i++) { j++; } ``` So there is no need to write j in your for(statement). The j written...
In this function:omapi_wait_for_completion ``` omapi_object_t *inner; if (object) { waiter = (omapi_waiter_object_t *)0; .... ``` 0is being cated to anomapi_waiter_object_tpointer. What is the purpose? I know a similar question exists:Casting NULL to a struct pointer in C?, but the answer is about v...
Sometimes, people just write useless code. There is no sense in actually writing the cast here.
I am trying to debug a deadlock/race condition in my multiprocess shared memory program. For some reason it is only deadlocking some of the time. I would like to know what each process is doing at this time so that I can find the bug. Any ideas on how I could use gdb or valgrind for this?
Not a complete answer, just a thought: you may attach to a working process usinggdb -p <processId> /path/to/executable/being/debugged. Or just usestrace -p <pid>. BTW Right now I'm doing this for LibreOffice with KDE4 dialogs plugin hanging on startup (somewhere in libSM interaction) :) A typical race condition, bec...
We are given the prompt (using AT&T ASM) ``` eax = A ebx = B ecx = &X edx = &Y ``` I understand that (%eax) would grab the data in the memory location at A, but what would doing (%edx) grab? Say for example the call ``` movl (%edx), %ebx ``` Also ``` movl %eax, (%ecx) ``` Does the first ca...
From the 'C' language perspective: ``` eax = A ``` eax gets a copy of the value of A. ``` ebx = B ``` ebx gets a copy of the value of B. ``` ecx = &X ``` ecx gets the address (or memory location) of X. ``` edx = &Y ``` edx gets the address (or memory location) of y.
I am sending data between a C TCP socket server and a C# TCP client. From the C# client, the data being sent is an array of the .NET framework type System.Byte, which is an unsigned 8-bit integer. From the C server, the data being sent is an array of the C type char, which is also an unsigned 8-bit integer. From wh...
Your intuition is correct: endianness is irrelevant for 8-bit integers; it only comes into play for types that are wider than one byte.
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question appears to be off-topic becauseit lacks sufficient information to diagnose the problem.Describe your problem in more detail orinclude a minimal examplein the question itself.Closed9 years ago.Improve this q...
This hasn't been needed in many years. Modern hard drives will automatically park the read heads when shutting down. Also, as mentioned in Oli Charlesworth's comment, that functionality would have to be provided by some sort of device driver and its associated API. There's nothing in C that you can just call to do tha...
I'm a bit confused about this here ``` char *string; scanf("%s",string); int i=strlen(string); int k = 0; while(k<i){ printf("%c", string[k]); k++; } ``` and when I compile this it prints out nothing.
``` scanf("%s",string); ``` stringis a pointer. you need to allocate memory to it so that it can hold the input read usingscanf. ``` char *string; ``` this statement just creates a pointer to a character array but doesn't allocate memory to hold the array.You need to allocate memory explicitly using dynamic-allocat...
The kernel communicates with drivers that means my application could do it as well maybe doing system calls? For example I would like to simulate a click in my application is there a way I can send some input to the mouse driver and achieve this or make a system call to achieve the simulation? Bottom line, I would lik...
Yes, check the/dev/<device>entry in your file system that the driver has created and access the/dev/<device>as a file from your user application and performopen/read/write/closeoperations on it. The correspondingread/writein the driver will be called. If you need to define specific functions then you need to defineioc...
This question already has answers here:Why cast unused return values to void?(10 answers)What does void casting do?(2 answers)Closed9 years ago. I was checking code and I came across the following snippet: ``` int check(char *a) { (void)(a);//What is this line doing?? return 0; } int main(void) { cha...
Some compiler may give a warning if a function parameter is not used in the function,(void)acan silence such warnings. Another commons way to achieve this is: ``` int check(char *a) { a = a; return 0; } ```
``` int i = 5; while(i>5) printf("%d",i); ``` prints nothing. ``` int i = 5; while ( 5<i<10 ) { printf("%d",i); i++; } ``` prints 5 In both the cases shouldn't be the result "prints nothing" . Because 5 is not less than 5.
In C integer is used as a boolean:0isfalse, everything else istrue. As @JonathanLeffler noted (see his comment below), in C99 and C11 there is a standard boolean datatype, but it also expands to integer constants (0and1).Link. When you write an expression like5 < i < 10, it is treated like(5 < i) < 10, where5 < iis ...
I am trying to debug a deadlock/race condition in my multiprocess shared memory program. For some reason it is only deadlocking some of the time. I would like to know what each process is doing at this time so that I can find the bug. Any ideas on how I could use gdb or valgrind for this?
Not a complete answer, just a thought: you may attach to a working process usinggdb -p <processId> /path/to/executable/being/debugged. Or just usestrace -p <pid>. BTW Right now I'm doing this for LibreOffice with KDE4 dialogs plugin hanging on startup (somewhere in libSM interaction) :) A typical race condition, bec...
We are given the prompt (using AT&T ASM) ``` eax = A ebx = B ecx = &X edx = &Y ``` I understand that (%eax) would grab the data in the memory location at A, but what would doing (%edx) grab? Say for example the call ``` movl (%edx), %ebx ``` Also ``` movl %eax, (%ecx) ``` Does the first ca...
From the 'C' language perspective: ``` eax = A ``` eax gets a copy of the value of A. ``` ebx = B ``` ebx gets a copy of the value of B. ``` ecx = &X ``` ecx gets the address (or memory location) of X. ``` edx = &Y ``` edx gets the address (or memory location) of y.
How is memory allocated when recursive functions are called? A function has it's own allocated memory. When it is called, the parameters (not reference-passed ones) and variables get memory. So when the function is called again from within it's body, how is memory allocated to the variables and parameters of the secon...
A recursive function is no different from any other function--automatic local variables are allocated as a single block by advancing the stack pointer far enough to account for the sum of their sizes (plus any padding required for alignment). Each recursive call pushes a new stack frame in that manner, then pops it w...
Programming newbie, I want to disable the compiler/linker and just look at the precompile/ preprocessor's preprocessed code for a program...not sure what this would be called or what the usual method is for doing something like this. Using the GNU GCC compiler in Code::Blocks, and I looked thru all the various option...
gcc -E source.c -o myfile.i Here -E is a flag stand's forPRE-Processonly. And -o is another flag which stores the PRE-Processed output of source.c into myfile.i (here .i is common extension given for PRE-Processed files in gcc)
I'm allocating memory for a 2d array dynamically using the below code, ``` int **matrix = (int **) malloc(testVals[m].rows*sizeof(int)); for(int i = 0 ; i < testVals[m].rows ; i++) matrix[i] = (int *) malloc(testVals[m].columns*sizeof(int)); ``` but I'm in need to add extra rows and columns as per requirements. ...
You can usereallocon each row if you need to add a column: That is, if you need to add N columns, you realloc each row by extending each of them by N. EDIT: You can look at thispossible duplicate
I'm trying to make a program in c90 which will read some words from a txt file and copy them to a matrix array. It seems that the compilation is all right but there is a thread named "EXC_BAD_ACCESS(code=1 adress=0x68). can you help me figure out where the problem is?? ``` int main(int argc, char *argv[]) { FILE *in...
Check that your file is actually being opened, otherwise printf() will try to print out random memory which may go beyond the bounds of what you have actually allocated and cause an error. ``` input = fopen("test.txt", "rt"); if (!input) { perror("Failed to open file"); exit(1); } ``` You may also want to ch...
In the example below: ``` #include <stdio.h> #include <stdlib.h> void test1 (int x) { int * xp = &x; printf("Address of xp (test1): [%p]\n", &xp); printf("xp points to: [%p] which is the same as [%p]\n", xp, &x); } int main() { int x = 4; printf("Address of x (main): [%p] \n", &x); test1(x);...
That is defined by the implementation. It's very likely on the machine stack, since the stack is very common way to implement both argument-passing and local variables. The stack space is freed when thetest1()function exits, so the memory in question can be re-used.
For GCC 32 bits, -1 >> 1 returns me FFFFFFFF, but I thought after 2's complement, I will get 0111 1111 ... 1111 which should be 7fff ffff. did i miss something?
Undermostimplementations, that operator does anarithmetic shiftfor signed types, so it preserves thesignbit (which is the leftmost bit), in this case1. As @Clifford correctly pointed out, the language standard leaves the implementation of>>up to the implementor. See theWikipedia articlefor details.
There are several basic MPI datatypes however, what if it is needed to send/receive an instance of a class. If this is possible, could you give an example?
To send astruct, you may useMPI_Type_create_structhttp://www.mpich.org/static/docs/v3.1/www3/MPI_Type_create_struct.html Here is an example of how to do so : http://mpi.deino.net/mpi_functions/MPI_Type_create_struct.html Bye,
How is memory allocated when recursive functions are called? A function has it's own allocated memory. When it is called, the parameters (not reference-passed ones) and variables get memory. So when the function is called again from within it's body, how is memory allocated to the variables and parameters of the secon...
A recursive function is no different from any other function--automatic local variables are allocated as a single block by advancing the stack pointer far enough to account for the sum of their sizes (plus any padding required for alignment). Each recursive call pushes a new stack frame in that manner, then pops it w...
Programming newbie, I want to disable the compiler/linker and just look at the precompile/ preprocessor's preprocessed code for a program...not sure what this would be called or what the usual method is for doing something like this. Using the GNU GCC compiler in Code::Blocks, and I looked thru all the various option...
gcc -E source.c -o myfile.i Here -E is a flag stand's forPRE-Processonly. And -o is another flag which stores the PRE-Processed output of source.c into myfile.i (here .i is common extension given for PRE-Processed files in gcc)
I'm allocating memory for a 2d array dynamically using the below code, ``` int **matrix = (int **) malloc(testVals[m].rows*sizeof(int)); for(int i = 0 ; i < testVals[m].rows ; i++) matrix[i] = (int *) malloc(testVals[m].columns*sizeof(int)); ``` but I'm in need to add extra rows and columns as per requirements. ...
You can usereallocon each row if you need to add a column: That is, if you need to add N columns, you realloc each row by extending each of them by N. EDIT: You can look at thispossible duplicate
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.Closed9 years ago.Improve this question What scripting languages can only interface to libraries that implement a C API? Assume w...
Pretty much all the major languages have a runtime based in C and require you to directly or indirectly through FFI interface through a C API/ABI, these include but are not limited to the following. SquirrelLuaRubyPythonJavaScript
I've written and compiled files before but today I receive this error message ``` dawas-mbp:~ dawasherpa1$ /Users/dawasherpa1/Desktop/Programming 1/Strings/bin/Debug/Strings -bash: /Users/dawasherpa1/Desktop/Programming: No such file or directory dawas-mbp:~ dawasherpa1$ ```
There is aspacein the directory name "Programming 1", so that with ``` $ /Users/dawasherpa1/Desktop/Programming 1/Strings/bin/Debug/Strings ``` the shell tries to execute "/Users/dawasherpa1/Desktop/Programming" with the argument "1/Strings/bin/Debug/Strings". You have to enclose the entire path in quotation marks ...
I have a function that returns a type of struct that I've defined: ``` typedef struct irPulseSet { int pulseCount; int (*pulses)[2]; } irPulseSet; irPulseSet irReadPulse() { irPulseSet outputPulseSet; //some stuff return outputPulseSet; } ``` But I'm calling it inside of a loop: ``` while(1) { ...
The variablecurrentlPulseSetis living on the stack. When it goes out of scope it will be removed from memory automatically. You don't have to do anything.
could we reallocated a shared memory ? by passing it's address toreallocfunction , if NO , how I can reallocate the shared memory ?
You can callmremap(). Alternatively, you can callmmap()again, copy the data, andmunmap()the original.
I'm coding for pebble and it doesn't allow to usefree() I want to get current time and this works. But I'm not sure if it's memory safe. I meants- is a pointer and I think it will need to be free() after use ``` struct tm *ts; time_t timestamp = time(NULL); ts = localtime(&timestamp); ``` Will it be memory leak...
No, there is no leak. The function returns a pointer to an internal object, which hold the correct data untul the next call to localtime().
Using ``` char *addr = getenv("CNFG") ``` I get ``` 0x7fffffffebea ``` Then debugging my program I get this error message: ``` (gdb) x/ls 0x7fffffffebea 0x7fffffffebea: <Address 0x7fffffffebea out of bounds> ``` How do I to examine the contents of that environment variable (in order to to check that has a vali...
I get0x7fffffffebea It's not clear from your question, but you likely get that value when running program outside of GDB. That value should change from run to run (due to address space layout randomization),andyou should get a different value inside GDB (due to differences in stack layout when running under GDB). In...
The code is, ``` #include <stdio.h> #include <string.h> main() { int a, b, s; char ch; LOOP: printf("enter digits \t"); scanf("%d %d", &a, &b); s = a + b; printf("\n answer is %d", s); printf("\n add another no.? (yes/no) : \t"); scanf("%c", &ch); if (ch == "yes") goto LOO...
First if you want to store "yes" you will need a char array, not a single char. Then you can not compare char arrays with string literals like this:ch == "yes", you have to use "string compare",strcmporstrncmp.
Given thestruct task_structto work with. What's the best way to determine how old a process is? Thetask_structis used to hold specific pointers to it's next youngest sibling, and oldest child. That no longer seems to be available in some kernel versions. I'm specifically using the Android goldfish kernel. I've bee...
I think you can use real_start_time or start_time in task_struct. It is updated at the time of process creation ``` struct timespec start_time; /* monotonic time */ struct timespec real_start_time; /* boot based time */ ``` Note: this is vanilla kernel no idea about android kernel
``` #include <stdio.h> main() { int a[5] = {5,1,15,20,25}; int i,j,m; i = ++a[1]; j = a[1]++; m = a[i++]; printf("%d %d %d\n",i,j,m); } ``` Okay now the program compiles and runs fine. But the output which i get is 3 2 15 i.e i =3 , j=2, m = 15. I don't understand how come the value of i b...
I have written the values of the variables before and after the statement gets executes and all side effects have taken place. ``` int a[5] = {5, 1, 15, 20, 25}; int i, j, m; // before : i is indeterminate, a[1] = 1 i = ++a[1]; // after: i = 2, a[1] = 2 // before: j indeterminate, a[1] = 2 j = a[1]++; // after...
I am trying to print all the values in a two dimensional array. I come from Java and I'm having issues figuring this out in C. How do you access the value at two given indices in C? ``` void PrintArrayByPointer(int *ptrToArray) { int i,j; printf("\nPrint Array By Pointers: \n"); for(i=0; i<ROWS; i++) ...
``` printf("%d ", ptrToArray[i*COLS + j]); ``` I assume here that your array is stored in row-major order, which is pretty typical in C and C++.
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.Closed9 years ago.Improve this question What scripting languages can only interface to libraries that implement a C API? Assume w...
Pretty much all the major languages have a runtime based in C and require you to directly or indirectly through FFI interface through a C API/ABI, these include but are not limited to the following. SquirrelLuaRubyPythonJavaScript
I've written and compiled files before but today I receive this error message ``` dawas-mbp:~ dawasherpa1$ /Users/dawasherpa1/Desktop/Programming 1/Strings/bin/Debug/Strings -bash: /Users/dawasherpa1/Desktop/Programming: No such file or directory dawas-mbp:~ dawasherpa1$ ```
There is aspacein the directory name "Programming 1", so that with ``` $ /Users/dawasherpa1/Desktop/Programming 1/Strings/bin/Debug/Strings ``` the shell tries to execute "/Users/dawasherpa1/Desktop/Programming" with the argument "1/Strings/bin/Debug/Strings". You have to enclose the entire path in quotation marks ...
I have a function that returns a type of struct that I've defined: ``` typedef struct irPulseSet { int pulseCount; int (*pulses)[2]; } irPulseSet; irPulseSet irReadPulse() { irPulseSet outputPulseSet; //some stuff return outputPulseSet; } ``` But I'm calling it inside of a loop: ``` while(1) { ...
The variablecurrentlPulseSetis living on the stack. When it goes out of scope it will be removed from memory automatically. You don't have to do anything.
could we reallocated a shared memory ? by passing it's address toreallocfunction , if NO , how I can reallocate the shared memory ?
You can callmremap(). Alternatively, you can callmmap()again, copy the data, andmunmap()the original.
I'm coding for pebble and it doesn't allow to usefree() I want to get current time and this works. But I'm not sure if it's memory safe. I meants- is a pointer and I think it will need to be free() after use ``` struct tm *ts; time_t timestamp = time(NULL); ts = localtime(&timestamp); ``` Will it be memory leak...
No, there is no leak. The function returns a pointer to an internal object, which hold the correct data untul the next call to localtime().
I've just recently learned how to check if a file exists, in C, without opening it with open(). What I wanted to ask is if there is an option or a flag or other instruction that checks if a file exists, but blocks the process until the file exists. Something like this: ``` while(access("socket", F_OK) !=0); ``` But ...
There's no way to do this portably, and on some filesystems (e.g. certain network filesystems) there simply isn't any way to do it at all without periodically checking for the file's existence. That said, there arenonportableapproaches which can cover the majority of platforms in wide use: OS X:FSEventsLinux:inotify...
I made a program that calculates product of all elements in column of a 2D array and stores that value in another 1D array. This is my code: ``` void product_of_col(int n) { int i, j, product; for(i = 0; i < n; i++) { product = 1; for(j = 0; j < n; j++) product *= a[j][i]; ...
You got the order wrong. Replacefor(j = 0; j < n; j++, product *= a[j][i]);withfor(j = 0; j < n; product *= a[j][i], j++);
The memory of a local array is freed once a function exits right? So why does this work when I use a block instead? ``` int main(int argc, char **argv){ char *s2; { char s[] = "testing"; s2 = s; } printf("%s\n", s2); return 0; } ```
It is up to the implementation. The only certain thing is thatsisnot guaranteedto remain accessible, but of course it may as well be. Just undefined behaviour. Hence do not rely on it.
I have the method... char** getStrings();which will return a pointer to char pointers. is it possible to do .. ``` char** allStrings = getStrings()? ``` or must I do something like... ``` char** alStrings = malloc(sizeof(char*) * numberOfStrings); allStrings = getStrings() //where numberOfStrings is some int. ```...
The first one is obviously correct.The second one, after fixing the typo, is equal to the first one plus a memory leak. Please also refer to the functions contract for accessing all those strings, and for deallocation. You probably get aNULL-terminated array of0-terminated strings, but deallocation might be trickier...
This line will compile fine: ``` memcpy(&rp.iplow, &((struct sockaddr_in*) &dstl)->sin_addr, 4); ``` whereas what I originally coined it as: ``` memcpy(&rp.iplow, &((struct sockaddr_in) dstl).sin_addr, 4); ``` will sayerror: conversion to non-scalar type requested Shall I conclude that one cannot use struct types...
Yes you are able to conclude that structure types are not able to cast directly. So you must need to type cast it as shown in first line written by you.
I know that in general sqlite is supposed to be platform independent ->https://www.sqlite.org/onefile.html. In my case I'd like to save 2dimensional c/c++ arrays into the db as blobs as there is no other way to do this. But since the value-types of the arrays as blobs are opaque to sqlite, the db has no chance to trea...
As user3477950 said, SQLite cannot know what BLOBs contain; to it, they're just an array of bytes. No conversion is done regarding endianness, representation, padding, etc.; the bytes it stores are exactly what you give it.
I would like to be able to take any unsigned long integer as an argument for my program. Consider this simplified version. ``` int main (int argc, char* argv[]){ unsigned long int steps; sscanf(argv[1], "%lu", &steps); printf("n is %lu \n",steps); } ``` The problem I have is that if you give it -10 it will re...
You can useatol()and check for the returned value. Here is a little example: ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { unsigned long int steps = 0; if (argc > 1) { if (atol(argv[1]) > 0) steps = atol(argv[1]); } printf("%lu\n", steps); return 0; } ...
I have a UTF8 encoding database. I am using ECPG - PROGRAM C. When I get data recordset with EXEC SQL ``` EXEC SQL DECLARE cur_myTable CURSOR FOR SELECT code, label INTO :hv_cod, :hv_label FROM myTable ``` but I print data in the pgc file, ``` printf("\n libellé => %s", :hv_...
Is it possible to UTF8 decode a host variable to ISO-8859-1 in a program C ? Sure, lots of libraries do it. Look atlibiconvfor example. Is it possible to say in the .pgc file : Postgres I want UTF8-decode values ? Trivially.Setclient_encodingtoiso-8859-1or whatever your local encoding is. You cando this with libpq ...
I have some code in C to print out lines of text in different colors. It's working onLinuxusing escape characters (for examplehere).It's working onWindowsusingSetConsoleTextAttribute But my problem is when using Cygwin.Escape characters don't work on Cygwin.And calls toGetConsoleScreenBufferInfoalways failed, andget...
Thanks SzG and M Oehm for you comments. As you said, M Oehm, the linux example is working. I found the problem in my code. I was using the color value forWindowsinstead of the ones forLinux. For example: ``` _ftprintf(target, TEXT("%c[%d;%dm%s%c[K\n"), 0x1B, foreground, background, printBuffer, 0x1B); `...
This question already has answers here:Fastest way to find out minimum of 3 numbers?(10 answers)Closed9 years ago. I'm working on algorithm that heavily uses min() function to find the smallest number of three numbers. Program is written in C/C++ language. Temporarily I use min( number1, min(number2, number3)) But ...
As long as your compiler is optimizing that's probably as good as you're going to get. ``` #include <algorithm> int test(int i, int j, int k) { return std::min(i, std::min(j, k)); } ``` compiled withg++ -S -c -O3 test.cppI get ``` cmpl %edi, %esi movl %edx, %eax cmovg %edi, %esi cmpl %edx, %esi cmovle...
I want to end the program when a user inputs "0" which is working fine when I am using the do/while loop but now I don't want the "0" to appear on the output... I just want the program to end when the user inputs 0 but not count it as the output line This is my input: (per line) ``` 1.0 0.2 10.0 20.0 0 ``` Here is ...
``` do { scanf("%f", &value); if (value != 0) { *(fArray + counter) = value; counter++; } } while (value != 0); ```
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do...
GitHub has many open source projects with many files. Just searchC(orC++) as the language andthousands of open source projects will appear.
In C, we can convertvoid*to any other pointers. But C++ forbids it. ``` int *a = malloc(4); ``` leads to this error: ``` invalid conversion from ‘void*’ to ‘int*’ [-fpermissive] ``` Are there any latent dangers here in c++? Are there any examples of c++?
The reason you cannot implicitly convert fromvoid *is because doing so is type unsafe and potentially dangerous. C++ tries a little harder than C in this respect to protect you, thus the difference in behavior between the two languages. Consider the following example: ``` short s = 10; // occupies 2 bytes in memory ...
Working on a simple school problem using C to calculate sine of 1 radian. ``` #include <stdio.h> #include <stdlib.h> #include <math.h> int main(int argc, const char * argv[]) { double radian = (180 / M_PI); double y = sin(radian); printf("The sine of 1 radian is %.3f", y); return 0; } ``` The ...
180 / piis one radian IN DEGREES.But thesin()function takes a value in radian.So it's justsin(1).
I want to use the file exchange about kd-tree in matlab and search in mathwork site and saw the below m-files but I cant understand how can I mex files. in comments "Kuan-Ting Yu" say: 1. use mex -setup to find your compiler. E.g. VS 2010 2. in "kdtree_common.h", replace #include "c:/.../mex.h" with "mex.h" 3. dir t...
To mex all source files, you have to call themexfunction. To call mex for all cc-files in a directory, use ``` for file = dir('*.cc'); mex(file.name) ; end ```
My program in c gives me strange output. ``` #include<stdio.h> #include <math.h> int main() { int a,b; float c; printf("Input values of a i b: \n"); scanf("%f%f",&a,&b); c =a*(a+b)/(float)((a+b)*(a+b)); printf("Resoult of expression is: %f\n", c); } ``` Resault is always like: -1.#IND00 Why does it happends...
You are reading inintvalues using the%fformatter flag, which is meant forfloat.aandbare of typeint, so you want to use%d.
I'm building a node-webkit app and want to be able to take screenshots of external apps that users are running. Is there a cross-platform (MIT or open source) solution for this? Perhaps there's a C library that can handle this and I can link it in my node app? Any advice is greatly appreciated.
If you want to use python. python's Wx library you can make it cross platform. ``` import wx app = wx.App(False) s = wx.ScreenDC() w, h = s.Size.Get() b = wx.EmptyBitmap(w, h) m = wx.MemoryDCFromDC(s) m.SelectObject(b) m.Blit(0, 0, w, h, s, 0, 0) m.SelectObject(wx.NullBitmap) b.SaveFile("screenshot.png", wx.BITMAP_TY...
I have a binary tree data structure with the following footprint. I am using C. Node is a struct containing ``` Node* left Node* right int key; VECTOR data; ``` The tree is balanced by the keys (e.g. the node left of the current one has a lower key value) , not the data. I want to find the node with the largest ...
I would try something along the lines of ``` int find_max_data_size( Node * p ) { if( !p ) return 0; int const left_size = find_max_data_size( p->left ); int const right_size = find_max_data_size( p->right ); int const my_size = get_size( p->data ); return max( left_size, right_size, my_size ); } ``` an...