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[i] = array[n-i]; array[n-i] = tmp; } } ``` I don't understand why my output is the same as the input: 1 2 3 4 5 6 Is my function call no side effect? What's wrong?
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; } } ``` Moreover you need to use n-1-i instead of n-i
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 have added the node.h file into my node.c file with the implementation ofnovonoh(int valor)function, when I add the "node.h" file into my main.c file, I got this error: 1>main.obj : error LNK2005: _base already defined in node.obj1>main.obj : error LNK2005: _nnil already defined in node.obj What is wrong with the code to get this error ? How I can solve this ?
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 a file.txtinto memory in C. I puttxtfiles in same place with source files, sofileNameis given assmall_addressbook.txt When I run code in eclipse (on macbook), it always printsFile not found, and in Unix, I gotsegmentation fault. I try runninggdbin Unix and I got this error report: ``` Program received signal SIGSEGV, Segmentation fault. __strncpy_sse2_unaligned () at ../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S:666 666 mov %rcx, (%rdi) ```
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()orpoll()to find out when reading or writing is possible again (or you can just busy-wait).
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.0x55. You can use C++14 separators (or whatever they're called) to write it as0b01'01'01'01for better human-readability, esp. in cases where each element is different.
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 student *ptr) { ptr->go; } ```
``` 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 variables. It has no effect on the output. The output will be0even if the call tom(&s)is removed.
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 get segmentation fault?
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 multiplication arithmetic as you are doing, you just need to add the pipe_idx to the pointer and it will do the desired arithmetic for you. You need, ``` char** ptr2 = a + pipe_idx ```
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 check (!!) to prevent going out of bounds(eg.while ((i-1 >= -1) && strlen(word[i-1]....)
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 for such a possibility in "man 7 socket" but didn't find. My question is - how to achieve such a functionality in Linux? Any ideas?
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 connection you need in your application just to achieve this feature.
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 compiler will parse this as a variable with typeunsigned(which is shorthand forunsigned int) and the name of the variable will beint32_t.unsigned int32_t variable_namewould be a syntax error.
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 get the file descriptor from yourFILE *structures. Alternatively you could usechmod(2)and pass it the file name.
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 has changed. What happened to it exactly? (Is all the memory get wiped automatically?)
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 for such a possibility in "man 7 socket" but didn't find. My question is - how to achieve such a functionality in Linux? Any ideas?
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 connection you need in your application just to achieve this feature.
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 compiler will parse this as a variable with typeunsigned(which is shorthand forunsigned int) and the name of the variable will beint32_t.unsigned int32_t variable_namewould be a syntax error.
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 get the file descriptor from yourFILE *structures. Alternatively you could usechmod(2)and pass it the file name.
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 has changed. What happened to it exactly? (Is all the memory get wiped automatically?)
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 always gives output 13 . why this is so?
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.st_ino == dst.st_ino)) { // same file, skip copy } // copy the file ``` check outhttp://linux.die.net/man/2/stat
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 += 10; return 10; } // does this invoke UB ? should we writefoo((unsigned long)4)andreturn (long)10??
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 somewhere showing what I want...
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 process terminates things are lost. Therefore, this directory change is applicable to the process whichsystemspawns, andnotto the working directory of the program which callssystem. Although, depending on what is your purpose, I would recommend seeingfork,execfamily, andchdirin a combination.
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 = (int (*)()) 0x4004ed <func> (gdb) ```
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 always gives output 13 . why this is so?
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.st_ino == dst.st_ino)) { // same file, skip copy } // copy the file ``` check outhttp://linux.die.net/man/2/stat
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 += 10; return 10; } // does this invoke UB ? should we writefoo((unsigned long)4)andreturn (long)10??
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 somewhere showing what I want...
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 process terminates things are lost. Therefore, this directory change is applicable to the process whichsystemspawns, andnotto the working directory of the program which callssystem. Although, depending on what is your purpose, I would recommend seeingfork,execfamily, andchdirin a combination.
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 = (int (*)()) 0x4004ed <func> (gdb) ```
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 me the value 255 for split now. I feel like I need something like... ``` int y = split - '0'; //but this makes an INT pointer without a cast ```
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.st_ino == dst.st_ino)) { // same file, skip copy } // copy the file ``` check outhttp://linux.die.net/man/2/stat
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 += 10; return 10; } // does this invoke UB ? should we writefoo((unsigned long)4)andreturn (long)10??
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 somewhere showing what I want...
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 process terminates things are lost. Therefore, this directory change is applicable to the process whichsystemspawns, andnotto the working directory of the program which callssystem. Although, depending on what is your purpose, I would recommend seeingfork,execfamily, andchdirin a combination.
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 = (int (*)()) 0x4004ed <func> (gdb) ```
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 me the value 255 for split now. I feel like I need something like... ``` int y = split - '0'; //but this makes an INT pointer without a cast ```
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 way is to usecalloc(), which has a chance of being optimized on some platforms.
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 like best. Both variants do the same thing.
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 *writeByte, uint8_t writeByteLen); ``` Thanks !
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 regAddr, uint8_t command) { uint8_t cmdbuffer[1] = {command}; write_register(regAddr, cmdbuffer, 1); } ... write_command(RST_REQ_REG, RESET_CMD); ```
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 = 0; for (i = 0; i < sizeof(array); i++) { puts(array[i]); } } ``` What am I doing wrong?
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, 5}; int i = 0; for (i = 0; i < sizeof(array) / sizeof(array[0]); i++) { printf("%d\n", array[i]); } } ```
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 this question I am trying to measure time in C in microseconds. I tried this code, but the valuetime_passedis a huge number, instead of 0 (or 1). ``` struct timeval start; settimeofday(&start,NULL); struct timeval stop; settimeofday(&stop,NULL); unsigned long long int time_passed = (stop.tv_sec-start.tv_sec)*1000000 + (stop.tv_usec - start.tv_usec); printf("time passed: %llu us\n",time_passed); ```
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 value of b---------// int main() { printf("\nValue of b: %ld", b); getch(); for(;b-c;) f[b++]=a/5; for(;d=0,g=c*2;c-=14,printf("%.4d",e+d/a),e=d%a) for(b=c;d+=f[b]*a,f[b]=d%--g,d/=g--,--b;d*=b); } ``` The calculated value is correct. But how could the programmer be sure that the initial value ofbwould be0? It does not seem to be initialized at all! Is there some specialty about initial value of global variables?
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 if I put everything in one expression like ``` (double*)out++; ``` or ``` ((double*)out)++; ``` the compilter doesn't like it. Is there a more elegant way to do this?
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 *writeByte, uint8_t writeByteLen); ``` Thanks !
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 regAddr, uint8_t command) { uint8_t cmdbuffer[1] = {command}; write_register(regAddr, cmdbuffer, 1); } ... write_command(RST_REQ_REG, RESET_CMD); ```
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 = 0; for (i = 0; i < sizeof(array); i++) { puts(array[i]); } } ``` What am I doing wrong?
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, 5}; int i = 0; for (i = 0; i < sizeof(array) / sizeof(array[0]); i++) { printf("%d\n", array[i]); } } ```
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 buff[2]; i2cWrite(&buff, sizeof(buff), I2CADDR) buffer = // STUCK HERE } ```
``` #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", value); } ```
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 usestrstr()since thedestmay be wrong with the formatxxxx.xxxlikeabcd.xxxy
``` 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 indicating that address space, andenviron=NULLmeans thatenvironis just not indicating that address space anymore, I mean not erasing contents of memory which exists for environment variables. But, why this means erasing entire environment??
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 connection failed\n"); } ``` My question is, will thisEOFevent be overlapped or merged with other data read? For example, the client sends1 byteto the server and accidentally shutdowns immediately. If they happen very close by time, is thereadon server still separable to1 byteandEOF?
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 to compile my actual program.
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 gcc -c 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 will the list definition?
``` 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 thewaitpid(). I've looked in the man pages and don't see any flags for this. Thoughts?
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 set on installing signal handlers. For more on this please see here:http://man7.org/linux/man-pages/man7/signal.7.html
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 this question So I'm starting to code in C and I just found an error and I can't tell why this is happening to me: //variables ``` #include <stdio.h> int main () { int x; printf ("Add a value to variable 'x': "); scanf ("i%", &x); printf ("'x' = %i.\n", x); system ("pause"); return 0; } ``` When I compile it it just tells me that the value of X is 0, no matter what value I assigned to it before.
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()returns and I call it again?
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 local variables of that function (and thus, locals to each thread). ICC, on the other hand, uses a mechanism resembling fork(), and does not create a magic function. Both implementations are, of course, valid, and semantically identical.
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 segmentation fault, its mainly something wrong in that for loop, how to just remove this segmentation fault in that for loop.... actually am learning this double pointer stuff, so i may be a little stupid in asking few question.... thanks in advance
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 done without kernel's help?
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 isn't theredouble abs_d(double x)?
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 . I have added path of bin folder in dev c++ to environment variables. But still I am not able to compile my programm. Any suggestion on how to compile it using cmd will be much appreciated.
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 almost every forum, so if you find yourself blocked don't hesitate to google it up or look for the question in this website itself
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 different cards.
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 are interfaces active. Use ioctl to bring cards up or down and to get the card's hw addr. Otherwise you should be using netlink - You're looking for NL80211_CMD_NEW_INTERFACE in nl80211.h
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? ``` scanf(" %[^\n]", word); scanf(" %s", word); ```
%[^\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 terminating null-character */ ```
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 different cards.
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 are interfaces active. Use ioctl to bring cards up or down and to get the card's hw addr. Otherwise you should be using netlink - You're looking for NL80211_CMD_NEW_INTERFACE in nl80211.h
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? ``` scanf(" %[^\n]", word); scanf(" %s", word); ```
%[^\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 terminating null-character */ ```
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 cannot figure out why. I've been trying to draw the picture of what's going on in the code, but my pictures make it seem like it only execute 4 times.
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 program behave like this with different compilers?
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 != NULL && a->isValid()and be sure that you're not dereferencing a null pointer.
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 and Date using time.h
__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 thetime.hheader.
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). This ensures that the creating process can fill in the fill without worrying about some other process inadvertently overwriting it. Without this feature, it would have to create the process with write permission, fill it in, then remove the write permission, which would allow a window during which some other process could overwrite it.
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 accepting/rejecting thehint. QuotingC11, chapter §6.7.1, (emphasis mine) A declaration of an identifier for an object with storage-class specifierregistersuggeststhat access to the object be as fast as possible.The extent to which such suggestions are effective is implementation-defined. FWIW, most modern-day compilers can detect the mostly-used variables and allocate them in actual register,if required. Remember, CPU register is a scarce resource.
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 4 bytes and forsizeof(int*)I am getting 8 .1. Why am I getting 4 bytes forsizeof(int)in my x86_64?
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 bytes (32 bits) in both ILP32 and LP64, pointers are 8 bytes (64 bits) in LP64.
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 problem, I found that libusb provides a static library and I've seen articles about linking static libraries on a DLL using C++. So my question is... Is it possible to link a static library(.lib file) into a dynamic link library (.dll) in a C environment? P.S. If it is possible can I ask links/tutorials to get me started on developing this?
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). This ensures that the creating process can fill in the fill without worrying about some other process inadvertently overwriting it. Without this feature, it would have to create the process with write permission, fill it in, then remove the write permission, which would allow a window during which some other process could overwrite it.
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 accepting/rejecting thehint. QuotingC11, chapter §6.7.1, (emphasis mine) A declaration of an identifier for an object with storage-class specifierregistersuggeststhat access to the object be as fast as possible.The extent to which such suggestions are effective is implementation-defined. FWIW, most modern-day compilers can detect the mostly-used variables and allocate them in actual register,if required. Remember, CPU register is a scarce resource.
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 4 bytes and forsizeof(int*)I am getting 8 .1. Why am I getting 4 bytes forsizeof(int)in my x86_64?
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 bytes (32 bits) in both ILP32 and LP64, pointers are 8 bytes (64 bits) in LP64.
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 problem, I found that libusb provides a static library and I've seen articles about linking static libraries on a DLL using C++. So my question is... Is it possible to link a static library(.lib file) into a dynamic link library (.dll) in a C environment? P.S. If it is possible can I ask links/tutorials to get me started on developing this?
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 4 bytes and forsizeof(int*)I am getting 8 .1. Why am I getting 4 bytes forsizeof(int)in my x86_64?
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 bytes (32 bits) in both ILP32 and LP64, pointers are 8 bytes (64 bits) in LP64.
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 problem, I found that libusb provides a static library and I've seen articles about linking static libraries on a DLL using C++. So my question is... Is it possible to link a static library(.lib file) into a dynamic link library (.dll) in a C environment? P.S. If it is possible can I ask links/tutorials to get me started on developing this?
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; Foo(&s, 1); ``` vs. ``` struct MyStruct s[1]; // stack-allocated array of size 1 s[0].x = 0; s[0].y = 0; Foo(s, 1); ```
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]; //bitshifting printf("%02x ", number); ``` I seem to be getting this in some cases. ``` ffffffbc // the bc seems to be correct however the f's are not ```
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); fgets(helmet, 80, (FILE*)fp); fclose(fp); ``` This makes the var chestplate "Wood 5" and the var helmet "Iron 10", is there a way to loop the function so I dont need to import one at a time?
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 arduino sketches is Arduino 1.6.6. But my update only concerned the plc it self. I have found people having the same problem through the different patches but no concrete solution. I don't know if this is any-clear and if anyone has a solution to this problem. Thank you.
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, does this mean that we can actually just use void functions for everything? Or is there something that a void function cannot do to replace another int function/(type) function?
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 simulate a volcanic eruption in 2D using simple C code and without using any textures(I cannot use textures in my project). PS: I Have very basic knowledge about opengl, just a beginner. Thanks.
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:TestGemRemoteFetcher>': uninitialized constant TestGemRemoteFetcher::OpenSSL (NameError) ``` Clearly it cannot find openssl, but I have it installed via Brew. What am I missing? There are many answers to this sort of question out there (this, for example), but I can't seem to make any of the solutions work.
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 some calculations and ``` yes = fwrite(vel, nxyz*sizeof(float), 1, f1_out); ``` How to change the last line to get the ascii output?
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 testing purposes while(1) sleep(1); return 0; } ```
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 I have to make to get the output0x7f0x80? Thanks,
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",(uint8_t *)0x0D); //supplying a pointer ``` You'll invokeundefined behavior, as perC11, chapter §7.21.6.1 [...] If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined. [...]
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 (some_array[0]); ``` yields 30, which is the total number of elements the array can store. ``` strlen(some_array); ``` yields 4, which is the index of 0x00 element in the array. How can i determine the number of elements stored in the array ??
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, NULL, (void*)hola, 0); mthread_join(a, NULL); } ``` Then I run clang to compile: ``` # clang Mthreads.c /var/tmp/g-10649b.o: In function `main': Mthreads.c:(.text+0x5f): undefined reference to `mthread_create' Mthreads.c:(.text+0x7d): undefined reference to `mthread_join' clang: error: linker command failed with exit code 1 (use -v to see invocation) ``` Any idea how to make this work?
Usemthreadlibrary when compiling. Try it and you will solve your problem ``` clang Mthreads.c -lmthread ```