question
stringlengths
25
894
answer
stringlengths
4
863
This is my main: ``` int main(){ int array[] = {1,2,3,4,5,6}; int i = 0; reverse(array,6); for(i=0; i < 6; i++) printf("%d\n",array[i]); } ``` and this is my reverse function: ``` void reverse(int * array,int n){ int i; for(i=0; i < n; i++){ int tmp = array[i]; array...
You just need to stop your loop at n/2 otherwise you'll reverse your array (end to n/2) and then you reverse it again (from n/2 to n) ``` void reverse(int * array,int n){ int i; for(i=0; i < n/2; i++){ int tmp = array[i]; array[i] = array[n-1-i]; array[n-1-i] = tmp; } } ``` Moreo...
I'm writing a simple program, and had to write the following struct ( into my "node.h" file ): ``` #ifndef NODE_H #define NODE_H struct _noh { int peso; int altura; struct _noh* filho[2]; } base = { 0, 0 ,{ &base, &base } }, *nnil = &base; typedef struct _noh noh; noh* novonoh(int valor); #endif ``` ...
I solved the question, just removing the base and nnil variables from header.
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed7 years ago.Improve this question I want to read from ...
While calling function use absolute file path(Ex: "C:/MyFolder/MyFile.txt")
I have a fifo opened as RDWR(for communicate process-process) and pipes(process-thread), how can I understand when I reach pipes or fifos limit? When I try to write more than 64 KB it just wait in write().
You need to use non-blocking mode: ``` pipe2(fds, O_NONBLOCK); ``` Or if you need to do it after the pipe was created: ``` int flags = fcntl(fd, F_GETFL, 0); fcntl(fd, F_SETFL, flags | O_NONBLOCK); ``` Now when you read or write and the operation cannot complete immediately, it will return. You can then useselect...
In AVX, is there any special macro that helps to construct the immediate constant for_mm256_shuffle_*intrinsics, like_MM_SHUFFLE(..)for its SSE counterpart? I can't find any.
You still use_MM_SHUFFLE()for shuffles that take the control input as an 8bit immediate. e.g._mm256_shuffle_epi32(vpshufd) does the same shuffle on both lanes. _MM_SHUFFLE(dd,cc,bb,aa)just packs the low 2 bits of each arg into a0bddccbbaa. You can write_MM_SHUFFLE(1,1,1,1)(broadcast element 1) as0b01010101, i.e.0x5...
In this code I am trying to pass a pointer to the structure and then use this pointer to work on the structure members, but why is the output always showing 0? ``` #include<stdio.h> #include<string.h> struct student { int go; } s; void m(); void main() { m(&s); printf("%d",s.go); } void m(struct stude...
``` struct student { int go; }s; ``` creates a global variable. Global variables are zero initialized unless they are initialized explicitly. That statement is equivalent to: ``` struct student { int go; }; struct student s = {0}; ``` Hence the value ofs.gois0. The call tomdoes not change the values of any v...
Here's the code: ``` char* a[] = {"ls", "-l", "|", "grep", "test"}; int pipe_idx = 2; char** ptr2 = a + (pipe_idx * sizeof(char**)); printf("%s\n", *ptr2); ``` Basically, this is just a demo code. The program gets the pipe_index (in this case it's2) and jumps to the right place, and then print it. Why do I g...
ptr2is pointing to memory that doesnt belong to you. Right now, it is pointing toa + 8, becausesizeof(char**)is sizeof pointer, not thecharitself. So the size exceeds your array size. It's UB, and thats why you are getting segfault. If you are trying to traverse the array using char pointer, you do not need to the mu...
I'm tring to stop a loop when i enter a word with 4 letters, but it doesn't stop. What's wrong with it? Here my code : ``` int main() { char word[10][20]; int i=0; while(strlen(word[i])!=4) { scanf("%s",&word[i]); puts(word[i]); i++; } } ```
Replacewhile(strlen(word[i]) != 4withwhile ((i-1 >= -1) && (strlen(word[i-1]) != 4)). Your version is checking thecurrent wordwhich is not entered yet. You read a word, increaseiand compute length of theith word, but it's not here yet, but you wanna check the length ofthe last word entered, so useword[i-1]andadd a ch...
As far as i know, the only possible way to find largest number and lowest number if they array is not sorted by using linear search. is there any other option for this one? just want to know tho
Since the value of a particular element in an unsorted collection tells you nothing about the value of adjacent elements, you need to inspect every value. And doing that is O(N).
I'm testing SSH connection under Linux. With using tcpdump I noticed that TCP FIN flag is set in common SSH packet data. For testing purposes I'd like to achieve the situation where packet with TCP FIN flag is sent as a separate packet, so it would be a packet with no data, but with FIN flag set. I've been looking f...
Tuning a TCP connection this way can not be done and it would not make really sense to control it. If you need to produce traffic with this behavior you cannot use normal TCP sockets but need to useraw socketswhere you can set the header like you want. You would of course need to re-implement all the parts of the TCP ...
I just discovered fixed-size types which can be found in stdint.h / cstdint. Some of them are "normal" types, like int32_t and some are designed to be unsigned, like uint64_t. Do i need to use the "unsigned" keyword when using types which are unsigned by design ?
You do not need to useunsignedand in fact, youcan notuse it. Only the fundamental types may be modified with thesignedandunsigned(alsolongandshort) keywords. Aliases of the standard types can not be modified using those keywords and that includes the fixed width aliases. If you writeunsigned int32_t, then the compi...
I am writing a program which requires me to create a file using standardfopen fprintf fclosecalls. I want to set the execute bits. I can do this withchmodbut this seems overkill. For the life of me (possibly due to advanced age) I can't seem to find (or remember) an API to do this.
fchmod(2)would be in keeping with your other calls... Given a file descriptor infd: ``` struct stat buf; fstat(fd, &buf); fchmod(fd, buf.st_mode | S_IXUSR | S_IXGRP | S_IXOTH); ``` will add all three execute bits to the file's current mode (error handling left as an exercise for the reader). You'd usefileno(3)to ge...
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 Let's say that at some point in my program I am usingexecvand the function ran successfully. Now my program...
execve() does not return on success, and the text, data, bss, and stack of the calling process are overwritten by that of the program loaded. That is to say, all data of current process will be gone, and the new program is loaded into memory, replacing the original process.
As far as i know, the only possible way to find largest number and lowest number if they array is not sorted by using linear search. is there any other option for this one? just want to know tho
Since the value of a particular element in an unsorted collection tells you nothing about the value of adjacent elements, you need to inspect every value. And doing that is O(N).
I'm testing SSH connection under Linux. With using tcpdump I noticed that TCP FIN flag is set in common SSH packet data. For testing purposes I'd like to achieve the situation where packet with TCP FIN flag is sent as a separate packet, so it would be a packet with no data, but with FIN flag set. I've been looking f...
Tuning a TCP connection this way can not be done and it would not make really sense to control it. If you need to produce traffic with this behavior you cannot use normal TCP sockets but need to useraw socketswhere you can set the header like you want. You would of course need to re-implement all the parts of the TCP ...
I just discovered fixed-size types which can be found in stdint.h / cstdint. Some of them are "normal" types, like int32_t and some are designed to be unsigned, like uint64_t. Do i need to use the "unsigned" keyword when using types which are unsigned by design ?
You do not need to useunsignedand in fact, youcan notuse it. Only the fundamental types may be modified with thesignedandunsigned(alsolongandshort) keywords. Aliases of the standard types can not be modified using those keywords and that includes the fixed width aliases. If you writeunsigned int32_t, then the compi...
I am writing a program which requires me to create a file using standardfopen fprintf fclosecalls. I want to set the execute bits. I can do this withchmodbut this seems overkill. For the life of me (possibly due to advanced age) I can't seem to find (or remember) an API to do this.
fchmod(2)would be in keeping with your other calls... Given a file descriptor infd: ``` struct stat buf; fstat(fd, &buf); fchmod(fd, buf.st_mode | S_IXUSR | S_IXGRP | S_IXOTH); ``` will add all three execute bits to the file's current mode (error handling left as an exercise for the reader). You'd usefileno(3)to ge...
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 Let's say that at some point in my program I am usingexecvand the function ran successfully. Now my program...
execve() does not return on success, and the text, data, bss, and stack of the calling process are overwritten by that of the program loaded. That is to say, all data of current process will be gone, and the new program is loaded into memory, replacing the original process.
here is the code. ``` #include <stdio.h> #include <conio.h> int main() { int num,sum=0; printf("enter any number to find its sum of digits"); scanf("%d",&num); while (num!=0) { sum+=num%10; num=num/10; } printf("%d",sum); return 0; } ``` Input other than integer number al...
Because you are failing to check the return value ofscanf(). Any value could come out. You must always check your return values in C.
I need to use tcl.h in my C project (VS 2012) for registering function in SQLite. I have downloaded Tcl for windows and installed it. But my project still doesn't recognize when I write #include . What should I do to get access to this header? Thanks in advance.
Open the project properties and do :
I'm learning C currently,. Using Stat(2) system call How would I compare 2 files st_ino(Inodes) & st_dev(device) and if the same, not to copy the file from source to destination. I can't find any good examples online I am looking at this codehttp://www.people.fas.harvard.edu/~lib215/lectures/lect02/5_Code/llcopy.c
You already have the idea how to do it, just try to translate your thoughts into code: ``` struct stat src, dst; int err; err = stat(src_file, &src); if (err < 0) { perror("stat"); exit(1); } err = stat(dst_file, &dst); if (err < 0) { perror("stat"); exit(1); } if ((src.st_dev == dst.st_dev) && (src.s...
Upon invoking a function,or returning a value from a function,that expects a value of typeT,does using a constant literal without explicit cast invoke undefined behavior? For example,we have a function who's prototype islong foo(unsigned long x);Invocation:foo(4); //does this invoke UB? long foo(unsigned long x) { x...
No, it is all well-defined. There exists an implicit conversion rule between the two types, so theintis simply converted to anunsigned longand the program works as expected.
In C program, I want to display the current version of compiler which was used in the program. Like, ``` char *version; version = malloc(sizeof(char) * 50); strcpy(version, ??? ); printf("Current compiler version is ...%s", version); ``` In this case, what should I put in "???" blank? I guess there is MACRO somewh...
Print_MSC_VERto get just the MSC version. Print_MSC_FULL_VERto get the full MSC version. Try this! ``` printf("Current compiler version is ...%d\n", _MSC_VER); printf("Current compiler full version is ...%d\n", _MSC_FULL_VER); ``` It is an integer MACRO. So, hold it in an int.
I am some kind of newbie in programming and i was just asking myself, if i can switch between folders with the system() command and work there, just like i can do when i type in the commands in the terminal by myself. It's not that kind of very important problem, but it would be nice to know.
You can do the following possibly:system ("cd /path/to/dir; pwd");. Which is, separate the commands via a semicolon. Although once the function returns the directory change will not be applicable anymore. This is because thesystemcommand spawns a new process to execute whatever you have put in the arguments. Once the ...
I'm discovering GDB and i would like to know if it's possible to get the memory address of the declaration of a function, for instance: ``` int func() { return 1; } int main() { func(); return 0; } ``` How do I know at which address is declared the functionfunc()?
You can also useinfo line <line number>to get the address at line number as below: ``` (gdb) list 1 #include <stdio.h> 2 3 int func() 4 { 5 return 1; 6 } 7 8 int main() 9 { 10 func(); (gdb) info line 3 Line 3 of "test.c" is at address 0x4004ed <func> but contains no code. (gdb) p &func $1...
here is the code. ``` #include <stdio.h> #include <conio.h> int main() { int num,sum=0; printf("enter any number to find its sum of digits"); scanf("%d",&num); while (num!=0) { sum+=num%10; num=num/10; } printf("%d",sum); return 0; } ``` Input other than integer number al...
Because you are failing to check the return value ofscanf(). Any value could come out. You must always check your return values in C.
I need to use tcl.h in my C project (VS 2012) for registering function in SQLite. I have downloaded Tcl for windows and installed it. But my project still doesn't recognize when I write #include . What should I do to get access to this header? Thanks in advance.
Open the project properties and do :
I'm learning C currently,. Using Stat(2) system call How would I compare 2 files st_ino(Inodes) & st_dev(device) and if the same, not to copy the file from source to destination. I can't find any good examples online I am looking at this codehttp://www.people.fas.harvard.edu/~lib215/lectures/lect02/5_Code/llcopy.c
You already have the idea how to do it, just try to translate your thoughts into code: ``` struct stat src, dst; int err; err = stat(src_file, &src); if (err < 0) { perror("stat"); exit(1); } err = stat(dst_file, &dst); if (err < 0) { perror("stat"); exit(1); } if ((src.st_dev == dst.st_dev) && (src.s...
Upon invoking a function,or returning a value from a function,that expects a value of typeT,does using a constant literal without explicit cast invoke undefined behavior? For example,we have a function who's prototype islong foo(unsigned long x);Invocation:foo(4); //does this invoke UB? long foo(unsigned long x) { x...
No, it is all well-defined. There exists an implicit conversion rule between the two types, so theintis simply converted to anunsigned longand the program works as expected.
In C program, I want to display the current version of compiler which was used in the program. Like, ``` char *version; version = malloc(sizeof(char) * 50); strcpy(version, ??? ); printf("Current compiler version is ...%s", version); ``` In this case, what should I put in "???" blank? I guess there is MACRO somewh...
Print_MSC_VERto get just the MSC version. Print_MSC_FULL_VERto get the full MSC version. Try this! ``` printf("Current compiler version is ...%d\n", _MSC_VER); printf("Current compiler full version is ...%d\n", _MSC_FULL_VER); ``` It is an integer MACRO. So, hold it in an int.
I am some kind of newbie in programming and i was just asking myself, if i can switch between folders with the system() command and work there, just like i can do when i type in the commands in the terminal by myself. It's not that kind of very important problem, but it would be nice to know.
You can do the following possibly:system ("cd /path/to/dir; pwd");. Which is, separate the commands via a semicolon. Although once the function returns the directory change will not be applicable anymore. This is because thesystemcommand spawns a new process to execute whatever you have put in the arguments. Once the ...
I'm discovering GDB and i would like to know if it's possible to get the memory address of the declaration of a function, for instance: ``` int func() { return 1; } int main() { func(); return 0; } ``` How do I know at which address is declared the functionfunc()?
You can also useinfo line <line number>to get the address at line number as below: ``` (gdb) list 1 #include <stdio.h> 2 3 int func() 4 { 5 return 1; 6 } 7 8 int main() 9 { 10 func(); (gdb) info line 3 Line 3 of "test.c" is at address 0x4004ed <func> but contains no code. (gdb) p &func $1...
I'm trying to parse a char string into an INT. If I had... ``` unsigned char color[] = "255" ``` And wanted to parse this into an INT. How would I go about doing this? I tried... ``` unsigned char *split; split = strtok(color," ,.-"); while(split != NULL) { split = strok(NULL, " ,.-); } ``` This just gives...
To convert a string to integer, callstrtol: ``` char color[] = "255"; long n; char *end = NULL; n = strtol(color, &end, 10); if (*end == '\0') { // convert was successful // n is the result } ```
I need to use tcl.h in my C project (VS 2012) for registering function in SQLite. I have downloaded Tcl for windows and installed it. But my project still doesn't recognize when I write #include . What should I do to get access to this header? Thanks in advance.
Open the project properties and do :
I'm learning C currently,. Using Stat(2) system call How would I compare 2 files st_ino(Inodes) & st_dev(device) and if the same, not to copy the file from source to destination. I can't find any good examples online I am looking at this codehttp://www.people.fas.harvard.edu/~lib215/lectures/lect02/5_Code/llcopy.c
You already have the idea how to do it, just try to translate your thoughts into code: ``` struct stat src, dst; int err; err = stat(src_file, &src); if (err < 0) { perror("stat"); exit(1); } err = stat(dst_file, &dst); if (err < 0) { perror("stat"); exit(1); } if ((src.st_dev == dst.st_dev) && (src.s...
Upon invoking a function,or returning a value from a function,that expects a value of typeT,does using a constant literal without explicit cast invoke undefined behavior? For example,we have a function who's prototype islong foo(unsigned long x);Invocation:foo(4); //does this invoke UB? long foo(unsigned long x) { x...
No, it is all well-defined. There exists an implicit conversion rule between the two types, so theintis simply converted to anunsigned longand the program works as expected.
In C program, I want to display the current version of compiler which was used in the program. Like, ``` char *version; version = malloc(sizeof(char) * 50); strcpy(version, ??? ); printf("Current compiler version is ...%s", version); ``` In this case, what should I put in "???" blank? I guess there is MACRO somewh...
Print_MSC_VERto get just the MSC version. Print_MSC_FULL_VERto get the full MSC version. Try this! ``` printf("Current compiler version is ...%d\n", _MSC_VER); printf("Current compiler full version is ...%d\n", _MSC_FULL_VER); ``` It is an integer MACRO. So, hold it in an int.
I am some kind of newbie in programming and i was just asking myself, if i can switch between folders with the system() command and work there, just like i can do when i type in the commands in the terminal by myself. It's not that kind of very important problem, but it would be nice to know.
You can do the following possibly:system ("cd /path/to/dir; pwd");. Which is, separate the commands via a semicolon. Although once the function returns the directory change will not be applicable anymore. This is because thesystemcommand spawns a new process to execute whatever you have put in the arguments. Once the ...
I'm discovering GDB and i would like to know if it's possible to get the memory address of the declaration of a function, for instance: ``` int func() { return 1; } int main() { func(); return 0; } ``` How do I know at which address is declared the functionfunc()?
You can also useinfo line <line number>to get the address at line number as below: ``` (gdb) list 1 #include <stdio.h> 2 3 int func() 4 { 5 return 1; 6 } 7 8 int main() 9 { 10 func(); (gdb) info line 3 Line 3 of "test.c" is at address 0x4004ed <func> but contains no code. (gdb) p &func $1...
I'm trying to parse a char string into an INT. If I had... ``` unsigned char color[] = "255" ``` And wanted to parse this into an INT. How would I go about doing this? I tried... ``` unsigned char *split; split = strtok(color," ,.-"); while(split != NULL) { split = strok(NULL, " ,.-); } ``` This just gives...
To convert a string to integer, callstrtol: ``` char color[] = "255"; long n; char *end = NULL; n = strtol(color, &end, 10); if (*end == '\0') { // convert was successful // n is the result } ```
When I dynamically allocate memory in C with a function of themallocfamily is there some rule (coming from the C standard or the inner workings of an OS) as to what the initial value of that memory is? ``` int* ptr = malloc(sizeof (*ptr)); bool b = *ptr == 0; // always true? ```
The initial value of dynamically-allocated memory is indeterminate as far as the C standard is concerned. Some platforms may happen to give you zeros, others may happen to give you guard values like 0xEE everywhere, but none of this can be relied upon in a portable C program. If you need zeros, the most conventional...
I have a structure that has a function as one of it's members. Like ``` Creature.move = moveAway; ``` moveAway being name of the function. So how can you exactly use that function?
C does not have member functions, which means that your member apparently is not a function, but a functionpointer. In order to call the target function through that pointer it you have a choice of either ``` Creature.move( /* arguments */ ); ``` or ``` (*Creature.move)( /* arguments */ ); ``` Choose whichever you...
How can we pass a #defined macro to the function as an argument where the function accepts reference. This is what I am trying the wrong way: ``` #define RST_REQ_REG 0x04 #define RESET_CMD 0x01 write_register(RST_REQ_REG, RESET_CMD, 1); // Decleration of write_reg is void write_register(uint8_t regAddr, uint8_t...
You can't.write_registeraccepts apointeras second argument, period. You probably want this: ``` #define RST_REQ_REG 0x04 #define RESET_CMD 0x01 uint8_t cmdbuffer[1] = {command}; write_register(RST_REQ_REG, cmdbuffer, 1); ``` Maybe you want to wrap this into another function: ``` void write_command(uint8_t regA...
I'm new to C, coming from Java. I made the following trivial program that compiles fine, but nano throws me a Segmentation Fault whenever I run it. The point of it is to traverse through the array and have it print out each element on a separate line. ``` int main() { int array[5] = {1, 2, 3, 4, 5}; int i = ...
First,putstakes an null terminated strings, not an integer. Second, to determine the number of elements in the array, usesizeof(array)/sizeof(array[0]), becausesizeof(array)is the total number of bytes of the array. Third, useint main(void)for standard C. Try this: ``` int main(void) { int array[5] = {1, 2, 3, 4,...
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed7 years ago.Improve...
You are callingsettimeofday()when you should be callinggettimeofday()!
This question already has answers here:Are global variables always initialized to zero in C? [duplicate](6 answers)Closed7 years ago. This is a program which I came across on the net that calculates the value of𝝅. ``` #include <stdlib.h> #include <stdio.h> long a=10000,b,c=2800,d,e,f[2801],g;//--------HERE the val...
As pointed out inthisquestion, global variables are initialized to0by default. In your code,bis declared as a global variable.
I have a function that takes a void pointer as argument. I would like to cast that pointer to a specific type (e.g. double) and then increment it. The code below does exactly what I want ``` function(void *out){ double *temp = (double*) out; temp++; out = temp; /* do something with out here */ } ``` However...
The expression ``` ((double*)out)++; ``` is problematic because it tries to increment the result of a cast, which is not anlvalue. However, it is perfectly fine to add1to the result of a cast, and assign it back toout: ``` out = ((double*)out)+1; ```
How can we pass a #defined macro to the function as an argument where the function accepts reference. This is what I am trying the wrong way: ``` #define RST_REQ_REG 0x04 #define RESET_CMD 0x01 write_register(RST_REQ_REG, RESET_CMD, 1); // Decleration of write_reg is void write_register(uint8_t regAddr, uint8_t...
You can't.write_registeraccepts apointeras second argument, period. You probably want this: ``` #define RST_REQ_REG 0x04 #define RESET_CMD 0x01 uint8_t cmdbuffer[1] = {command}; write_register(RST_REQ_REG, cmdbuffer, 1); ``` Maybe you want to wrap this into another function: ``` void write_command(uint8_t regA...
I'm new to C, coming from Java. I made the following trivial program that compiles fine, but nano throws me a Segmentation Fault whenever I run it. The point of it is to traverse through the array and have it print out each element on a separate line. ``` int main() { int array[5] = {1, 2, 3, 4, 5}; int i = ...
First,putstakes an null terminated strings, not an integer. Second, to determine the number of elements in the array, usesizeof(array)/sizeof(array[0]), becausesizeof(array)is the total number of bytes of the array. Third, useint main(void)for standard C. Try this: ``` int main(void) { int array[5] = {1, 2, 3, 4,...
How do I convert anuint8_t array[2]to anuint16_t value I am reading two bytes of data from an i2c device into an array and have to convert that to an integer to perform conversions on the data. ``` static int i2cRead(uint8_t *buffer, uint32_len, uint16_t addr); static uint16_t readVaue(uint8_t reg) { uint8_t bu...
``` #include <stdio.h> #include <stdint.h> int main(void) { uint8_t array[] = {0xAA, 0x55}; // Big endian conversion uint16_t value = ((uint16_t)(array[0])<<8) + array[1]; printf("%X\n", value); // Little endian conversion value = ((uint16_t)(array[1])<<8) + array[0]; printf("%X\n", v...
In C programming, suppose that I have some input strings with unknown length like: abcde.xxx abc.xxx abcdefgh.xxx .... How can I take the last 4 characters from them? I tried this way but it doesn't work: ``` char dest[] = "abcdef.ghi"; char s[5]; memset(s, '\n', sizeof s); strncpy(s, dest - 5, 4); ``` But I can't...
``` char s[5] = {0}; size_t len = 0; char dest[] = "abcdef.ghi"; char *p = strchr(dest, '.'); if(!p) { // error no '.' return; } len = strlen(p); if(len != sizeof(s)-1) { // More or less than 3 characters plus '.' return; } strcpy(s, p); ```
When I use the codeenviron=NULL, it means that I'm erasing entire environment for that process. But I wonder whyenvrion=NULLmeans that it is erasing entire environment for that process. Basically, environment variables are in the address space below the process's stack address range. So,environvariable is indicatin...
The C standard library accesses the environment through theenvironpointer. If you set that pointer to something different, that makes the standard library no longer find the previously set environment variables and thus has the effect of clearing the environment or setting it to whatever you set theenvironpointer to.
I am implementing a non-blocking socket IO reactor using linuxselect. Let's say, a server and a client are in communication. If the client or the server is down, the other side is supposed to receive anEOFwhich can be told by the return value ofreadcall (C function call). ``` if(read(fd, ...) == 0) { printf("Endpoint...
If the other end sends one byte and then closes the connection, then you will first read one byte, and then thenextcall toreadwill return 0. There's no way for a singlereadcall to do both - because it has to return 0 to indicate closure, and non-0 if it read some data.
I've used linuxbrew to install gcc 5.3 on a machine on which I don't have sudo access. I now want to link with X11: ``` > gcc test.c -lX11 ld: cannot find -lX11 ``` I've checked thatlibX11.soexists in/usr/lib64/which is on the compiler'sLIBRARY_PATH. If I use the system'sgccit works fine, but I need a newer version ...
use-Lflag, like this-L/usr/lib64, or you can specify full path to library like thisgcc test.c /usr/lib64/libX11.so
When trying to create a static library from a makefile, the library does not get created. Anyone have any input on this? ``` all: test.exe test.exe: test.o gcc -o test.exe test.o -L. -ltest test.o: libtest.a gcc -c test.c libtest.a: ABC-test.o ar rcs ABC-test.o ABC-test.o: A-test.c B-test.c C-test.c ...
In this rule: ``` libtest.a: ABC-test.o ar rcs ABC-test.o ``` you forgot to pass the name of the library toar. Try this: ``` libtest.a: ABC-test.o ar rcs libtest.a ABC-test.o ``` or better: ``` libtest.a: ABC-test.o ar rcs $@ $^ ```
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 Node definition of a graph in c: ``` struct AdjListNode { int dest; struct AdjListNode* next; }; ``` What...
``` struct AdjList { struct AdjListNode *head; }; struct Graph { int V; struct AdjList* array; }; ``` visit here:http://www.geeksforgeeks.org/graph-and-its-representations/
I'm trying to make my processwaitpid()for a child process, but also print something every interval amount of time. My current plan is to schedule anitimer,waitpid(), handle theSIGALRMprinting, and stopping the timer when thewaitpid()finishes. The only part I can't figure out is preventing theSIGALRMfrom interrupting...
Ifwaitpid()returned-1anderrnoequalsEINTRjust start over callingwaitpid(). ``` pid_t pid; while (((pid_t) -1) == (pid = waitpid(...))) { if (EINTR == errno) { continue; } ... } ``` Alternatively (at least for Linux) the return ofwaitpid()on reception of a signal could be avoided via theSA_RESTARTflag se...
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed7 years ago.Improve...
Change your scanf to ``` scanf("%d", &x); ``` and it will work.scanf("i%", &x);is telling scanf that you want to match a literal 'i' and a literal '%'.
I am usingrecv()to read data from a socket andfcntl()to set the socket blocking/non-blocking. My question is: If I calledrecv()(blocking) and I callfcntl()from another thread and set the socket non-blocking, will the currently runningrecv()return or the effect offcntl()will only take place after the blockingrecv()retu...
It won't affect the current receive operation. Strange thing to do.
Currently looking atthisguide to using OpenMP with C/C++ programs and wonder what they mean bycreating a magic functionin the quote below: Internally, GCC implements this by creating a magic function and moving the associated code into that function, so that all the variables declared within that block become loc...
A "magic" function is a function created by the compiler - its magicness comes from the fact that you as a programmer don't need to do anything, it's "magically done for you".
``` typedef struct { int member; } mystruct; void myfunc(mystruct **data) { mystruct *const *p; for(p = data; *p !=NULL; p++) { printf("hello\n"); } } void main(int argc, char *argv[]) { myfunc(NULL); } ``` tried with the above code am getting segmenta...
The*pin the for loop dereferences the first pointer. But that pointer isNULL, as you call your function withmyfunc(NULL);.
Maybe it is very silly question. However I can not find a proper answer in google until now. We can find so many document and website which explain how linux kernel allocates some memory, like slab / buddy / kmalloc / vmalloc... My question is how linux's user application allocates memory which they want. Can it be d...
Sooner or later the user-space allocator is going to need pages of memory mapped into the virtual address space of the process, and that can only be done by the kernel. So the answer to your last question is no, it can not be done without the kernels help.
This question already has answers here:How to get absolute value from double - c-language(5 answers)Closed7 years ago. Is there a standard C function that would take a double and return its absolute value as a double? It is not that difficult to write one, but if it exists why bother. There is int abs(int x), but why...
What you want isfabs.fabsffor floats,fabsfor doubles. http://pubs.opengroup.org/onlinepubs/009695399/functions/fabs.html
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 installed Dev C++. Now I want to run my C code from Command window in windows 8.1 ...
Unfortunately, what you've tried to do wouldn't work since Dev C++ is an integrated development environment and it has its own compiler (MinGW), besides, you only need a compiler so your best bet is to offer a look at this topic :Compiling C++ in cmd using MinGW on Windows 8Side note : most basics are covered in almos...
I can perform normal scan using ioctl SIOCSIWSCAN and SIOCGIWSCAN and get list of AP, but when I set card into monitor mode i get errno = Operation not supported. Is there a different ioctl call for passive scans?? I know the wifi card is not the issue, because I get results with airodump-ng and I checked two differ...
First, on the command line type: ``` iw phy <phy> info ``` and see if new_interface is listed under supported commands. You can get the phy for your cards by: iw dev Second, I have found that it's easier to set a card in monitor mode if I delete all interfaces on the phy first. Some cards don't play well if there ...
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 What is the difference between the following two invocations ofscanfand when should I use one or the other?...
%[^\n]is for reading string until hit to\nor EOF. Whitespaces can be included in the string. %sis for reading string until hit to whitespace or EOF. It is better to specify maximum length to read to avoid buffer overrun like this: ``` char word[100]; scanf("%99s", word); /* don't forget to reserve a space for termi...
I can perform normal scan using ioctl SIOCSIWSCAN and SIOCGIWSCAN and get list of AP, but when I set card into monitor mode i get errno = Operation not supported. Is there a different ioctl call for passive scans?? I know the wifi card is not the issue, because I get results with airodump-ng and I checked two differ...
First, on the command line type: ``` iw phy <phy> info ``` and see if new_interface is listed under supported commands. You can get the phy for your cards by: iw dev Second, I have found that it's easier to set a card in monitor mode if I delete all interfaces on the phy first. Some cards don't play well if there ...
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 What is the difference between the following two invocations ofscanfand when should I use one or the other?...
%[^\n]is for reading string until hit to\nor EOF. Whitespaces can be included in the string. %sis for reading string until hit to whitespace or EOF. It is better to specify maximum length to read to avoid buffer overrun like this: ``` char word[100]; scanf("%99s", word); /* don't forget to reserve a space for termi...
Studying for finals, I got stuck on this problem. They ask how many times the following code executes printf: ``` #include "csapp.h" void doit() { Fork(); Fork(); printf("hello\n"); return; } int main() { doit(); printf("hello\n"); exit(0); } ``` The solutions say that it printf executes 8 times, but I ca...
2 forks - Four processes. Each process has twoprintfswithhello(one inmainand one indoit- hence 8.
I have the following line in my code: ``` 1 || printf("A"); ``` I was surprised to see thatAis not printed; I am guessing this is due to compiler optimizations:1was evaluated astrue, and, because the entireORexpression must have beentrue, theprintf("A")wasn't even evaluated... Can someone confirm this? Would the pro...
In the expressiona || b,bis only evaluated whenais false (similarly ina && b,bis only evaluated ifaistrue). This is known as short-circuiting and it's not an optimization, it's behavior mandated by the standard. If the compiler did anything else, it'd not be a valid implementation. This allows you to do things likea ...
I have a function like this: ``` foo(int a[], int b); ``` and I want to print the name of the array in the function. If I call ``` foo(cards, 5); ``` I want to print this:array name:cards;array size:5. How should I do this?
You can't. By the time your program is executing, the name "cards" that was used in the source code is no longer available. But you can do: ``` void foo(int *a, int b, const char *name); ... foo(cards, 5, "cards"); ```
I am confused....I printed__TIME__in C then it prints time and then again after 5 seconds I executed it. I did it for 5 times. But for all the times, the time remained same. Time is not getting changed even not second also getting changed. All the time hours minutes and seconds remain same. So how can I print Current ...
__TIME__is a preprocessor macro that expands to the timeat which the file was compiled. It will not change between consecutive runs of the program. As you can see in the link to the documentation that I posted, it clearly says that it expands to a "string constant". If you want to get the current time, have a look at...
consider this line of code: ``` file_desc = open(file, O_RDWR | O_CREAT | O_EXCL, 0444); ``` how can you open 'file' with read only permissions for owner/group/other (the 0444) while you say open it with O_RDWR access mode? thanx
From theopenman page: Note that this mode only applies to future accesses of the newly created file; the open() call that creates a read-only file may well return a read/write file descriptor. So the process that creates the file can write to it, but some other process can't (unless it changes the permissions first)...
Is there a way to go from the below ``` int a; ///< This is a variable int b = 3; ///< This is another variable ``` To the below? ``` int a; ///< This is a variable int b = 3; ///< This is another variable ```
align_right_cmt_spanshould be the correct setting.
I want to know, How do we make sure if a variable defined withregisterspecifier got stored in CPU register?
Basically, you cannot. There is absolutely nothing in the C standard that givesyouthe control. Using theregisterkeyword is giving the compiler ahintthat that the variablemaybestored into a register (i.e., allowed fastest possible access). Compiler is free to ignore it. Each compiler can have a different way of accept...
This question already has answers here:What is the size of a pointer? What exactly does it depend on?(2 answers)Closed7 years ago. I am using 64bit ubuntu machine (x86_64).My senior has told that in C program size of any pointer is always equal to size of int . Is it correct ?But when i executesizeof(int)I am getting...
My senior has told that in C program size of any pointer is always equal to size of int . Is it correct? NO, that is not correct. There aremultiple different memory models possible, often on the same system at the same time. Often systems support running ILP32 and LP64 processes at the same time. While anintis 4 b...
Hi I'm trying to create a dll of my C program, my program sends and receives messages to a usb device. I'm using libusb1.0 as a library for my C Program. Now that I want to make my program into a dll to be usable by other programs, I can't imagine how to import or bundle my dll with the libusb. So researching on my p...
In Windows a DLL is basically just a normal executable file with a special entry-point (DllMaininstead ofWinMainormain), and as any other normal executable you can use both static and dynamic libraries.
consider this line of code: ``` file_desc = open(file, O_RDWR | O_CREAT | O_EXCL, 0444); ``` how can you open 'file' with read only permissions for owner/group/other (the 0444) while you say open it with O_RDWR access mode? thanx
From theopenman page: Note that this mode only applies to future accesses of the newly created file; the open() call that creates a read-only file may well return a read/write file descriptor. So the process that creates the file can write to it, but some other process can't (unless it changes the permissions first)...
Is there a way to go from the below ``` int a; ///< This is a variable int b = 3; ///< This is another variable ``` To the below? ``` int a; ///< This is a variable int b = 3; ///< This is another variable ```
align_right_cmt_spanshould be the correct setting.
I want to know, How do we make sure if a variable defined withregisterspecifier got stored in CPU register?
Basically, you cannot. There is absolutely nothing in the C standard that givesyouthe control. Using theregisterkeyword is giving the compiler ahintthat that the variablemaybestored into a register (i.e., allowed fastest possible access). Compiler is free to ignore it. Each compiler can have a different way of accept...
This question already has answers here:What is the size of a pointer? What exactly does it depend on?(2 answers)Closed7 years ago. I am using 64bit ubuntu machine (x86_64).My senior has told that in C program size of any pointer is always equal to size of int . Is it correct ?But when i executesizeof(int)I am getting...
My senior has told that in C program size of any pointer is always equal to size of int . Is it correct? NO, that is not correct. There aremultiple different memory models possible, often on the same system at the same time. Often systems support running ILP32 and LP64 processes at the same time. While anintis 4 b...
Hi I'm trying to create a dll of my C program, my program sends and receives messages to a usb device. I'm using libusb1.0 as a library for my C Program. Now that I want to make my program into a dll to be usable by other programs, I can't imagine how to import or bundle my dll with the libusb. So researching on my p...
In Windows a DLL is basically just a normal executable file with a special entry-point (DllMaininstead ofWinMainormain), and as any other normal executable you can use both static and dynamic libraries.
This question already has answers here:What is the size of a pointer? What exactly does it depend on?(2 answers)Closed7 years ago. I am using 64bit ubuntu machine (x86_64).My senior has told that in C program size of any pointer is always equal to size of int . Is it correct ?But when i executesizeof(int)I am getting...
My senior has told that in C program size of any pointer is always equal to size of int . Is it correct? NO, that is not correct. There aremultiple different memory models possible, often on the same system at the same time. Often systems support running ILP32 and LP64 processes at the same time. While anintis 4 b...
Hi I'm trying to create a dll of my C program, my program sends and receives messages to a usb device. I'm using libusb1.0 as a library for my C Program. Now that I want to make my program into a dll to be usable by other programs, I can't imagine how to import or bundle my dll with the libusb. So researching on my p...
In Windows a DLL is basically just a normal executable file with a special entry-point (DllMaininstead ofWinMainormain), and as any other normal executable you can use both static and dynamic libraries.
Let's say I have a function which takes an array of structs, defined like so: ``` void Foo(struct MyStruct *s, int count) { for (int i = 0; i < count; ++i) { // Do something with s[i] } } ``` Are these following two snippets guaranteed to behave the same way? ``` struct MyStruct s; s.x = 0; s.y = 0;...
The answer is yes, they are effectively the same. First, arrays are passed as pointer to its first element, when used in function arguments. Actually, all objects in C can be treated as a array of one element of that type in terms of storage.
So i have been trying to bitshift 2 bytes from an array that i have, I sometimes end up with good values but not all the time. So here is an example. ``` char buffer[2]; //current character buffer to store the bytes unsigned int number; //the unsigned int to store values number = buffer[0] << 8 | buffer[1]; ...
This is because thecharwas promoted to integer, with its sign bit, you need to convert tounsignedvalue before the promotion is done. Sonumber = buffer[0] << 8 | buffer[1];should be ``` number = (unsigned char)buffer[0] << 8U | (unsigned char)buffer[1]; ```
``` entry -> data ``` holds ``` "key_string \0 value_string \0" ``` (that is, two concatenated and null terminated strings) I want to pass the key and value into ``` kvstore_put(&(server ->store), key, value); ``` as arguments.
You don't need to copy anything - it can all be done with pointers. Because it's null terminated, the input string can double as the key. The value can be set in a string pointer with: ``` char *pszValue = strchr (pszKeyString, 0)+1; ``` No copying, very simple implementation.
Is there a way to import all strings from a text file at once? I want to import all prices from a text file, where the string is composed by the name of the product and the price itself in the same line. Example: "Wood 5\nIron 10\n". My function is: ``` fp = fopen("prices.txt", "r"); fgets(chestplate, 80, (FILE*)fp);...
This is how you would loop through all the lines in the file. ``` char string[80]; while (fgets(string, 80, fp)) { // Do something to string } ```
Given an array whose elements are sorted, return the index of a the first occurrence of a specific integer. we have to do this in sub-linear time. I.e. do not just go through each element searching for that element. can we solve this using binary search???
you could perform a binary search on the array,it means the index the binary search resulted was not the first occurence.
So i just updated my arduino to and my code doesn't seem to want to compile any more at first i thought it was a problem in my code but after trying a code that use to work it gave the same error which is: avr-g++: error: missing filename after '-o' exit status 1 Error compiling. The platform i am running for my ar...
So I solved my problem by uninstalling and then reinstalling the Arduino platform. But I have no clue on what is causing this problem that has occured multiple times now.
I need to print upword and downword number at a same time but with single variable and single loop. For eg. ``` If I give input 5 then output should be 5 & 1 4 & 2 3 & 3 2 & 4 1 & 5 ``` But the main condition is single loop and single variable Thanks.
You can use structures to have single variable have multiple data. ``` #include <stdio.h> int main(void) { struct data { int n, i; } d; if (scanf("%d", &d.n) != 1) return 1; for (d.i = 1; d.i <= d.n; d.i++) { printf("%d & %d\n", d.n - d.i + 1, d.i); } return 0; } ```
For example: ``` int f1() { return 3; } void f2(int *num) { *num = 3; } int n1, n2; n1 = f1(); f2(&n2); ``` With f1, we can return a value and do "variable=f1()" But the same can be done with a void function that updates the value of that variable given its address without having to do "variable=f1()". So, ...
The main problem with making everything a void function (which in some people's lexicon is called a "routine") is that you can't chain them easily: ``` f(g(x)) ``` becomes, if you really want to chain it: ``` int gout; f((g(x, &gout), gout)) ``` Which is painful.
This question already has answers here:How to generate a random integer number from within a range(11 answers)Closed7 years ago. I want to generate random points in a specific range for an opengl program, say points between the coordinates Xmin=200, Xmax = 400 and Ymin= 200 , Ymax = 400. Actually I am trying to simu...
To generate randomly distributed points in a range [min, max] one can use the following formula: ``` (rand() % (max- min)) + min ``` The first part generates random numbers in the range [0, max-min] which are then shifted to [min, max] by adding min to it.
On OSX, after downloading theruby repositorylatest commit from github and following the instructions to build, I runmakebut I get the error: ``` Failed to configure openssl. It will not be installed. ``` If I runmake check, I get more information. ``` Skipping `gem cert` tests. openssl not found. ... `<class:TestG...
Brew installopenssllibrary as akeg-only. Try passing path to your openssl to your build script: ``` ./configure --with-openssl-dir="$(brew --prefix openssl)" ```
I want to make a small change in one C code,in order to double-check some results.Just few relevant lines ``` FILE *f1_out, *f2_out; /* open files */ if ((f1_out = fopen(vfname, "w")) == (FILE *) NULL) { fprintf(stderr, "%s: Can't open file %s.\n", progname, vfname); return (-1); } ``` Then goes som...
Assuming that yourvelis an array of floats, and yournxyzis the number of floats in that array, and that you want the output on the standard output and not on the file you opened: ``` for (int i = 0; i < nxyz; ++i) { printf("vel[%d] = %f\n", i, vel[i]); } ```
I'm struggling to implement the ability to capture signals in a process using C language. Can anyone help-me with a working example? Thanks.
You'll need to use thesignal.hlibrary. Here's a working example in which I capture SIGINT and print a message to STDOUT: ``` #include<stdio.h> #include<signal.h> void sig_handler(int signo) { if (signo == SIGINT) write(0, "Hello\n", 6); } int main(void) { signal(SIGINT, sig_handler); // Just to...
This question already has answers here:Printing hexadecimal characters in C(8 answers)Closed7 years ago. I have following C code. ``` char a[] = "\x7f\x80"; printf("0x%02x\n",a[0]); printf("0x%02x",a[1]); ``` It should print, ``` 0x7f 0x80 ``` However I'm getting following ? ``` 0x7f 0xffffff80 ``` What changes...
Use the correct types and conversion specifiers: ``` unsigned char a[] = "\x7f\x80"; printf("0x%02hhx\n",a[0]); printf("0x%02hhx",a[1]); ``` Conversion specifierxrequires an unsigned type, and the length modifierhhis used forunsigned char.
``` printf("%x\n",(const uint8_t *)0x0D); printf("%x\n",(const uint8_t)0x0D); printf("%x\n",(uint8_t *)0x0D); printf("%x\n",0x0D); ``` They all give meD. What is it the significance of theconstand the*s here?
%xformat specifier experts the argument to be of typeunsigned int. In your case, ``` printf("%x\n",(const uint8_t)0x0D); printf("%x\n",0x0D); ``` arguments will be promoted (default promotion rule) to match the type, but in case of ``` printf("%x\n",(const uint8_t *)0x0D); //supplying a pointer printf("%x\n",(u...
I have declared an array of 30 elements as:- ``` unsigned char some_array[30]; ``` I store some elements in the array, for eg:- ``` {0xFB, 0x07, 0x0B, 0x02, 0x00, 0x0C, 0x03, 0x08, 0x0F, 0x0F, 0x07, 0x0A, 0x09, 0x06, 0x0D} ``` I need to find the number of elements in this array. ``` sizeof (some_array) / sizeof (...
The number of elements in the array is 30. If you want to know the number of elements to which you've assigned values, you'll have to keep track explicitly. There's no way to distinguish between an array element with some assigned value, and an uninitialized element whose (garbage) value happens to be that same value...
Currently, I am studying Minix and I am doing a system based onthreadsand do not know how to compile my program. For example:Mthreads.c ``` #include <stdlib.h> #include <stdio.h> #include <minix/mthread.h> void hola(int y){ printf("Hola Mundo"); } int main(){ mthread_thread_t a; mthread_create(&a, N...
Usemthreadlibrary when compiling. Try it and you will solve your problem ``` clang Mthreads.c -lmthread ```