question
stringlengths
25
894
answer
stringlengths
4
863
My project uses boost while there are two version of boost(The old one is used for other projects). In my CMakeList.txt, I usefind_packageto find boost. Unfortunately, it finds an old version of boost, how to solve this case? My solution is use a var to overwrite${Boost_INCLUDE_DIRS}, is there any elegant solution? ...
You can add the version you want to the find_package command, i.e.find_package(Boost 1.50 REQUIRED). Seethis question.
This might be obvious but, can a void pointer safely point to another pointer? i.e. point to a type int * ``` int i = 5; int *ip = &i; void *vp = &ip; int *nip = *(int **)vp; int ni = *nip; // == 5? ``` EDIT: Sorry maybe I'm not being clear, I would like to know if a void pointer can POINT TO a section of memory th...
Yes, you can convert any object pointer tovoid *and back to the original pointer type without loss of information. From the horse's mouth: (C99, 6.3.2.3p1) "A pointer to void may be converted to or from a pointer to any incomplete or object type. A pointer to any incomplete or object type may be converted to a point...
I am taking a university course in computer architecture so I am new to assembly language. My question is, how do I translate the following code from C to MIPS assembly language without using pseudoinstructions? ``` B [8] = A [i-j] ``` i and j are assigned to registers $s3 and $s4 and the base address of A and B are...
No. Instead calculate the address needed by adding $t0 to $s6. ``` sub $t0, $s3, $s4 sll $t0, $t0, 2 add $t0, $t0, $s6 lw $t1, 0($t0) sw $t1, 32($s7) ```
I executed the following code. ``` #include <stdio.h> int main() {char *a="awake"; printf("%s\n", *(a+1)); return 0; // expected out_put to be wake } ```
You're dereferencing the pointer, which makes it acharbut trying to output a string. Change your print statement toprintf("%s\n", a+1);
This question already has answers here:In C, why is sizeof(char) 1, when 'a' is an int?(5 answers)Size of character ('a') in C/C++(4 answers)Closed9 years ago. Why is the output for the following program 4? ``` #include <stdio.h> int main() { printf("%d\n", sizeof('3')); return 0; } ```
Because the type of a character constant isint, notchar(and the size ofinton your platform is four). The C99 draft specification says: An integer character constant has type int. This might seem weird, but remember that you can do this: ``` const uint32_t png_IHDR = 'IHDR'; ``` In other words, a single character ...
This question already has answers here:How to set breakpoints on future shared libraries with a command flag(3 answers)Closed9 years ago. Setting breakpoint on shared library: ``` (gdb) b file.c:278 No symbol table is loaded. Use the "file" command. Make breakpoint pending on future shared library load? (y or [n]...
See "help set breakpoint pending", or "apropos pending".
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ...
Because the type ofiisdouble, and the size ofdoubleon your platform is 8. The line of weird casts doesn't matter, it doesn't change the declaration ofi, nor thesizeofinvocation.
In our code base we have a part of software that allows to run an arbitrary amount of external programs and monitor their exit codes via the use of fork() and the installation of a SIGCHLD handler. In the unit test cases this piece of software works fine. However the process that is running this fork "server" is also...
After fork(), signal handlers are inherited. So perhaps you should reset them to their defaults between fork() and exec(), by using signal() with SIG_DFL in the first child process, before you invoke the legacy software.
What mark does a language leaves on a compiled library that we need language bindings if we have call its functions from a different language? object code looks 'language free' to me. While learning OpenGL in c in Linux environment I have across language bindings.
Binding provides a simple and consistent way for applications to present and interact with data. Source: The tag under your question
I'm writing some C code using the libxml2 library to read an XML file. There seem to be two different functions for this purpose,xmlParseFileandxmlReadFile, and and I'm not sure of the difference between them (besides the fact that xmlReadFile() takes some additional parameters). The examples on the libxml2 website ...
xmlReadFile() is a bit more powerful as it is able to take an URL instead of a local file path, and allows to specify more options (http://xmlsoft.org/html/libxml-parser.html#xmlParserOption), so I tend to use it instead of xmlParseFile(). That said, if you are parsing a local XML file and not using the parser option...
Is there any benefit to aligning my data in an mmap()ed file? i.e if data for an object to be read is offset with a multiple of the OS'es page size from the start of the file (or mmap?). Would this result in faster read performance because less page faults are generated and the OS doesn't have to swap data in and out...
From reading around I have the answer. If a small piece of data will cross the boundary of a page, it's probably better to align it with the next page as the OS loads data from the disk pages at a time.
I am using the code ``` while(fscanf(input, "%49[^@ ]@%49s -> %49[^@ ]@%49s", sender, trash, receiver, trash) != EOF){ printf("%s " "%s\n", sender, reciever); } ``` to try to read and print every line from a file however when I run this code it gets stuck in an endless loop printing the first line of the file ove...
``` #include < stdio.h > FILE *fr; main() { int n; char line[80]; fr = fopen ("test.txt", "r"); /* open the file for reading */ while(fgets(line, 80, fr) != NULL) { /* get a line, up to 80 chars from fr. done if NULL */ sscanf ( line ); } fclose(fr); /* close the file prior ...
I executed the following code. ``` #include <stdio.h> int main() {char *a="awake"; printf("%s\n", *(a+1)); return 0; // expected out_put to be wake } ```
You're dereferencing the pointer, which makes it acharbut trying to output a string. Change your print statement toprintf("%s\n", a+1);
This question already has answers here:In C, why is sizeof(char) 1, when 'a' is an int?(5 answers)Size of character ('a') in C/C++(4 answers)Closed9 years ago. Why is the output for the following program 4? ``` #include <stdio.h> int main() { printf("%d\n", sizeof('3')); return 0; } ```
Because the type of a character constant isint, notchar(and the size ofinton your platform is four). The C99 draft specification says: An integer character constant has type int. This might seem weird, but remember that you can do this: ``` const uint32_t png_IHDR = 'IHDR'; ``` In other words, a single character ...
This question already has answers here:How to set breakpoints on future shared libraries with a command flag(3 answers)Closed9 years ago. Setting breakpoint on shared library: ``` (gdb) b file.c:278 No symbol table is loaded. Use the "file" command. Make breakpoint pending on future shared library load? (y or [n]...
See "help set breakpoint pending", or "apropos pending".
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ...
Because the type ofiisdouble, and the size ofdoubleon your platform is 8. The line of weird casts doesn't matter, it doesn't change the declaration ofi, nor thesizeofinvocation.
I'm just trying to malloc an array of strings and copy input from a file into this array. This combination of lines causes a segfault and I don't know why. ``` int count = 0; char **output = (char**)malloc(numLines*257); fgets(output[count], 257, input); ```
You've allocated space for an array of pointers, but you haven't initialized any of those pointers. ``` int count = 0; char **output = malloc(numLines*sizeof(char *)); int i; for (i = 0; i < numLines; i++) { output[i] = malloc(257); } fgets(output[count], 257, input); ```
I have a function that works, but I would like to know whystatic char out[0];does not produce a warning when it needs to allocate statically memory in scope? What is the correct value for the size ofoutin this example?: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> char *hex(char *s) { int i, l ...
No C compiler I know of gives warnings for out-of-bounds array accesses. You're on your own for maxing sure the array index is in bounds.
I need to step through this program, but the icons related to debugging are greyed out, even if I set the configuration to 'debug'. Any idea how this is supposed to work? ``` #include <stdio.h> int main( void ) { int number = 7; printf ( "%d", number % 2 ); number = number / 2; printf ( "%d", number % 2 ); ...
Found out how to do it: At least there needs to be a Makefile which can be used by gdb. The one created by Anjuta when creating a new C Makefile project can be used as basis. Also, gdb needs to be enabled in the settings window. 1.Click "Add breakpoint" in the toolbar 2.Execute > Debug program Then the buttons beco...
I saw the following code from somewhere: ``` while(*i++ = *j++) { } ``` but what is this code doing? what is the meaning of it?
It copies elements from an array (or a pointer to an array) calledjto one calledi. It does this until it finds a value (fromj) which is equivalent to zero. This is a common idiom for copying C-style, null-terminated strings; it could also be used to copy an array of integers terminated by a sentinel zero. In case t...
I am trying to create a matrix in C in order to solve the LaPlacian However, this is going wrong. I have located the problem at the initialisation stage of the matrix. Every time the program is run, it places a seemingly random value in one element. This number changes each time suggesting an instability in the code,...
You are looking at an element past the end of each array. Your for loops should use<and not<=: ``` for (i = 0; i < meshno; ++i) { for(j = 0; j < meshno; ++j) { ```
In file.txt I have the following content: ``` We are in 2012 ``` I want to print the second char i.e "e", but the following program is showing blank. ``` #include <stdio.h> #include <stdlib.h> int main() { char c; FILE *file; file = fopen("file.txt", "r"); c = getc(file+1); putchar(c); fclose(file)...
file is not a pointer to a memory buffer. ``` FILE* file; ``` It's pointer to a file structure. By providing (file+1) argument to getc(), you just provided it with an uninitialized area as input. The answer is pretty simple : either call getc() twice; or, as it may be an exercise, you can use fseek(), to move the f...
Is there a way to set a breakpoint for C code in Visual Studio inside a#define? When I set the breakpoint it isn't reached, and the rest code continues to be executed. For example: ``` #define YY_USER_ACTION sn_yylloc.first_line = sn_yylloc.last_line =sn_yylineno; \ sn_yylloc.first_column = sn_yycolumn; \ sn_yylloc.l...
This#defineis being expanded by the preprocessorbeforecompilation. What you could do is try to run with the Visual Studio debugger with this code instead of the original code (readthis questionabout getting your hands on the preprocessed code).
How can I enable and disable (clear and setGIESRbit) in C using themspgcc?
``` /*interrupt.c ganeshredcobra@gmail.com GPL */ #include <msp430g2553.h> #define LED1 BIT0 #define LED2 BIT6 #define BUTTON BIT3 volatile unsigned int i;//to prevent optimization void main(void) { WDTCTL=WDTPW+WDTHOLD; P1DIR |= (LED1+LED2);// P1OUT &= ~(LED1+LED2); P1IE |= BUTTON; P1IFG &= ~BUTTON; //__enable_inter...
I am writing a custom handler and wanted to see how stable it is and just let my browser request the same URL over and over. It doesn't crash but I get some messages like the one in the title. I.e. conn 0x7f7d6c001610 error: i=-2 errno=11 state=4 rc=3 br=721 This also happens when I execute the "hello" example but ...
This error report is not critical. This means connection to client dropped for some reason before request has been fulfilled.
I read some legacy code: ``` if ( 1 || !Foo() ) ``` Is there any seen reason why not to write: ``` if ( !Foo() ) ```
The two arenotthe same. The first will never evaluateFoo()because the1short-circuits the||. Why it's done - probably someone wanted to force entry in thethenbranch for debugging purposes and left it there. It could also be that this was written before source control, so they didn't want the code to be lost, rather ju...
I want to use a static keyword in many place of an implementation file (.m file), and somewhere I need to use an NSString object of this keyword. So I want to use C macro to define a string object with the keyword. For example: ``` #define NSStringFromKeyword(aKeyword) @"aKeyword" // This will not work @implement...
``` #define NSStringFromKeyword(aKeyword) @#aKeyword ``` It's calledstringification
This question already has an answer here:Why does the address of a variable keep changing between runs? [duplicate](1 answer)Closed9 years ago. sometimes p=3,which memory &p=somehexadecimal and this values changing frequently .why its memory value changing?Is that possible to maintainconstant memory value for p?
If you use a variable in static memory, it will be located at the same address through the run of the program. A global is an example, astaticclass member, namespacestaticor function-scopestatics are others.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question I am a beginner and I need to know how to put a large string like a page full of string pointed to by a poi...
You wantstrncpy. ``` const char *src = "Some string"; const int BUF_SIZE = 64; char buf[BUF_SIZE]; strncpy(buf, src, sizeof buf); buf[BUF_SIZE-1] = '\0'; ``` strncpy, unlikestrcpy, takes an additional parameter; the size of the supplied buffer. This helps to combat buffer overflows.
How can I enable and disable (clear and setGIESRbit) in C using themspgcc?
``` /*interrupt.c ganeshredcobra@gmail.com GPL */ #include <msp430g2553.h> #define LED1 BIT0 #define LED2 BIT6 #define BUTTON BIT3 volatile unsigned int i;//to prevent optimization void main(void) { WDTCTL=WDTPW+WDTHOLD; P1DIR |= (LED1+LED2);// P1OUT &= ~(LED1+LED2); P1IE |= BUTTON; P1IFG &= ~BUTTON; //__enable_inter...
I am writing a custom handler and wanted to see how stable it is and just let my browser request the same URL over and over. It doesn't crash but I get some messages like the one in the title. I.e. conn 0x7f7d6c001610 error: i=-2 errno=11 state=4 rc=3 br=721 This also happens when I execute the "hello" example but ...
This error report is not critical. This means connection to client dropped for some reason before request has been fulfilled.
I read some legacy code: ``` if ( 1 || !Foo() ) ``` Is there any seen reason why not to write: ``` if ( !Foo() ) ```
The two arenotthe same. The first will never evaluateFoo()because the1short-circuits the||. Why it's done - probably someone wanted to force entry in thethenbranch for debugging purposes and left it there. It could also be that this was written before source control, so they didn't want the code to be lost, rather ju...
I want to use a static keyword in many place of an implementation file (.m file), and somewhere I need to use an NSString object of this keyword. So I want to use C macro to define a string object with the keyword. For example: ``` #define NSStringFromKeyword(aKeyword) @"aKeyword" // This will not work @implement...
``` #define NSStringFromKeyword(aKeyword) @#aKeyword ``` It's calledstringification
This question already has an answer here:Why does the address of a variable keep changing between runs? [duplicate](1 answer)Closed9 years ago. sometimes p=3,which memory &p=somehexadecimal and this values changing frequently .why its memory value changing?Is that possible to maintainconstant memory value for p?
If you use a variable in static memory, it will be located at the same address through the run of the program. A global is an example, astaticclass member, namespacestaticor function-scopestatics are others.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question I am a beginner and I need to know how to put a large string like a page full of string pointed to by a poi...
You wantstrncpy. ``` const char *src = "Some string"; const int BUF_SIZE = 64; char buf[BUF_SIZE]; strncpy(buf, src, sizeof buf); buf[BUF_SIZE-1] = '\0'; ``` strncpy, unlikestrcpy, takes an additional parameter; the size of the supplied buffer. This helps to combat buffer overflows.
I have created the program and generate code below #include <stdio.h> int main(){ int a,i; scanf("%d",&a); while(a!=-1){ if(a>=0 && a<=80){ for(i=a;i<=a;i++) printf("|"); printf("%d\n"); scanf("%d",&a); } } with input 1 3 4 4 5 5 -1, it should be display a bar chart like | | | | | | | | | | | ...
``` for(i=a;i<=a;i++) ^ maybe you want 0 here? ``` printf("%d\n");also looks wrong,%dis a formate string uses to print value ofint. To print simply newline char it should be justprintf("\n");
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'm working on a project where I need to integrate 2 simulation software packages; as in ...
Is SOAP or RESTful service an option? That would work in both C and C++
I have write a program by C and run it in Ubuntu,the main code is follow: ``` int main(){ pid_t pid=fork(); if(pid==0){ printf("d"); exit(0); } else{ printf("a"); sleep(4); } } ``` The question is: why the codesleep(4);run beforeprintf("a"); hope someone can g...
It is not. Most probably,printf()buffered its output until a chance to output the buffer (in your case, when the process terminated).
If I were to do something like: ``` printf("The string is: %s\n", "string1"); ``` Is the following done at compile time: ``` printf("The string is: %s\n", (unsigned char*) "string1"); ``` Or similar?
It is defined by the standard that the type of string literals is an array ofchar1and arrays automatically decay to pointers, i.e.char*. You don't need to cast it explicitly while passing it as an argument toprintfwhen%sspecifier is used. Side note: In C++ it'sconst char*2. [1]C99 6.4.5:"A character string literal...
Does C support pass by const reference like C++? If not, are there other ways to make pass-by-value more efficient? I don't think it makes sense to pass references to a function only because it's more efficient.
C does not support references or passing by reference. You should use pointers instead and pass by address. Pass-by-value is efficient for primitive types, but does a shallow copy for structs. In C++ it makes a LOT of sense to pass objects by reference for efficiency. It can save a ton of copying and calling of con...
Why is the following illegal in C? ``` y = (w + x)++; ``` According to my book, this is illegal, but I don't see why.
Ini++, thevalueofiis changed. After execution,i's value is one plus its previous value. You can't store a value inw+x, though, and so you can't do any of the following, which all (if they worked) would have more or less the same effect: ``` w+x = w+x+1; w+x += 1; (w+x)++; ``` Something that can be placed on the le...
Beginner's question - How do I use k in the command string? ``` #include <stdio.h> #include <stdlib.h> int main() { int k; for(k = 0; k < 5; k++) { // make k appear in place of USE_K_HERE char argv[] = "./a.out -k USE_K_HERE < test.txt"; system(argv); } } ```
You can use snprintf in the loop body: ``` char cmd[100]; snprintf( cmd, sizeof(cmd), "./a.out -k %d < test.txt", k ); system(cmd); ``` http://en.cppreference.com/w/cpp/io/c/fprintf
When I run the below program, I do not get any output. ``` #include <stdio.h> int main() { printf("hello"); while(1) { } return 0; } ``` whereas if i edit the printf command to add a '\n' character to the end of the string, then the expected output comes. what is going on in the first code? ...
This is because stdout isline buffered, i.e. the output is not written to the device (the terminal) until a full line has been collected. You can callfflush(stdout);to force a flush of the buffer to the terminal. Do not try to flushingstdinby the way, that's not allowed.
I have char array: ``` char c[10]="ff213"; ``` and I need to cast one element of char to int. I tried this: ``` int i=atoi(c[2]); ``` But I get Runtime error. And this: ``` int i=(int)c[2]; ``` But it returns 50 instead of 2. How can I do that?
Like so: ``` const int digit2 = c[2] - '0'; ``` This works because C guarantees that the encodings for the decimal digits are in sequence and without any gaps. This is not (as you can see) a "cast", it's just plain computation. If you cast the character, you get the encoding's representation as an integer, in your ...
Asssume thatgetNumberis 65432I want to store the number to each arrays Example: ``` number[0] = 6 number[1] = 5 number[2] = 4 ``` How should I do? ``` char input[32]; char getNumber[32]; int number[20]; fgets(input,sizeof(input),stdin); sscanf(input,"%s",number); ```
What you are actually trying to do could look like this: ``` int digits[20]; char word[20]; sscanf(input, "%19s", word); // <-- read word int i, len = strlen(word); for (i = 0; i < len; ++i) digits[i] = word[i] - '0'; // <-- get integral value of each character ```
When I compile a C project it can take about 90 seconds even though I use a fast Intel I7 CPU. Is it because compilation is a low-level task or why are my build times so long? My environment is the Nios 2 IDE for Altera DE2 FPGA.
if your project is managed by Makefile, try "make -jn" to trigger mul-threads in compiling, n is thread num for compiling, e.x. "make -j10"
I have write a program by C and run it in Ubuntu,the main code is follow: ``` int main(){ pid_t pid=fork(); if(pid==0){ printf("d"); exit(0); } else{ printf("a"); sleep(4); } } ``` The question is: why the codesleep(4);run beforeprintf("a"); hope someone can g...
It is not. Most probably,printf()buffered its output until a chance to output the buffer (in your case, when the process terminated).
If I were to do something like: ``` printf("The string is: %s\n", "string1"); ``` Is the following done at compile time: ``` printf("The string is: %s\n", (unsigned char*) "string1"); ``` Or similar?
It is defined by the standard that the type of string literals is an array ofchar1and arrays automatically decay to pointers, i.e.char*. You don't need to cast it explicitly while passing it as an argument toprintfwhen%sspecifier is used. Side note: In C++ it'sconst char*2. [1]C99 6.4.5:"A character string literal...
Does C support pass by const reference like C++? If not, are there other ways to make pass-by-value more efficient? I don't think it makes sense to pass references to a function only because it's more efficient.
C does not support references or passing by reference. You should use pointers instead and pass by address. Pass-by-value is efficient for primitive types, but does a shallow copy for structs. In C++ it makes a LOT of sense to pass objects by reference for efficiency. It can save a ton of copying and calling of con...
Why is the following illegal in C? ``` y = (w + x)++; ``` According to my book, this is illegal, but I don't see why.
Ini++, thevalueofiis changed. After execution,i's value is one plus its previous value. You can't store a value inw+x, though, and so you can't do any of the following, which all (if they worked) would have more or less the same effect: ``` w+x = w+x+1; w+x += 1; (w+x)++; ``` Something that can be placed on the le...
Beginner's question - How do I use k in the command string? ``` #include <stdio.h> #include <stdlib.h> int main() { int k; for(k = 0; k < 5; k++) { // make k appear in place of USE_K_HERE char argv[] = "./a.out -k USE_K_HERE < test.txt"; system(argv); } } ```
You can use snprintf in the loop body: ``` char cmd[100]; snprintf( cmd, sizeof(cmd), "./a.out -k %d < test.txt", k ); system(cmd); ``` http://en.cppreference.com/w/cpp/io/c/fprintf
When I run the below program, I do not get any output. ``` #include <stdio.h> int main() { printf("hello"); while(1) { } return 0; } ``` whereas if i edit the printf command to add a '\n' character to the end of the string, then the expected output comes. what is going on in the first code? ...
This is because stdout isline buffered, i.e. the output is not written to the device (the terminal) until a full line has been collected. You can callfflush(stdout);to force a flush of the buffer to the terminal. Do not try to flushingstdinby the way, that's not allowed.
I have a NUMA machine of 2 nodes. I want to allocate the two halves of an array on the two nodes respectively. How can I do that? Please note that by "half" I mean a continuous chunk of virtual memory. I found the function numa_alloc_interleaved, but it doesn't satisfy my requirement.
You have a couple of choices. You can have one piece of code that usesnuma_alloc_onnodeto allocate a block on each node you want to use, then give control/ownership of that block to the code running on that node. Alternatively, you can start the code on each node, then have each node's code allocate its own memory l...
I know a pointer to a function is 8 byte because of virtualization but why a pointer to a pointer to a function is 8 byte? ``` typedef void(*fun())(); sizeof(fun*); // returns 8 byte ```
If you have a 64-bit system with 8-bit bytes (and it sounds like you do), probablyallpointers will be 8 bytes in size. Virtualization doesn't have anything to do with it.
Is there some "nice" way to check if a variable passed to a macro is a pointer? e.g. ``` #define IS_PTR(x) something int a; #if IS_PTR(a) printf("a pointer we have\n"); #else printf("not a pointer we have\n"); #endif ``` The idea is that this is not done run-time but compile-time, as in: we get different code depend...
On Clang and GCC,__builtin_classify_type(P)evaluates to 5 ifPis an object with a pointer type.
I am passing an array of type int pthread_create and getting error: ``` histogram.c:138:3: warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type [enabled by default] expected ‘void * (*)(void *)’ but argument is of type ‘void * (*)(int *)’ void *output_results(); pthread_create(&t2,...
Should be ``` void *output_results(void*); pthread_create(&t2, NULL, output_results, (void *)bins); void *output_results(void *data) { int *bins = (int*)data; // some code } ``` The error message is pretty clear: the function should be of typevoid * (*)(void *)and notvoid * (*)(int *)(plus your prototype fo...
This question already has answers here:How do function pointers in C work?(12 answers)Closed9 years ago. ``` typedef long (*GuiFunc) (int, int, int, unsigned short*, long, long); ``` Please help me understand the above line of code
``` typedef long (*GuiFunc) (int, int, int, unsigned short*, long, long); ``` Defines new typeGuiFunc.that can declare a function pointer which takes 6 parametersint, int, int, unsigned short*, long, longandreturns long. Assume you have a function like this ``` long foo(int, int, int, unsigned short*, long, long) ...
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 A cron job is created, and in the cron job contains the following code: ``` int flag = s...
The return code is a bitmask of several things (see for examplethis question). In your case it suggests an exit code of 255 (which is purely from your child process, not due to signal). You should check yourmainprogram.
In my case I have a library built with code sourcery gcc targeting arm cortex-m4. I am trying to then link that library into a project being compiled with IAR compiler. Is it possible to do this or does the library have to be rebuilt with the new tools? What factors affect this?
Static library is bundle of several object files which are always compiler specific. So if you try to link agccbased lib withIARcompiler, you will get error at compile time due to mismatch between object file formats to be linked. You need to rebuild your library using IAR.
I am learning C. Why doesn't the static variable increase above1. ``` #include <stdio.h> int foo() { static int a = 0; return a+1; } int main() { int i; for (i = 0; i < 10; i = foo()) printf("%d\n", i); return 0; } ``` Where is the mistake in this code ?
Because you are not storing anything back into it. This should work for you: ``` int foo() { static int a = 0; return ++a; } ``` Herereturn ++ameansa = a + 1, i.e., increment a first then return its value.a+1evaluates to1but does not store anything back intoa
``` char* key; key=(char*)malloc(100); memset(key,'\0',100*sizeof(char)); char* skey="844607587"; char* mess="hello world"; sprintf(key,skey); sprintf(key,mess); printf("%s",key); free(key); ``` why does the printout only have the "mess" don't have skey? is there any other way to combine two strings us...
``` sprintf(key,"%s%s",skey,mess); ``` for adding them separately : ``` sprintf(key,"%s",skey); strcat(key, mess); ```
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question When a C Program is compiled and and executable is created, The exe makes certain assumptions with respect ...
C compilers translate C code to machine code. Machine code is different for different types of CPUs. The number of registers, the word size and memory bus size also varies between different architectures. Also, the interaction with the operating system is not the same. In an embedded system there might not even be an...
My function ``` void myFunction (FILE *f); ``` gets an already opened file. I need to write a literalCR+LF, so I want to setf's mode to binary. How can I do that?
As per comments, perhaps a function such as the following may be useful (untested!) : ``` #include <stdio.h> #ifdef WIN32 #include <fcntl.h> #include <io.h> #endif int SetBinary(FILE *pFile) { // set file mode to binary #ifdef WIN32 return _setmode(_fileno(pFile), O_BINARY); #else return setmode(_fileno...
I was reading some tutorial on endianness. Got the integer part. But the tutorial left of by mentioning whether endianness issues apply also for C style strings, without mentioning correct answer. Does endiannes apply to C style strings? From my understanding, No. am I correct? e.g., if I have string "cap" stored lik...
Endianness only applies to entities which are longer than one byte. Thus,narrowC strings which are arrays ofcharshould be OK. If you have wide strings, however, of typewchar_t[], then you should definitely be concerned about correctly handling endianness.
I am attempting to compile C program on Window platform (currently, it's running on AIX). Problem is: when I build this program, the compiler could not find procinfo.h file. I spent much time to search on the internet but still cannot solve this problem. ``` fatal error: procinfo.h: No such file or directory ``...
AFAIK, procinfo.h is a part of unix kernel headers, it is not available on Windows, at least not in a native Windows development environment (like MSVC). Your specific C program can be written in a way that is not compatible with Windows or might require a significant effort for porting.
I can't seem to understand why is my pointer changing address in this situation : ``` int *load(FILE *fp, int * vector, int w, int h){ //other coding int array[w][h]; int *ptr = &array; return ptr; } main(){ //other coding int *ptr = load(file, vector, w, h); printf("%d ", *(ptr)); pr...
Thearrayaddress you are returning fromload()is local variable of that function. You should never return its address, as its allocated on stack and will be reused for subsequent function calls. The changed values you are seeing are because call toprintf()s are updating that location of stack.
Implementation of my_memcpy (memory copy from source to destination based on size) uses a lot of pointer arithmetic, which is a very common method of implementation. Issue: Based on certain standards, my code is not supposed to use pointer arithmetic, but can use arrays. Is there any way we can implement that functi...
what about the following, ``` unsigned i = 0; while(u32_length >= SIZE){ u32p_dst[i] = u32p_src[i]; ++ i; u32_length -= SIZE; } ```
I am trying to usestrtok()to parse a string deliminated by spaces. From what I can tell, I am using it correctly, but it won't run on ideone.com. Is there anything wrong with the following code? I just getRuntime error time: 0 memory: 2288 signal:11 ``` #include <stdio.h> #include <string.h> #include <stdlib.h> ...
Always consult themanpages first. strtok(3)says: Be cautious when using these functions. If you do use them, note that:These functions modify their first argument.These functions cannot be used on constant strings.
Is it a standard to have only dynamic libraries mostly without their static version? I am particularly asking about math library. In my fedora 17 (linux machine on Intel 32 processor), I have latest gcc and it has libm-2.15.so and symbolic link file libm.so but there is no libm.a. Is libm.a missing on my system?
Install the static libraries: ``` # yum install glibc-static ```
Many places I read thatlibc.ais the gcc standard c library. I could not find it on my system. My system (fedora 17 - linux on intel 32 chip) has latestgccand following files I could find on the disk in/usr/lib: libc.so (238 bytes)libc-2.15.so (2 MB)libc_nonshared.a (20.7 kB) I checked by using -v -wl,--verbose...
It was missing on my system sinceglibc-staticwas not installed. Now I've installed it and I can seelibc.ain/usr/lib.
I'm writing a program to prompt the user to enter a number between 1 and 5. If the value is greater than 5 or less than 1 I want the program to wait until an appropriate answer is given. This is what I came up with and it's not working. I've tried a few different tips off the net and it still isn't working. Any tips w...
You need a variable for each test: ``` while(p1_move >=6 || p1_move <=0); ``` You also have potentially undefined behaviour here: ``` scanf("%d", &p1_move); ``` You do not test whether the input was successful. If the input failed first time around (egEOF or non-integer input),p1_movewill remain uninitialised.
Is it possible to do multiple operations in increment part of for loop in C/C++? Something like this: ``` int a = 0, b = 0, c = 5; for(; a < c; increase a by 1 and increase b by 2) ```
Use the comma operator: ``` for (; a < c; ++a, b += 2) ```
I'm trying to compile a simple "Hello, World" program using gcc in C programming language. I use the following command on a source code file "test.c" (without the quotes). I use the following command: gcc test.c -O -Wall -Werror test I expect this to compile my program and create and executable called test that I ...
gccis treatingtestas an input file name. Assuming you want to usetestas the output file name, you need to use the-ooption. ``` gcc test.c -O -Wall -Werror -o test ^^ ```
I have an old piece of code and it uses Numeric and I wanted to swap that with numpy. There is some C code too that uses the following: ``` #include <Numeric/arrayobject.h> ``` I want to do the same using Numpy, is there a way to do this?
So if anyone is interested -to continue to use arrayobject.h like in the old Numeric system do the following: ``` Replace <Numeric/arrayobject.h> with <numpy/arrayobject.h> ``` But the new arrayobject.h is in a different location to Numeric so update the setup.py as follows: add the following ``` import numpy as ...
I wanted to know what's the difference between these two versions of the main() code in C: ``` int main() { uint32_t a; f(&a); } ``` and ``` int main() { uint32_t *a; f(a); } ``` for a function ``` void f(uint32_t *pointer) { // ... } ```
In your first example, you pass a pointer to uninitialized variablea.f()could store a value there, for instance, andmain()would be able to use that value later. In your second example, you pass an uninitialized pointera.f()can't do anything useful with it.
I have a data type defined by me, and I want to create a matrix of that data type, but I'm not able to use it. I have typedef char data[10]; ``` data **matrix; matrix=(data**)malloc(n*sizeof(data*)); for (i=0;i<x;++i) matrix[i]=(data*)malloc(m*sizeof(data)); matrix[i][j]="example"; ``` But in the last line...
Here ``` matrix[i][j]="example"; ``` you assign to array which is illegal. Try this: ``` strcpy( matrix[i][j], "example" ); ``` Please note thatstrcpyis insecure, use more secure alternative for your system -strlcpyorstrcpy_s. Or you can followH2CO3's suggestion.
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ...
Normally, hidden files have a.at the start of their name. Check whether the first character of the filename is.; if it is.then that is a hidden file and you will not display that file. ``` char *filenames[10]; for (int i = 0; i < 10; i++) if (filenames[i][0] != '.') // Display filename ```
I'm trying to use the functionsisDigit()I have the correct include statement,#include <ctype.h>however, I seem to be getting a warning when I compile, ``` warning: implicit declaration of function 'isDigit' is invalid in C99 [-Wimplicit-function-declaration] ``` The line that compiles the warning isif(isDigit(atoi(i...
include this header file in your program :#include<ctype.h>
In my application, I will be retrieving error message strings from a database. I would like to substitute numbers into the error message. The error message will be a C style string like: ``` Message %d does not exist ``` or ``` Error reading from bus %d ``` Ideally, I would like to be able to do a C style printf u...
Apart for simple string concatenation or using<<together with number and a message. I can think ofboost::format ``` int message_no=5; std::cout << boost::format("Message %d doesn't exist") % message_no ; ```
I've tested this on my Linux box, which has gcc, and compiles fine. ``` void myFunc(int* &input); ``` That compiles with no errors. On my avr, declaring the same function: ``` void myFunc(int* &input); ``` Results in an compilation error: ``` expected ';', ',' or ')' before '&' token ``` gcc version on linux is...
In C (not sure about C++) ``` void myFunc(int* &input); ``` is not a valid declaration.In C, all calls are by value. There is no call by reference unlike C++.
I need to collect all the interface names, even the ones that aren't up at the moment. Likeifconfig -a. getifaddrs()is iterating through same interface name multiple times. How can I collect all the interface names just once usinggetifaddrs()?
You could check which entries from getifaddrs belong to the AF_PACKET family. On my system that seems to list all interfaces: ``` struct ifaddrs *addrs,*tmp; getifaddrs(&addrs); tmp = addrs; while (tmp) { if (tmp->ifa_addr && tmp->ifa_addr->sa_family == AF_PACKET) printf("%s\n", tmp->ifa_name); tmp...
I need to have a context menu (currently created with TrackPopupMenu) close automatically after a period of inactivity. I'm trying to search but only finding the opposite (how toactivatea popup after a timeout) or specialized things for particular applications. The only things I've found that is even close is to enu...
SendWM_CANCELMODEmessage to the parent window that host the context menu .
I have two variables: dataRx (SLAVE::1234)globalAuthcode (1234) and I comparing ``` if(strcmp(dataRx, globalAuthcode) == 0) ``` I can't find function like SUBSTR from PHP :) I want leve only 1234 from dataRx variable.
Use pointer arithmetics: ``` strcmp(dataRx + 7, globalAuthcode) /* ^^^^ */ ``` ThedataRx + 7skips over the first seven characters of the string. Of course, you might want to make sure that the stringisat least 7 characters before doing that.
How can I make multiplication table to look like this:http://i.imgur.com/rR6JSua.png? With my code it only has one column. ``` #include<stdio.h> int main() { int i, j; for(i = 1;i <= 9;i++) { for(j = 1;j <= 9;j++) { printf("%d * %d = %d\n",i , j,i*j); } p...
Try This: ``` #include<stdio.h> int main() { int i, j; for(i = 1;i <= 9;i+=3) { for(j = 1;j <= 10;j++) { printf("%2d * %2d = %2d ",i , j,(i)*j); printf("%2d * %2d = %2d ",i+1 , j,(i+1)*j); printf("%2d * %2d = %d\n",i+2, j,(i+2)*j); } printf("\n"); } return 0; ``` }
How it is possible to write this more laconical but not using memcpy? ``` memcpy(pDest, pSrc, 4); for (int i = 0; i < 4; i++) pDest[i] = pSrc[i]; ``` Because calling memcpy is not optimal sometimes
Here are excellent comments, but since nobody else has yet posted the most obvious answer: Modern compilers are excellent at optimizingmemcpy. It may inline it, or use different versions for different data. Measure your code performance first and draw conclusions based on that. Ifmemcpyseems to be the bottleneck on...
I want to write a simple C program which would print the number of times that program itself got executed (by user). for example, output should beYou are executing this program 3rd time I first thought of using file handling but later came to know aboutvolatileandregister. Is there any use ofvolatileorregisterin t...
No,volatileandregisterare only meaningful within the same run. Instead, store a counter in a file.
my code is ``` #include <stdio.h> int main() { int name; scanf("%d",&name); printf("%d",name); } ``` Why when I enter "Hello","World","Good", etc it must show 2 ? Why 2 not the other number ? If I want to scanf string and printf ASCII code of it how should i do ? thankyou
To print ascii values of an entered string : ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main(){ char array[100]; int i=0; printf("Enter string : "); scanf("%s",array); // fixed as suggested in comments for(i=0;i<strlen(array);i++){ printf("%d-",array[i]); ...
``` #ifndef _WINDOWS if(condition) { printf("to do in linux"); } else #endif { printf("should work in both linux and windows..."); } ``` My question: does this code work for both in linux and windows?
You have more logic than you need - you can just do this: ``` #ifndef _WINDOWS printf("to do in Linux"); // ... #endif printf("to do in both Linux and Windows"); // ... ```
I have this line of code (usingMSSQL): ``` double avg = db.MyTable.Where(x => x.RecordDate < today).Select(z => z.value).Average(); ``` I wonder if this is translated toSQLAVG()function or theAverage()run on client side ? This table contains 50,000 records per day and I prefer to let the database calculate the aver...
If you don't enumerate yourqueryable, yes,averagewill be done on db side. You can also simplify your code. Select is not needed, there's an overload for average taking anExpression<Func<T, double>>(or a decimal, int...) as parameter. ``` double avg = db.MyTable.Where(x => x.RecordDate < today).Average(z => z.value);...
I want the output of the following code as -|-2-|- (When i input the value of key as 2). I know \b just move the cursor to 1 space back but why it isn't able to move one space back after a newline is used to input the value of key. Is it possible to use the escape character \b after a newline character has been used...
Here is a simple solution : ``` #include<stdio.h> int main() { int key; char output[8] = {'\0'}; printf("Enter value of key: )"; scanf("%d",&key); sprintf(output,"-|-%d-|-",key); printf("%s\r\n",output); return 0; } ```
``` #include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { char* key="844607587"; while(*key!=0){ printf("hello world,%c\n",*key); key++;} } ``` Why doesn't the program stop at the zero digit? Then what does the 0 mean? the one without ' '
You made a simple mistake - you are comparing the (most likely ASCII) characters in your string with the numeric value 0. Change: ``` while(*key!=0){ ``` to ``` while(*key!='0'){ ``` Note that The numeric value 0 is the value of the C string terminator, often written as'\0', so your code stops when it reaches the ...
I'm trying to allocate some memory as unsigned char* however when I do the pointer doesn't seem to have been initialized! ``` unsigned char* split = (unsigned char*) malloc ((sizeof(unsigned char)*sizeof(unsigned int))); memset(&split,0,sizeof(int)); if(split==NULL) { std::cout<<"Unable to allocate mem...
Yourmemsetcall doesn't write to the buffer you've just allocated, the one pointed to bysplit. It writes to the area of memory wheresplitvariable itself stored - as pointed to by&split. WhereuponsplitbecomesNULL.
Suppose I have the following code. While debugging, I want Eclipse to stop when it has done 1 million iterations. How to do this? I cannot manually do 1 million times. ``` for(int i = 0; i < 10000000; i++) { //some code } ```
You can put conditional break point in eclipse: Put a breakpointRight-click->PropertiesTurn on "condition" check-boxPut condition codei == 1000000
``` typedef struct s { int x; int y; } S; typedef struct t { S s; } T t = {0}; T *pointer_to_T = &t; printf("End address %x", pointer_to_T->s); printf("Beginning address %x", &(pointer_to_T->s)); ``` Based on my testing, pointer_to_T->s is the address of the end of the structure S ``` pointer_to_T->s - &(p...
The expected behaviour here can range from printing garbage tonasal demons, because this behaviour is undefined. The%xspecifier makesprintfexpect an integer but it gets a struct, so anything is possible. What's most likely happening here is that it would prints.x, but again it may as well spawn a one-way portal toПетр...
I've been able to retrieve the uptime value from/proc/uptime(which is in seconds). However, I need to retrieve the last boot time stamp using C. (I cannot usesystem(...)function to call uptime.) For example, when I run theuptimecommand, the value I get is: ``` 15:31:35 up 2 days, 4:14, 3 users, load average: 0.04...
Open/proc/uptimeand read it. The first number is the uptime in seconds.
I am trying to create a Makefile that compiles multiple C files for use in Minix. How would I change the Makefile so that it compiles multiple files at the same time? Below is the current state of my Makefile. ``` CFLAGS = -D_POSIX_SOURCE LDFLAGS = CC = cc LD = cc PROG = test OBJS = test.o $(PROG)...
Split it up this way: ``` PROG1 = test PROG2 = test2 OBJ1 = test.o OBJ2 = test2.o $(PROG1): $(OBJ1) $(LD) $(LDFLAGS) $(OBJ1) -o $(PROG1) $(PROG2): $(OBJ2) $(LD) $(LDFLAGS) $(OBJ2) -o $(PROG2) ``` etc
I am trying to declare an array ofstructs, is it possible to initialize all array entries to a defaultstructvalue? For example if mystructis something like ``` typedef struct node { int data; struct node* next; }node; ``` Is there a way to declare data to4and next tonull? Wh...
Sure: ``` node x[4] = { {0, NULL}, {1, NULL}, {2, NULL}, {3, NULL} }; ``` Even this should be fine: ``` node y[4] = { {0, y + 1}, {1, y + 2}, {2, y + 3}, {3, NULL} }; ```
``` list *attachnode(list *tmp,list *hd)//function to get the ip address { if(hd==NULL) { hd=tmp; } else { tmp->next=hd; hd=tmp; } return(hd); } ``` tmp->next=hd giving a warning of incompatible type pointer conversion by default "next" i...
you say, "next" is "list type" but i believe it should be "list *" type but without your typedef we cannot be sure okay, your comment, my edith: it should betypedef struct list {...; struct list *next;} list; the reason is, that C does need a forward declaration, else it could not determine the "type" of next. vis...
``` typedef struct s { int x; int y; } S; typedef struct t { S s; } T t = {0}; T *pointer_to_T = &t; printf("End address %x", pointer_to_T->s); printf("Beginning address %x", &(pointer_to_T->s)); ``` Based on my testing, pointer_to_T->s is the address of the end of the structure S ``` pointer_to_T->s - &(p...
The expected behaviour here can range from printing garbage tonasal demons, because this behaviour is undefined. The%xspecifier makesprintfexpect an integer but it gets a struct, so anything is possible. What's most likely happening here is that it would prints.x, but again it may as well spawn a one-way portal toПетр...
I've been able to retrieve the uptime value from/proc/uptime(which is in seconds). However, I need to retrieve the last boot time stamp using C. (I cannot usesystem(...)function to call uptime.) For example, when I run theuptimecommand, the value I get is: ``` 15:31:35 up 2 days, 4:14, 3 users, load average: 0.04...
Open/proc/uptimeand read it. The first number is the uptime in seconds.