question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
the flow in my program callspthread_join(thread_id, nullptr);2 times for the samethread_idfrom the same calling thread.
First time the call returns successfully but the second time it just hangs indefinitely. The documentation does not say clearly that it's forbidden to call pthread_join multiple times for the same t... |
Have a look at thedocumentation forpthread_join- in the Notes section it is stated that:
Joining with a thread that has previously been joined results in undefined behavior.
Lots of other good information on joining threads (and other aspects, if you search for some of the other pthread functions) in the link too.
|
There is a problem which confuses me a lot.
```
int main(int argc, char *argv[])
{
int i = 12345678;
return 0;
}
```
```
int main(int argc, char *argv[])
{
int i = 0;
return 0;
}
```
The programs have the same bytes in total. Why?
And where the literal value indeed stored? Text segment or other... |
The programs have the same bytes in total.Why?
There are two possibilities:
The compiler is optimizing out the variable. It isn't used anywhere and therefore doesn't make sense.If 1. doesn't apply, the program sizes are equal anyway. Why shouldn't they?0is just as large in size as12345678. Two variables of typeToccu... |
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.Closed7 years ago.Improve this question
I have the basic knowledge of preprocessor.But i have never understood how it works.Can s... |
```
#define A 1234
```
Literally as far as the compiler is concerned, every instance of A is now 1234.
Its useful for code readability and modifieability. If you have a constant number for instance thats used in 7-8 different functions, you can #define it and use atokeninstead, and then change it in 1 place rather t... |
This question already has answers here:What is the proper #include for the function 'sleep()'?(6 answers)Closed7 years ago.
How can I sleep or pause the program excecution by a few seconds in C? I'm looking for something like this that is used in Java:
```
Thread.sleep(interval);
```
Is possible do this using C ?
T... |
```
#include <stdio.h>
#include <unistd.h>
int main (void){
sleep(3);
return 0;
}
```
Read morehere.
|
I am writing a program in c which traverse a tree in in-order, pre-order and post-order . this code is not compiling properly . it shows a error saying "unknown type name 'node'"
```
struct node
{
int value;
node* left;
node* right;
};
struct node* root;
struct node* insert(st... |
change inside structure
```
struct node
{
int value;
struct node* left; //Changed
struct node* right;
};
```
|
I want to find straight lines marked in the image, the coordinates point A, point B is the beginning and end of the segment. Please help me!
img:enter image description heresource:enter image description here
|
It is called the "Hough Transform"
You could experiment using something like Mathlab, and then implement it using opencv houghtransform.
https://github.com/Itseez/opencv/blob/master/samples/cpp/houghlines.cpp
|
I am unable to usemicrocoaplibrary (https://github.com/1248/microcoap) in Arduino IDE. When I try to compile it produces following error
```
main-posix.c:1:24: fatal error: sys/socket.h: No such file or directory
#include <sys/socket.h>
^
```
This question has already been answered in (Cant use... |
Delete that main-posix.c because this is necessary for linux, not Arduino. It will definitely work.
|
I have two files. I want to copy source file to destionation file. If they are different, then I just want to copy different line not all file. In the below case, two line are same, but destination has extra line. How can I just delete last line of destination file?
For example:
```
Source File:
test1
test2
Dest... |
On POSIX systems, if you want to delete some ending bytes in a file, you could useftruncate(2)
There is no portable way to remove bytes in the middle of a file.
|
I created signals. One of them prints "1" 20 times. Another prints "2" 20 times.I want these signals to print their numbers in turn:1,2,1,2...But the program prints only "1".Can someone help me with that?
|
Run this code and see what when you send SIGUSR1 or SIGUSR2 to the pid printed.
```
#include <stdio.h>
#include <signal.h>
void handler1(int signal)
{
printf("Foo\n");
}
void handler2(int signal)
{
printf("Bar\n");
}
int main()
{
printf("PID: %d\n", getpid());
sigset(SIGUSR1,handler1);
sigset(SIG... |
I have a string which is always has two forward slashes as/709/nviTemp1I would like to extract the/709/from that string and return it in char*, how would I use strstr for that purpose?
I also might have many forward slashes in the path like/709/nvitemp1/d/s/
so I only need to get the first token/709/
|
You may try something like this:
```
char str[100] = "/709/nviTemp1";
char resu[100];
char *tmp;
tmp = strchr(str+1, '/');
strncpy(resu, str, (size_t)(tmp - str) + 1);
resu[(size_t)(tmp - str) + 1] = '\0';
```
Thestrchrsearch the 1st '/', but starting atstr+1skips the real first one. Then compute "size" beetween st... |
I need the basic symbol jumping feature while I navigate my source code.
I mean while I open a C source code folder into the VScode-0.9.1, then I want to jump to one function's definition usingF12orCtrl+Shift+O, there is no response forF12, or an error message like “unfortunately we have no symbol information for the ... |
There is currently no deeper language support for C files in Visual Studio Code. This will probably change in the future when the extension API for the editor will be public.
For now you have only syntax highlighting for C files.
|
Why does gets() ask for string here. I mean, why doesn't it consume the newline character from the previous printf() and the program just terminate?
And yes i know i should use fgets() and stuff like that. Please don't mention about it.
code for reference-
```
#include <stdio.h>
main()
{
char str[30];
print... |
From the manual ofchar *gets(char *str):
Reads a line from stdin and stores it into the string pointed to by,
str. It stops when either the newline character is read or when the
end-of-file is reached, whichever comes first.
From the manual for printf :
The functions printf() and vprintf() write output to ... |
```
int n = 0;
int temp = 0;
while ((temp != 1) || (n <= 0)){
puts("enter array count");
temp = scanf("%d", &n);
printf("\n%d\n", temp);
}
```
I need to check input value for the fact it must be an integer and be > 0.
scanfreturns count of success set values and if it's not an integer it will return 0.
So th... |
When you type something invalid, such as a character, forscanf("%d", &n);, thescanffails, returns 0, andleaves the invalid data in thestdin. In the next iterationscanfsees this invalid data prevailing in thestdin, fails again and this process is repeated.
The fix is to clear thestdinin each iteration of the loop. Add... |
I want to set a a break-point in the C implementation for model.matrix. I tried Selva's solution inHow can I view the source code for a function?:
```
> debug(C_modelmatrix)
Error in debug(C_modelmatrix) : object 'C_modelmatrix' not found
> debug(modelmatrix)
Error in debug(modelmatrix) : object 'modelmatrix' not fou... |
There is still-useful video tutorial by Seth Falcon onhow to debug R packages with native codewhich shows this.
In essence, launchRwithR -d gdbto invoke thegdbdebugger which you then instruct to set breakpoints in the right places.
If you (or your operating system) prefers a different compiler, youobviouslyneed to s... |
```
char *name= "tony";
name[2] = 'z';
printf("%s",name);
```
why does this give me a bus error 10? and what does it mean?
This book tells me its because "tony" string literal is saved in read only memory and you can't alter it, but i don't understand because i can do things like this..
```
char *name= "tony";
... |
```
char *name= "tony";
name = "another";
printf("%s",name);
```
In this case you did not change the data in the read only memory. You just madenamepointer to point to another read only memory (where "another" is stored).
```
char *name= "tony";
name[2] = 'z';
printf("%s",name);
```
In this case, you are actually e... |
I'm brand new to working with c. I've got a file with the following format style:
```
number:number,number,number
```
Is there anyway I can usefscanfto obtain the numbers from the file?
My code below is not working:
```
fscanf(file,"%d%[^:]:%d%[^,],%d%[^,],%d",&one,something,&two,something3,&three,something4,&four... |
You don't need the%[^:]parts there, you can put delimiters into the format string directly:
```
int a, b, c, d;
while (scanf("%d:%d,%d,%d",&a,&b,&c,&d) == 4) {
printf("%d %d %d %d\n", a, b, c, d);
}
```
Demo.
|
```
int n = 0;
int temp = 0;
while ((temp != 1) || (n <= 0)){
puts("enter array count");
temp = scanf("%d", &n);
printf("\n%d\n", temp);
}
```
I need to check input value for the fact it must be an integer and be > 0.
scanfreturns count of success set values and if it's not an integer it will return 0.
So th... |
When you type something invalid, such as a character, forscanf("%d", &n);, thescanffails, returns 0, andleaves the invalid data in thestdin. In the next iterationscanfsees this invalid data prevailing in thestdin, fails again and this process is repeated.
The fix is to clear thestdinin each iteration of the loop. Add... |
I want to set a a break-point in the C implementation for model.matrix. I tried Selva's solution inHow can I view the source code for a function?:
```
> debug(C_modelmatrix)
Error in debug(C_modelmatrix) : object 'C_modelmatrix' not found
> debug(modelmatrix)
Error in debug(modelmatrix) : object 'modelmatrix' not fou... |
There is still-useful video tutorial by Seth Falcon onhow to debug R packages with native codewhich shows this.
In essence, launchRwithR -d gdbto invoke thegdbdebugger which you then instruct to set breakpoints in the right places.
If you (or your operating system) prefers a different compiler, youobviouslyneed to s... |
```
char *name= "tony";
name[2] = 'z';
printf("%s",name);
```
why does this give me a bus error 10? and what does it mean?
This book tells me its because "tony" string literal is saved in read only memory and you can't alter it, but i don't understand because i can do things like this..
```
char *name= "tony";
... |
```
char *name= "tony";
name = "another";
printf("%s",name);
```
In this case you did not change the data in the read only memory. You just madenamepointer to point to another read only memory (where "another" is stored).
```
char *name= "tony";
name[2] = 'z';
printf("%s",name);
```
In this case, you are actually e... |
I'm brand new to working with c. I've got a file with the following format style:
```
number:number,number,number
```
Is there anyway I can usefscanfto obtain the numbers from the file?
My code below is not working:
```
fscanf(file,"%d%[^:]:%d%[^,],%d%[^,],%d",&one,something,&two,something3,&three,something4,&four... |
You don't need the%[^:]parts there, you can put delimiters into the format string directly:
```
int a, b, c, d;
while (scanf("%d:%d,%d,%d",&a,&b,&c,&d) == 4) {
printf("%d %d %d %d\n", a, b, c, d);
}
```
Demo.
|
I know that i C , you always have to add a null terminator\0so that the processor knows when a word was ended .
But i get hard time to understand when you have to do it . so for example this code works for me without it :
```
char connectcmd[50]={0};
sprintf(connectcmd,"AT+CWJAP=\"%s\",\"%s\"",MYSSID,MYPASS);
```... |
sprintfalways terminates it withnull character, so no need to mannually add it.
From C99 standard -
7.21.6.6 The sprintf function[...]A null character is written at the end of the characters written; it is not counted as part of the returned value. If copying takes place between objects that overlap, the behavior is... |
I want to know there are how many functions I can call in C library, e.g. Gnu C library? or Approximately?
|
If you are in unix like OS, you can usenmutility, part ofgnu binutils. In my cygwin environment,nmlists 1570 symbols defined in the text section.
```
% nm -C /usr/lib/libc.a | grep -w T | wc -l
1570
```
Let's exclude the_variants
```
% nm -C /usr/lib/libc.a | grep -w T | grep -v _ | wc -l
751
```
If you are on w... |
I looked up the manual of iso_8859-1 and found the degree symbol:
```
Oct Dec Hex Char Description
260 176 B0 ° DEGREE SIGN
```
Code:
```
int main( int argc, char *argv[])
{
char chr = 176; //stores the extended ASCII of a symbol
printf("Character with an ascii code of 251: %c \n", chr);... |
the ASCII code for the degree celsius is 248. You can declare this as a char in C.
```
#include<stdio.h>
void main()
{
char ch=248;
printf("Today's temperature was 23%cC",ch);
}
```
|
This question already has answers here:C : #define usage [duplicate](3 answers)Closed7 years ago.
```
#include <stdio.h>
#define SQR(x) x*x
int main()
{
printf("%d",225/SQR(15));
return 0;
}
```
The output to this code is 225. I'm unable to understand as what really is happening here.
If I use#define SQR(x) ... |
#definemacros aren't functions - they are just macros, text replacement. If you take the expression225/SQR(15)and replaceSQRwith15*15, you'll get225/15*15, and since/and*have the save precedence and are left associative -255/15*15 = 255.
|
So the question in one of my assignments is: ..
A function whose signature is
int int2seq( bool* X, int8_t x );
that should extract and then store each i-th bit of x in the i-th element of array X; it should return the
total number of elements stored.
my Question is What is thebool* XI've never come across it be... |
I think you need to seethisit will help you to understand bool in C.
In your casebool *Xpointer to bool array is what I understand. But it also can point to single variable also.
|
When I am trying to generate a random number 0 throughint:
```
//Populate Currently Allocated Reasource for each customer
for (i = 0; i < NUMBER_OF_CUSTOMERS; i++)
{
printf("%d:[ ",i);
for (j = 0; j < NUMBER_OF_RESOURCES; j++)
{
allocation[i][j] = rand() % maximum[i][j];
printf("%d ",allo... |
Takinga % bgives you the remainder whenais divided byb. As such, it will always give you a result that is less thanb, and it doesn't work whenbis zero, because you can't divide by zero.
If you want a random number between 0 andx, you need to takerand() % (x + 1).
|
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.Closed7 years ago.Improve this question
How to create the left and right aligned printout of the string by placing exactly the required number of c... |
Here is something you can start with:
```
function strReplace(char str[]) {
char s[STR_LEN);
int i;
for(i = 0, j = 0; i < STR_LEN; ++i, ++j) {
if(str[i++] == ' ') s[j++] = '\t';
s[j] = str[i];
}
}
```
what this will do is insert `\t' into string instead of ' ' which in turn will add up to n s... |
I know that i C , you always have to add a null terminator\0so that the processor knows when a word was ended .
But i get hard time to understand when you have to do it . so for example this code works for me without it :
```
char connectcmd[50]={0};
sprintf(connectcmd,"AT+CWJAP=\"%s\",\"%s\"",MYSSID,MYPASS);
```... |
sprintfalways terminates it withnull character, so no need to mannually add it.
From C99 standard -
7.21.6.6 The sprintf function[...]A null character is written at the end of the characters written; it is not counted as part of the returned value. If copying takes place between objects that overlap, the behavior is... |
I want to know there are how many functions I can call in C library, e.g. Gnu C library? or Approximately?
|
If you are in unix like OS, you can usenmutility, part ofgnu binutils. In my cygwin environment,nmlists 1570 symbols defined in the text section.
```
% nm -C /usr/lib/libc.a | grep -w T | wc -l
1570
```
Let's exclude the_variants
```
% nm -C /usr/lib/libc.a | grep -w T | grep -v _ | wc -l
751
```
If you are on w... |
I looked up the manual of iso_8859-1 and found the degree symbol:
```
Oct Dec Hex Char Description
260 176 B0 ° DEGREE SIGN
```
Code:
```
int main( int argc, char *argv[])
{
char chr = 176; //stores the extended ASCII of a symbol
printf("Character with an ascii code of 251: %c \n", chr);... |
the ASCII code for the degree celsius is 248. You can declare this as a char in C.
```
#include<stdio.h>
void main()
{
char ch=248;
printf("Today's temperature was 23%cC",ch);
}
```
|
This question already has answers here:C : #define usage [duplicate](3 answers)Closed7 years ago.
```
#include <stdio.h>
#define SQR(x) x*x
int main()
{
printf("%d",225/SQR(15));
return 0;
}
```
The output to this code is 225. I'm unable to understand as what really is happening here.
If I use#define SQR(x) ... |
#definemacros aren't functions - they are just macros, text replacement. If you take the expression225/SQR(15)and replaceSQRwith15*15, you'll get225/15*15, and since/and*have the save precedence and are left associative -255/15*15 = 255.
|
So the question in one of my assignments is: ..
A function whose signature is
int int2seq( bool* X, int8_t x );
that should extract and then store each i-th bit of x in the i-th element of array X; it should return the
total number of elements stored.
my Question is What is thebool* XI've never come across it be... |
I think you need to seethisit will help you to understand bool in C.
In your casebool *Xpointer to bool array is what I understand. But it also can point to single variable also.
|
Assume there is a structfakes:
```
struct fakes {
....
};
```
And there is a pointer:
```
struct fakes *fakes;
```
I'm wondering whethersizeof(struct fakes)andsizeof(*fakes)are the same.
|
I'm wondering whethersizeof(struct fakes)andsizeof(*fakes)are the same.
Yes, they are guaranteed to be the same.
|
I want to generate five random numbers each time using srand() function within the range 1 to 10. Here is a sample program:
```
#include<stdio.h>
#include<math.h>
#define size 10
int main()
{
int A[5];
for(int i=0;i<5;i++)
{
A[i]=srand()%size
}
}
```
But I am getting an error saying too few a... |
srandsets the seed forrand, the pseudo-random number generator.
Corrected code:
```
#include <stdio.h>
#include <math.h> /* Unused header */
#include <stdlib.h> /* For `rand` and `srand` */
#include <time.h> /* For `time` */
#define size 10
int main()
{
int A[5];
srand(time(NULL)); /* Seed `rand` with the... |
What is the difference between
```
float f = (float) 99.32 ;
```
and
```
float f = 99.32f ;
```
Both of them compiled and ran successfully.
|
```
float f = 99.32f ;
```
That is afloatliteral, which means a float variable being assigned with afloatvalue directly.
```
float f = (float) 99.32 ;
```
That is afloatvariable that is assigned adoublevalue that is cast tofloatbefore being assigned.
|
This question already has answers here:What does void* mean and how to use it?(10 answers)Closed7 years ago.
I'm learning about dynamics data structure e.g.mallocfunction.
Why sometimes programmers usevoid*as a pointer parameter to (for example) dynamic variables of integers and chars? What are the differences?
What ... |
Every pointer type can be cast tovoid*safely. Generic functions that need to work with pointers of all sorts of objects, such asmallocandrealloccan work only if they usevoid*in their interface.
|
Say if I concatenate one string to another, check if it has passed the line length limit, and if it has passed that limit is there a way to un-concatenate it?
|
If you concatenate a string and it passes the length limit, it is usually too late to undo it: assuming that the limit is based on the size of allocated memory, concatenation causesundefined behavior. At this point it's all over: your program may crash or do other unexpected things.
That is why you need to check the ... |
Suppose I have a text file which has three lines:
apple man womanpearbanana
I used
```
char name[100];
fgets(name,100,inputfile)
```
So nownameshould be "apple man woman"`. All three words separates by blank spaces, right?
I want to put these three words in a singlearray.
I think I need to usefgetsbut I'm new to... |
```
#include <stdio.h>
#include <string.h>
int main(void){
char name[] = "apple man woman";
char *array[sizeof(name)/2];
int n = 0;
for(char *word = strtok(name, " \t\n"); word; word = strtok(NULL, " \t\n")){
array[n++] = word;
}
for(int i = 0; i < n; ++i)
puts(array[i]);
... |
What is the difference between
```
float f = (float) 99.32 ;
```
and
```
float f = 99.32f ;
```
Both of them compiled and ran successfully.
|
```
float f = 99.32f ;
```
That is afloatliteral, which means a float variable being assigned with afloatvalue directly.
```
float f = (float) 99.32 ;
```
That is afloatvariable that is assigned adoublevalue that is cast tofloatbefore being assigned.
|
This question already has answers here:What does void* mean and how to use it?(10 answers)Closed7 years ago.
I'm learning about dynamics data structure e.g.mallocfunction.
Why sometimes programmers usevoid*as a pointer parameter to (for example) dynamic variables of integers and chars? What are the differences?
What ... |
Every pointer type can be cast tovoid*safely. Generic functions that need to work with pointers of all sorts of objects, such asmallocandrealloccan work only if they usevoid*in their interface.
|
Say if I concatenate one string to another, check if it has passed the line length limit, and if it has passed that limit is there a way to un-concatenate it?
|
If you concatenate a string and it passes the length limit, it is usually too late to undo it: assuming that the limit is based on the size of allocated memory, concatenation causesundefined behavior. At this point it's all over: your program may crash or do other unexpected things.
That is why you need to check the ... |
Suppose I have a text file which has three lines:
apple man womanpearbanana
I used
```
char name[100];
fgets(name,100,inputfile)
```
So nownameshould be "apple man woman"`. All three words separates by blank spaces, right?
I want to put these three words in a singlearray.
I think I need to usefgetsbut I'm new to... |
```
#include <stdio.h>
#include <string.h>
int main(void){
char name[] = "apple man woman";
char *array[sizeof(name)/2];
int n = 0;
for(char *word = strtok(name, " \t\n"); word; word = strtok(NULL, " \t\n")){
array[n++] = word;
}
for(int i = 0; i < n; ++i)
puts(array[i]);
... |
In one of my assignments I am seeing this line used:
```
int index = -1, k;
```
Im not sure what is happening when there are to entries for the one variable.
What exactly is the variable "index" holding when it has two entries?
|
This is the definition of 2 variables, both of the same typeint:indexandk. Onlyindexis initialized with-1, andkis left un-initialized.
|
Say if I concatenate one string to another, check if it has passed the line length limit, and if it has passed that limit is there a way to un-concatenate it?
|
If you concatenate a string and it passes the length limit, it is usually too late to undo it: assuming that the limit is based on the size of allocated memory, concatenation causesundefined behavior. At this point it's all over: your program may crash or do other unexpected things.
That is why you need to check the ... |
Suppose I have a text file which has three lines:
apple man womanpearbanana
I used
```
char name[100];
fgets(name,100,inputfile)
```
So nownameshould be "apple man woman"`. All three words separates by blank spaces, right?
I want to put these three words in a singlearray.
I think I need to usefgetsbut I'm new to... |
```
#include <stdio.h>
#include <string.h>
int main(void){
char name[] = "apple man woman";
char *array[sizeof(name)/2];
int n = 0;
for(char *word = strtok(name, " \t\n"); word; word = strtok(NULL, " \t\n")){
array[n++] = word;
}
for(int i = 0; i < n; ++i)
puts(array[i]);
... |
In one of my assignments I am seeing this line used:
```
int index = -1, k;
```
Im not sure what is happening when there are to entries for the one variable.
What exactly is the variable "index" holding when it has two entries?
|
This is the definition of 2 variables, both of the same typeint:indexandk. Onlyindexis initialized with-1, andkis left un-initialized.
|
I am encountering this weird message at the moment with my file.
I have a very basic C file that reads from a file and outputs upon request.
I am running the following command in Linux:
```
filename <filenametest.txt >filenameoutput
```
and it brings the following message:
```
filename: command not found
```
Any i... |
Assuming thatfilenameis the name of the executable generated on compiling your C code, maybe you should try using
./filename < filename.txt > filenameoutput.
Sincefilenameis not in the search path by default.
|
I am attempting to create a two dimensional array of strucs, albeit not in the most pretiest of ways, and am running into some syntax errors. My code is as follows:
```
struct Page
{
char Column[4];
int variable;
};
```
.
.
.
```
int main()
{
struct Page Test[2][2];
Test[0][0].Column = "ABC";
Test[0][0].var... |
The assignment operator cannot be used with arrays in C.
You could use initialization instead (which is not assignment despite using the=symbol):
```
struct Page Test[2][2] = {
{ "ABC", 124 }, { "DEF", 368 }, { "GHI", 763 }
};
```
|
I would like to determine during compile time what the specified TARGET_PLATFORM has been specified.
As an example, I would like to do something like the following:
```
#if (TARGET_PLATFORM == 21)
#include <sys/system_properties.h>
#else
#include <sys/_system_properties.h>
#endif
```
I would prefer an ndk built-in ... |
```
#include <android/api-level.h>
#if __ANDROID_API__ == 21
....
#else
....
#endif
```
|
Why this code is showing Segmentation fault (core dumped)?
```
#include<stdio.h>
void swap(int*,int*);
int main(){
int x=5,y=10;
swap(&x,&y);
printf("%d%d",x,y);
return 1;
}
void swap(int *a,int *b){
int *temp;
*temp = *a;
*a = *b;
*b = *temp;
}
```
|
int *temp;is the problem. It is not pointing to any memory that you own. The behaviour on dereferencingtempis undefined.
Useint temp;instead, (preferablyint temp = *a;since thentempis never in an uninitialised state) andtemprather than*tempin the assignments.
(By the way,0is conventionally the return value frommaint... |
How to generate assembly from a cross-compiled binary?
Compile command used is:
```
arm-none-linux-gnueabi-gcc test.c -o test
```
How can I disassemble the binarytest?
I have used:
```
objdump -d test -m arm
```
But it says:
```
test: file format elf32-little
objdump: can't use supplied machine arm
```
An... |
GCC generates the assembly already, you only need to tell it not to throw the files away when finished:
```
arm-none-linux-gnueabi-gcc -save-temps test.c -o test
```
Note that the generated files will only contain the assembly language of your code and not the stuff that is linked in from the C libraray, e.g. forpr... |
I am using google test and google mock to test some C code:
```
struct msghdr message;
int retval;
retval = recvmsg(fd,&message,0);
if(retval == EINTR || retval == EAGAIN)
{
// do something here
}
```
in my mock file, I mocked therecvmsgfunction:
```
MOCK_CONST_METHOD3(recvmsg, int(int fd, struct msghdr *msg,... |
There is a standard action calledSetErrnoAndReturn(errnum, value)which is described inGoogle Mock docs.
|
I have a client server system using MPI (using ports) in C++. Its running good. Is doing what I intend it to do.
I recently read about remote memory access (RMA) in MPI usingMPI_Winmemory windows. I'm wondering if it is possible to create a system similar to client-server using RMA. (Lets say the synchronization betw... |
Creation of RMA windows is a collective operation that involves the process group of an intracommunicator. To make it work with an intercommunicator, you must first merge the two process groups viaMPI_INTERCOMM_MERGEand then use the resultant intracommunicator for RMA operations. Note that doing so removes part of the... |
How do you make a code in C that will output this sequence?
```
10, 1, 9, 2, 8, 3, 7, 4, 6, 5
```
...easy!
```
#include <stdio.h>
int main(){
int f = 10, s = 1;
while (s <= 5)
printf("%d %d ",f--,s++);
getch();
}
```
There are many ways to do it, but as you might have noticed, it uses two variables.
So how d... |
This is your code using a single var:
```
int main()
{
int s = 1;
while (s <= 5)
{
printf("%d %d ", (11-s), s);
s++;
}
printf("\n");
}
```
|
I'm trying to send the child process a blank(SIGUSR1) signal from the parent. As far as I know, I have the signal set up properly. I feel like I am messing up on the Kill() function call. I expect some sort of printed output, but I get nothing. Not from inside the child nor from the signal function itself.
code:
```... |
The child process exits before the parent process has a chance to send a signal to it. Try addingsleep(5)in the child process after callingsignal.
|
I'm trying to make a single makefile file that compiles two different set of files. Is this posible?
What I tried so far is:
```
target1: OBJ = foo1.o foo2.o
target1: application
target2: OBJ = foo3.o foo4.o
target2: application
application: $(OBJ)
$(LD) $(OBJ)
```
What happens is thatLDis called with the c... |
You could go with this for instance (considering you won't call make with multiple target at once):
```
OBJ := foo1.o foo2.o
ifeq "$(MAKECMDGOALS)" "target2"
OBJ := foo3.o foo4.o
endif
target1 target2: application
application: $(OBJ)
$(LD) $^
```
|
I want to compile this code:
```
#include <stdalign.h>
#include <stdio.h>
#include <stddef.h>
int main ( int argc , char ** argv )
{
printf ("%zu\n", alignof ( max_align_t ));
return 0;
}
```
But compiler says that:
```
error: ‘max_align_t’ undeclared".
```
stddef.his included and everything must be ok, is... |
To use a C11 feature you need to tell the compiler to run in C11 compliant mode.
For gcc this can be achieved by specifying the option-std=c11.
|
Is there any difference in below two castings ?
```
int a=10;
int *p=&a;
(void)p; //does not give any warning or error
```
or
```
(void *)p; //error: statement with no effect [-Werror=unused-value]
```
when complied withgcc -Wall -Werror --std=c99 -pedantic
Just saw that in this answer.(clearly I... |
When you do
```
(void) p;
```
You tell the compiler to simply disregard the result of the expressionp. It's effectively the same as an empty statement:
```
;
```
When you do
```
(void *) p;
```
You tell the compiler to treat the variablepas a generic pointer, and that's the full expression for the statement, a... |
I'm working with an external project that uses.cfile extension for C++ files (they will not change this, I have even sent them a full patch).
Is there any way to force Eclipse (autotools project) to index all.c/.hfiles as C++?
|
Enter in
Preferences->C/C++->FileTypes
You can see the file association there. It doesn't let me change it in my Eclipse Luna CDT, but what you can do is to override it per project.
Properties->C/C++ General->FileTypes->Use project settings
|
I wrote a simple C socket program that sends an INIT package to the server to indicate to prepare a text transfer. The server does not sends any data back at that time.
After sending the INIT package the client sends a GET package and waits for chunks of data from the server.
So every time the server receives a GET pa... |
It depends. For TCP socketsreadmay return before the buffer is full, and you may need to receive in a loop to get a whole message. For UDP sockets the size you read is typically the size of a single packet (datagram) and thenreadmay block until it has read all the requested data.
|
i don't know where is the problem i'm assigning the address to other 2 dimensional array. Please help me to fix this problem
```
int main()
{
int a[3][2];
int b[2]={0,1};
a[2]=b;
return 0;
}
```
prog.cpp:8:9: error: invalid array assignment
|
You can't copy an array using=. Neither can you assign an array's address;x = y;doesn't work either whenxandyhave typeschar[1]for example. To copy the contents ofbtoa[2], usememcpy:
```
memcpy(a[2], b, sizeof(a[2]));
```
|
The following code fails becauseatoi()requires achar *and I'm only passing achar. I want to store the value of only the first digit. Any idea how I can do this?
```
int main () {
char a[]= "123";
int b = atoi(a[0]);
printf("%d",b);
}
```
Here's the exact error message:
```
division.c:9:16: warning: incompatib... |
Yeah, a single character is not a string asatoi()requires.
If you just want the value of the single digit, you can do it like this:
```
int b = (a[0] - '0');
```
|
The following code fails becauseatoi()requires achar *and I'm only passing achar. I want to store the value of only the first digit. Any idea how I can do this?
```
int main () {
char a[]= "123";
int b = atoi(a[0]);
printf("%d",b);
}
```
Here's the exact error message:
```
division.c:9:16: warning: incompatib... |
Yeah, a single character is not a string asatoi()requires.
If you just want the value of the single digit, you can do it like this:
```
int b = (a[0] - '0');
```
|
I was working with IAR Embedded Workbench, using C language.
I had some trouble while dividing my project into the usual main/.h/.c form.
For example, if i create an example.h
```
#ifndef EXAMPLE_H
#define EXAMPLE_H
void function(int [], int);
#endif
```
And than an example.c
```
#include "example.h"
void functio... |
The problem is invoid function(int [], int). Change tovoid function(int name[], int)orvoid function(int *, int). Another error is inint[] array- it has to beint array[]orint * array.
|
The docs don't really say whatstatusis.
What exactly isstatus?
http://man7.org/linux/man-pages/man2/exit_group.2.html
|
From theexit(3) man page:
The C standard specifies two constants,EXIT_SUCCESSandEXIT_FAILURE, that may be passed to exit() to indicate successful or
unsuccessful termination, respectively.
which is mentioned on the group_exit page you referred to. I think it is a typo that it is equivalent toexit(2)because there i... |
This question already has answers here:Most efficient way to create a zero filled JavaScript array?(45 answers)Closed7 years ago.
If I make this line in C\C++:
```
int myArray[10] = { 0 }; // all elements 0
```
I will have an array of ten zeros.
How can I make in the same mode an array in Javascript, withoutfor lo... |
Create an array of11undefinedelementsjointhem by using0as stringsplitthe array by empty stringUsemapto convert the strings to number
var myArray = new Array(11).join('0').split('').map(Number);
console.log(myArray);
document.write('<pre>' + JSON.stringify(myArray, 0, 2) + '</pre>');
|
This question already has answers here:Most efficient way to create a zero filled JavaScript array?(45 answers)Closed7 years ago.
If I make this line in C\C++:
```
int myArray[10] = { 0 }; // all elements 0
```
I will have an array of ten zeros.
How can I make in the same mode an array in Javascript, withoutfor lo... |
Create an array of11undefinedelementsjointhem by using0as stringsplitthe array by empty stringUsemapto convert the strings to number
var myArray = new Array(11).join('0').split('').map(Number);
console.log(myArray);
document.write('<pre>' + JSON.stringify(myArray, 0, 2) + '</pre>');
|
I am working on a project for university. One of the small things that make me lose points is that my answer is correct but it doesn't have four figure number.
For example say I print my answer which is17and on other test files it could change to 6. Is there a way I can ensure that it would always print either
0017 ... |
Try to use
```
printf( "%04d", myValue);
```
04will make sure that yourmyValuewill always have, at least, 4 digits.
|
I am new in Makefile. I have wrote hello.c and when I do "make hello" then it gives executable named as "hello". Internally it showing "cc hello.c -o hello". But without Makefile how make works? How make is gives executable as same name as source?
|
make has a database of built in rules. These rules include recipes for a number of common operations.
The GNU Make Manual covers (some at least) of these recipes in theCatalogue of Built-Inf Rulessection.
Additionally, the output from the-p/--print-data-baseoption will show you all of the rules/recipes and variables... |
I'm writing an SMT program, and I'm trying to workaround an interesting problem.
I need all my functions to exit together, however some of the threads get stuck at barriers, even when i don't want them to.
My question is: what happens when i delete a barrier? Do threads stuck at the barrier release? Is there a way t... |
It's not legal to callpthread_barrier_destroy()if there's any threads blocked on the barrier.
When your thread decides to exit early in a situation where other threads could be waiting on it at a barrier, it should callpthread_barrier_wait()before exiting.
|
So I am new to CDT (even though I have worked with C and Eclipse Java before), and seem to be getting the error as shown in the picture below:
Now, when I check theRun Configurations, the application field of the debug applicaiton seems to be empty, as shown below:
Finally, when I check the actual physical locat... |
It seems that your program doesn't compile correctly, maybe because you have a build error at the compiler level...
Try to pressCTRL+Band see if in the problems section you get some errors of the compiler .
|
I have a simple question which is not easily found. Lets say I want to make a functional prototype for a function containing pointers, for example:
```
int insert(char *word, char *Table[], int n)
```
Is there any special rules for function prototypes regarding pointers? Or will the functional prototype for this be:... |
If you want to write the prototype without parameter names, it will be
```
int insert(char *, char **, int);
```
The type of the first argument ischar *. The type of the second argument ischar **(recall that as a parameter,char *Table[]really meanschar **Table). The type of the third argument isint. The return type ... |
Check the min ex:
```
#include <stdio.h>
#include <string.h>
int main(void) {
char newline = '\n';
char* p = &newline;
if(strcmp(p, "\n") == 0) {
printf("ok\n");
} else {
printf("wrong\n");
}
return 0;
}
```
Is it undefined behaviour? Or is it simply wrong (i.e. it will alway... |
It's UB for the simple reason thatpis not a null-terminated string, andstrcmpis UB if input a non null-terminated string.
|
Code:
```
#include <stdio.h>
int main()
{
long cn=1;
char ch;
while((ch=getchar())!=EOF)
{
printf("%ld\t%c\n",cn++,ch);
}
}
```
When I input word "secret" and hit enter it shows count up to 7 and not 6,why?
|
Because the "enter" character is read as well. This is in fact a "newline", ASCII code 10 (or hex 0A).
|
I am working on a project for university. One of the small things that make me lose points is that my answer is correct but it doesn't have four figure number.
For example say I print my answer which is17and on other test files it could change to 6. Is there a way I can ensure that it would always print either
0017 ... |
Try to use
```
printf( "%04d", myValue);
```
04will make sure that yourmyValuewill always have, at least, 4 digits.
|
I am new in Makefile. I have wrote hello.c and when I do "make hello" then it gives executable named as "hello". Internally it showing "cc hello.c -o hello". But without Makefile how make works? How make is gives executable as same name as source?
|
make has a database of built in rules. These rules include recipes for a number of common operations.
The GNU Make Manual covers (some at least) of these recipes in theCatalogue of Built-Inf Rulessection.
Additionally, the output from the-p/--print-data-baseoption will show you all of the rules/recipes and variables... |
I'm writing an SMT program, and I'm trying to workaround an interesting problem.
I need all my functions to exit together, however some of the threads get stuck at barriers, even when i don't want them to.
My question is: what happens when i delete a barrier? Do threads stuck at the barrier release? Is there a way t... |
It's not legal to callpthread_barrier_destroy()if there's any threads blocked on the barrier.
When your thread decides to exit early in a situation where other threads could be waiting on it at a barrier, it should callpthread_barrier_wait()before exiting.
|
I'm trying to check some homework answers about overflow for 2's complement addition, subtraction, etc. and I'm wondering if I can specify the size of a data type. For instance if I want to see what happens when I try to assign -128 or -256 to a 7-bit unsigned int.
|
On further reading I see you wanted bit sizes that are not normal ones, such as 7 bit and 9 bit etc.
You can achieve this using bitfields
```
struct bits9
{
int x : 9;
};
```
Now you can use this typebits9which has one field in itxthat is only 9 bits in size.
```
struct bits9 myValue;
myValue.x = 123;
```
|
I am trying to get a hexadecimal memory address from a text file and shift the 3 most bits and then print the result.
The memory address is A3BC88A0 and I just want to print A3BC8? However, when I run the code, addr = A3BC88AO but result = 14779114. Can someone help me figure out why this is happening or what to do?
... |
What you want is not to shift by 3 bits, but by 3 hex digits, each of which is 4 bits. So do this instead:
```
unsigned result = addr >> 12;
```
|
I have a function I need to implement, which gets thei_node(struct inode *)andd_entry(struct dentry *) as input arguments. How can I create thevfsmountfrom these two inputs?
|
Generally, you cannot.vfsmountobject is accessible forfileobject, not fordentryone (inodecan be viewed as strictly connected todentry, so it doesn't add something new todentry).
dentryobject has novfsmountobject, universally corresponded to it: it depends frommnt_namespaceobject. You can get namespace for e.g. curren... |
I have two programs in the same directory main and example, if I execute./example file.txtit manages simple tasks with that file. Then my main program is
```
#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
int main (int argc, char* argv[]){
pid_t const pid1 = fork();
if(pid1==0... |
The easiest way to do this would be:
```
execl("./example", "example", argv[1], (char *)NULL);
```
Alternatively,
```
char *args[] = {
"example",
argv[1],
NULL
};
execv("./example", args);
```
|
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed7 years ago.
I am unable to findout the problem with the code below. I get warning message "operation on 'ptr' may be undefined" on printf statement. Also the the result is printed in reve... |
The C standard does not define in what order the parameters get evaluated. Try using *(ptr+1) instead of *ptr++, which also can be replaced with ptr[1].
|
Here is the Part of the program that i am trying to compile using gcc compiler on ubuntu 14.04.
```
#include<stdio.h>
#include<string.h>
main() {
int i;
char str[50], pat[3];
char sep;
printf("Enter the sting to seperate\n ");
scanf("%s", str);
fpurge(stdin);
printf("Enter the patern in N... |
fpurgeis not in the standard C library. It is nonstandard and not
portable. It is a BSD function.
http://bytes.com/topic/c/answers/845246-fpurge
|
I am developing a code in c, which simply FTPs the files on FTP server by using curl utility, by following thisexample
now i have one simple thing to do, specify curl to use particular interface (IP) of the server for upload, as other interface of the server is associated with other socket connection.
is there any w... |
Seems like curl support--interfaceoption
```
curl --interface eth0
```
|
I have a function I need to implement, which gets thei_node(struct inode *)andd_entry(struct dentry *) as input arguments. How can I create thevfsmountfrom these two inputs?
|
Generally, you cannot.vfsmountobject is accessible forfileobject, not fordentryone (inodecan be viewed as strictly connected todentry, so it doesn't add something new todentry).
dentryobject has novfsmountobject, universally corresponded to it: it depends frommnt_namespaceobject. You can get namespace for e.g. curren... |
I have two programs in the same directory main and example, if I execute./example file.txtit manages simple tasks with that file. Then my main program is
```
#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
int main (int argc, char* argv[]){
pid_t const pid1 = fork();
if(pid1==0... |
The easiest way to do this would be:
```
execl("./example", "example", argv[1], (char *)NULL);
```
Alternatively,
```
char *args[] = {
"example",
argv[1],
NULL
};
execv("./example", args);
```
|
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed7 years ago.
I am unable to findout the problem with the code below. I get warning message "operation on 'ptr' may be undefined" on printf statement. Also the the result is printed in reve... |
The C standard does not define in what order the parameters get evaluated. Try using *(ptr+1) instead of *ptr++, which also can be replaced with ptr[1].
|
Here is the Part of the program that i am trying to compile using gcc compiler on ubuntu 14.04.
```
#include<stdio.h>
#include<string.h>
main() {
int i;
char str[50], pat[3];
char sep;
printf("Enter the sting to seperate\n ");
scanf("%s", str);
fpurge(stdin);
printf("Enter the patern in N... |
fpurgeis not in the standard C library. It is nonstandard and not
portable. It is a BSD function.
http://bytes.com/topic/c/answers/845246-fpurge
|
I am developing a code in c, which simply FTPs the files on FTP server by using curl utility, by following thisexample
now i have one simple thing to do, specify curl to use particular interface (IP) of the server for upload, as other interface of the server is associated with other socket connection.
is there any w... |
Seems like curl support--interfaceoption
```
curl --interface eth0
```
|
When I typectags -R .it produces a file called tags, and vim uses that file to navigate tags. How do I make the file name to be .tags and make vim use it?
|
How to specify the name of thetagsfile is explained very early in$ man ctags:
```
$ ctags -Rf .tags .
```
How to tell Vim where to look fortagsfiles is explained in:help 'tags'(and linked sections). A goodgenericdefault value is:
```
set tags=./tags;,tags;
```
Since you want.tagsinstead oftagsyou should add that c... |
I have really been confused about this 2D char array
```
char **arg = malloc(sizeof(char*) * argc)
for (int i = 0; i < argc; i++)
arg[i] = malloc(sizeof(char) * size)
...
...
```
Now suppose after a series of operations, I forget the variable argc, how can I free those memory?
Can I do something like this? Is this... |
No
```
while(*tmp != NULL){
```
you may reach above a point where you will dereference memory which hasn't been assigned to and trigger undefined behaviour.
Or as suggested you can explicitly assign aNULLto the last allocated pointer, and in that case it will work.
|
Is the address of a global variable guaranteed to say the same during the whole process execution? That is, I have
```
static int dummy;
```
and I use
```
something(&dummy);
```
in a few different places across my code. Will&dummyever change, or can I safely use it as a key that is unlikely to be reused by another... |
Yes. From the C99 spec:
[6.2.4]The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists,has a constant address, and retains its last-stored value throughout its lifetime.
|
I have recently downloaded the MinGw compiler and for some reason it does not display and warning messages when I should be doing a explicit casts.
For example:
```
double x=9.97;
int y=x;
```
This seems to be ok with the compiler. I was just wondering do I need to install some other package
|
There is no cast required when assigning adoubleto anint. The decimal part is simply truncated. If you want warnings on this you can use-Wconversionor-Wfloat-conversion.
|
```
int main()
{
char *a1[10] = {"123","121"};
int i =0;
char *a=NULL;
for(i=0;i<2;i++)
{
a=strcat(a1[i],"0000");
printf("values %s",a);
}
}
```
Output of this code comes out to be this:
```
$ ./a.exe values 1230000 values 0000000
```
but it should be:
```
$ ./a.exe values ... |
You want an array of array of char, but char *a1[10] is an array of pointers to char (tipically placed in read-only segments / string literals), trying to modify a string literal usually leads to a segmentation fault.
Change
```
char *a1[10] = {"123","121"}; /* Array of string literals (read only) */
```
to
```... |
```
int array[2] = {1, 1};
int (*pointer_array)[2] = {NULL, NULL};
```
The first line can be correctly compiled but not the second one? Why?
GCC compiler will pop up a warning,excess elements in scalar initializer.
How to initialize a pointer array in C?
EDITED
I declared a pointer array in a wrong way.
It shoul... |
It should be
```
int (*pointer_array)[2]=(int[]){1,2};
```
This is pointer to array ofint.I don't know you want pointer to array ofintor array of pointers.
To declare as array of pointer you need to do this -
```
int *pointer_array[2];
```
|
This question already has answers here:Generating a random bit - lack of randomness in C rand()(4 answers)Closed4 years ago.
I want to generate a random boolean for use in a game, so it does not need to be cryptographically secure. I will usestdbool.hin my code, and I have also done#include <stdlib.h>. Preferably, it... |
Just callrand()and get the LSB of its return value.
```
bool randbool = rand() & 1;
```
Remember to callsrand()at the beginning.
|
I am trying to create a new pointer every iteration. Each pointing to its own memory location, holding the value of i at the time it is assigned. My approach is below but when I print the address of id, it is the same for each iteration.
code
```
for(i=1;i<=n;i++){
int id = i;
printf("i[%p], ",&i);
print... |
iandidare both local variables with automatic storage (commonly referred to ason the stack). Nonewinstances arecreatedupon each iteration of the loop, the same space is reused and a new value is stored inid, hence the same addresses printed byprintf.
Note that the value ofidis not guaranteed to be preserved across it... |
I'm trying to calculate the distance between 2 coordinates in 3D, however, when complied, and entered (1,1,1), (1,1,1), output returns 2 instead of 0.
Code here
```
#include <stdio.h>
#include <math.h>
int get_dist(int x_i,int y_i,int z_i,int x_o,int y_o,int z_o){
int coord_dist = 0;
coord_dist = sqrt(((x_o - x_i... |
^ is XOR, not exponent. You want the pow() function.
|
I write a C program mentioned below:
```
#include <stdio.h>
int sum(int&, int*);
int main(int argc, const char * argv[]) {
int array[] = {1,2,3};
int temp = 0;
int _result = sum(temp, 3);
return 0;
}
int sum(int &sum, int *array)
{
}
```
But, my program have a error for declaration... |
References are not available incSecond parameter calling sum does not make sense.
I guess you want something like
```
#include <stdio.h>
int sum(int*, int*, int);
int main(int argc, const char * argv[]) {
int array[] = {1,2,3};
int temp = 0;
int result = sum(&temp, array, 3);
return ... |
This question already has answers here:C sizeof a passed array [duplicate](7 answers)How to find the size of an array (from a pointer pointing to the first element array)?(17 answers)Closed7 years ago.
I wrote the following function in C:
```
void dummy(int* my_array, int size)
{
//my implementation
}
```... |
You're looking at it the wrong way. An array is contiguous piece of memory. In C, you can represent this concept with a pointer to its start and its size. Since your array is represented by a<my_array, size>tuple, it doesn't make sense to talk aboutmy_array's size, since it's only the start-pointer of the array.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.