question
stringlengths
25
894
answer
stringlengths
4
863
I am trying to write a function that can inverse the string contents. But when I run the program, it cannot work properly...... So my question is : Can somebody tell me what is the problem of this code? ``` #include <stdio.h> #include <string.h> #define ARR "It's a perfect day\n" char * string_in(char *, int); int m...
Your second loop should go only till (n/2) ``` for(int i = 0; i < (n/2); i++) ```
``` #include <unistd.h> #include <stdio.h> int child; pid_t pid; int main(void) { int i ; for(i=0;i<3;i++) { pid = fork(); child = getpid(); if( pid == 0) // child printf("Child process %d\n", child); } return 0;...
A picture is worth a thousand words:
I need to define a preprocessor macro swap(t, x, y) that will swap two arguments x and y of a given type t in C/C++.Can anyone have any opinion on how can i do it?
If you want to swap basic types like int or char (which implement the XOR operator) you can use the tripple XOR trick to swap the values without the need of an additional variable: ``` #define SWAP(a, b) \ { \ (a) ^= (b); \ (b) ^= (a); \ (a) ^= (b); \ } ``` If you're swapping complex ...
So, I got file "lfs.c" "lfs.h" "lfs.def" and ".gitignore". I tried installing MinGW and typing in that command:gcc lfs.c(Keep in mind that I'm a total newbie in such things), which leaves me with error "failed to include lua.h"... I don't know how to do that, can anyone please explain to me how to do that? Or at least...
You are likely to be missing Lua include files; seethis SO answerfor details on how to set it up. Simply getting lfs.dll may not be so easy as different DLLs may depends on different Lua DLLs on Windows. I have lfs.dll that is compiled against Lua51.dll, so if this works for your project/needs, you canget a compiled ...
I have this code: ``` __global__ void testCuda() {} void wrapperLock() { std::lock_guard<std::mutex> lock(mutexCudaExecution); // changing this value to 20000 does NOT trigger "Segmentation fault" usleep(5000); runCuda(); } void runCuda() { testCuda<<<1, 1>>>(); cudaDeviceSynchronize(); } `...
Using a single CUDA context, multiple host threads should either delegate their CUDA work to a context-owner thread (similar to a worker thread) or bind the context withcuCtxSetCurrent(driver API) orcudaSetDevicein order to not overwrite the context resources.
I want to calloc 25 bytes of memory exactly. In this case, msg_len = 5 bytes, since that is what the input is. This is the code I have: ``` int full_msg_size = 20 + msg_len; printf("full_msg_size: %d\n", full_msg_size); void *full_msg = calloc(full_msg_size, sizeof(char)); printf("size of full_msg: %d\n", (int*...
You are most likely allocating the correct number of bytes but you are asking how big a pointer to a void is. And on a 64 bit box it will very likely be 8 bytes. If it failed to allocate the amount of memory you asked for then full_message would have the value NULL.
I need to create matrix of Gaussian distributed random numbers in C. I was curious how does matlab generates it so that I can take a lead from that.
To generate Normal random numbers, the C code: ``` #include <stdlib.h> #include <math.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif double drand() /* uniform distribution, (0..1] */ { return (rand()+1.0)/(RAND_MAX+1.0); } double random_normal() /* normal distribution, centered on 0, std dev 1 */ ...
I'm practically new to C programming and I've been trying to get a simple average function right, but the fractional part of the answer keeps messing up...?? ``` #include <stdio.h> #include <float.h> float cal(int num1,int num2,int num3); int main(){ int a,b,c; float avg; a=10; b=5; c=11; ...
You're doing integer division here. Cast it tofloat(at least one of them) or use float literals before division to force it to use float division. For example, change ``` avg1=(num1+num2+num3)/3; ``` to ``` avg1=(num1+num2+num3)/(float)3; // 1. cast one to float avg1=(num1+num2+num3)/3.0f; // 2. use float li...
I'm trying to open a file usingavformat_open_inputand it crashes even if the file exists. ``` av_register_all(); AVFormatContext *avFormatContext; if (avformat_open_input(&avFormatContext, argv[1], NULL, NULL) < 0) { av_log(0, AV_LOG_FATAL, "Wasn't possible opening the file: %s", argv[1]); return -1; } ```
You must NULL the avFormatContext variable first: ``` av_register_all(); AVFormatContext *avFormatContext = NULL; if (avformat_open_input(&avFormatContext, argv[1], NULL, NULL) < 0) { av_log(0, AV_LOG_FATAL, "Wasn't possible opening the file: %s", argv[1]); return -1; } ```
I have this code: ``` __global__ void testCuda() {} void wrapperLock() { std::lock_guard<std::mutex> lock(mutexCudaExecution); // changing this value to 20000 does NOT trigger "Segmentation fault" usleep(5000); runCuda(); } void runCuda() { testCuda<<<1, 1>>>(); cudaDeviceSynchronize(); } `...
Using a single CUDA context, multiple host threads should either delegate their CUDA work to a context-owner thread (similar to a worker thread) or bind the context withcuCtxSetCurrent(driver API) orcudaSetDevicein order to not overwrite the context resources.
I want to calloc 25 bytes of memory exactly. In this case, msg_len = 5 bytes, since that is what the input is. This is the code I have: ``` int full_msg_size = 20 + msg_len; printf("full_msg_size: %d\n", full_msg_size); void *full_msg = calloc(full_msg_size, sizeof(char)); printf("size of full_msg: %d\n", (int*...
You are most likely allocating the correct number of bytes but you are asking how big a pointer to a void is. And on a 64 bit box it will very likely be 8 bytes. If it failed to allocate the amount of memory you asked for then full_message would have the value NULL.
I need to create matrix of Gaussian distributed random numbers in C. I was curious how does matlab generates it so that I can take a lead from that.
To generate Normal random numbers, the C code: ``` #include <stdlib.h> #include <math.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif double drand() /* uniform distribution, (0..1] */ { return (rand()+1.0)/(RAND_MAX+1.0); } double random_normal() /* normal distribution, centered on 0, std dev 1 */ ...
I'm practically new to C programming and I've been trying to get a simple average function right, but the fractional part of the answer keeps messing up...?? ``` #include <stdio.h> #include <float.h> float cal(int num1,int num2,int num3); int main(){ int a,b,c; float avg; a=10; b=5; c=11; ...
You're doing integer division here. Cast it tofloat(at least one of them) or use float literals before division to force it to use float division. For example, change ``` avg1=(num1+num2+num3)/3; ``` to ``` avg1=(num1+num2+num3)/(float)3; // 1. cast one to float avg1=(num1+num2+num3)/3.0f; // 2. use float li...
Suppose we have a stack as defined below: ``` typedef struct node { int data; struct node *next; } node; ``` I copied this definition from a book but I'm not exactly sure what the last 2 lines do. Does the node declaration at the end have anything to do with the structure declaration or is it just an object ...
The code is equivalent to: ``` struct node { int data; struct node *next; }; typedef struct node node; ``` By separatingtypedefwith thestruct nodetype, it's easier to seenodein your code is an alias forstruct nodemade bytypedef.
In a header file I have the following code which gives me the error in the title, while trying to link. ``` #ifndef BOOLEAN_H #define BOOLEAN_H #ifndef FALSE #define FALSE 0 #endif #ifndef TRUE #define TRUE !FALSE #endif #endif ``` indicating the error occurs in the line of the last#endif.
gccwhen compiled with-pedanticreports a diagnostic when the translation unit is empty as it is requested by the C Standard. To makegcchappy, you can add a dummytypedefin the empty.cfile: ``` typedef int make_iso_compilers_happy; ``` or ``` extern int make_iso_compilers_happy; ```
So I have to write a program that sorts a 2d array and then returns it but I just found out you cant return an array from a function. I tried researching this but nothing fixes the problem. Any help is appreciated, thanks. Below is the function I wrote to sort the vertical rows. ``` int vertSort(int matrix[][51], in...
Your code does not need to return anything, it modifies the caller's copy of the array. (Arrays cannot be passed by value in C). Change theintreturn type tovoidand all will be well.
This question already has answers here:segmentation fault in C during scanf(4 answers)Closed8 years ago. Why I am getting this error? Please help... I can't understant! It seems that I that I have an illegal access but I can't figure it out... ``` int main () { int repeat = 1; int comamnd = 0; do { pri...
``` scanf ("%d", command); ``` You're passing a zero toscanfas the place to read the input. You want: ``` scanf ("%d", &command); ``` If your compiler didn't warn you, you should switch to a better compiler.
What is the difference betweenchar *aandint *aas both work on Code Blocks for storing character pointer eg. ``` char *c, k = '$'; int *j; j = &k; printf("%c\n%p\n%c\n", k, j, *j); c = &k; printf("%c\n%p\n%c", k, c, *c); ```
Activate diagnostics and don't ignore them (-Wall -Wextra -pedantic-errors).The compiler should tell you that you are doing something disallowed. See here on coliru:http://coliru.stacked-crooked.com/a/31acb5b670254167 ``` main.cpp:7:7: error: incompatible pointer types assigning to 'int *' from 'char *' [-Werror,-Wi...
Let's say I'm writing a C# class with a simple method which returns a int type for example. I build the project which is a class library and then I obtain a dll. Can I use that dll to call that simple method but in C language? I've been doing some research and I found out that is possible if a have a dll written in ...
It is not so straightforward. Since C# is a managed language, it run in a sort of infrastructure, ant to call it from another language outside the dotnet environment you have to host such environment. You can have a look here to start working on:CorBindToRuntimeEx. If you can work with C++ the less painful integratio...
Problem-To print armstrong number between 100 to 500.Logical error-Code is not printing any output.Compiled using codeblocks ide. ``` int a,n,i,j,c; for(j=100;j<=500;j++) { int d=0; n=100; a=n; //assigning a to n as its value will be changed everytime the loop runs. for(i=1;i<=3;i++) //loop wi...
n=100;is inside the for loop, everytime, n will thus be = to100. it should be outside for loop.
What is the difference betweenchar *aandint *aas both work on Code Blocks for storing character pointer eg. ``` char *c, k = '$'; int *j; j = &k; printf("%c\n%p\n%c\n", k, j, *j); c = &k; printf("%c\n%p\n%c", k, c, *c); ```
Activate diagnostics and don't ignore them (-Wall -Wextra -pedantic-errors).The compiler should tell you that you are doing something disallowed. See here on coliru:http://coliru.stacked-crooked.com/a/31acb5b670254167 ``` main.cpp:7:7: error: incompatible pointer types assigning to 'int *' from 'char *' [-Werror,-Wi...
Let's say I'm writing a C# class with a simple method which returns a int type for example. I build the project which is a class library and then I obtain a dll. Can I use that dll to call that simple method but in C language? I've been doing some research and I found out that is possible if a have a dll written in ...
It is not so straightforward. Since C# is a managed language, it run in a sort of infrastructure, ant to call it from another language outside the dotnet environment you have to host such environment. You can have a look here to start working on:CorBindToRuntimeEx. If you can work with C++ the less painful integratio...
Problem-To print armstrong number between 100 to 500.Logical error-Code is not printing any output.Compiled using codeblocks ide. ``` int a,n,i,j,c; for(j=100;j<=500;j++) { int d=0; n=100; a=n; //assigning a to n as its value will be changed everytime the loop runs. for(i=1;i<=3;i++) //loop wi...
n=100;is inside the for loop, everytime, n will thus be = to100. it should be outside for loop.
Why add this constraint when your intentions are to both read and write data to the file? My application wants to open the file in both reading an writing mode. If I usew+it will destroy the previous contests of the file, but at the same time it will create the file if it doesn't exist. However if I use ther+mode, m...
Try something like this. If the first fopen fails because the file does not exist, the second fopen will try to create it. If the second fopen fails there are serious problems. ``` if((fp = fopen("filename","r+")) == NULL) { if((fp = fopen("filename","w+")) == NULL) { return 1; } } ```
I have a question about the following code: ``` void testing(int idNumber) { char name[20]; snprintf(name, sizeof(name), "number_%d", idNumber); } ``` The size of the char arraynameis 20, so if theidNumberis111it works, but how about the actual idNumber is111111111111111111111111111111, how to determine how...
Well, ifintis 32 bits on your platform, then the widest value it could print would be -2 billion, which is 11 characters, so you'd need 7 fornumber_, 11 for%d, and 1 for the null terminator, so 19 total. But you should check the return value fromsnprintf()generally, to make sure you had enough space. For example, if...
I'm currently writing a FUSE application that should implement process based access rights. I now stumble about the fact, that FUSE only provides the ThreadID, not the ProcessID. Now I need to find the PID (or Thread Group ID) for the given Thread ID of a different process. I noticed that the proc fs provides Thread ...
I think you need to use /proc/ to get this info yourself. I can't find any syscall or posix functions that do what you need. /proc/ should be fast as it isn't a real fs on disk and I think it's the only choice.
I need to write a program in C, that prints out last five lines of file by using basic functions like open, read, write, close, lseek. My code so far: ``` int main(int argc, char *argv[]){ int fd1=open(argv[1], O_RDONLY); char c; int currPos = lseek(fd1,-2,SEEK_END); while(currPos != -1){ read...
Why not count the number of characters read while reading back to the fifth newline (call thatn) and then do a read ofncharacters? You don't need to store the data, it's already stored in the file.
my program is taking an argument which says how many prints that should be used. example of arguments: prints 2. I then want to loop through the value after prints, the number 2. and then print that many times. I tried like this: ``` for(i = 0; i < argv[2]; i++) { .... ``` The problem is that argv is a char and...
argv[2] is achar*not achar. argv[2] points to a string( array of null terminated characters ). When you pass an arguments to you program, the argument is in that form. You will have to convert it, you can useatoi();
I'm trying to make a rudimentary countdown timer with the following code ``` #include <stdio.h> #include <unistd.h> int main(int argc, char *argv[]) { printf("Enter time in minutes:"); int x = 0; scanf("%d", &x); x = x*60; while(x!=0) { printf("Remaining time is %d\r", x); x--; ...
Standard output is line buffered by default. If it's ``` printf("Remaining time is %d\n", x); ``` Note the\nhere, it would output every time a\nis seen. However, in your case, you use the carriage return\ron purpose. The alternative method is to flush the standard out manually like this: ``` printf("Remaining time...
There is a header file in my project that contains this line: ``` typedef unsigned short uint16_t; ``` and in MinGW compiler , there is a file "stdint.h" that also has the same line: ``` typedef unsigned short uint16_t; ``` When I compile, I get the following error: error (dcc:1086):redeclaration of uint16_t Ca...
uint16_tis already defined instdint.has an unsigned 16 bit integer type. You should just omit your typedef.
I have this code.c in ubuntu in terminal but when I compile it with gcc this error appeared ``` cod2.c: In function ‘main’: cod2.c:9:11: error: subscripted value is neither array nor pointer nor vector ``` why is that? ``` int main(int argc , char ** argv){ mkdir(argc[1] , 00755); return 0; } ```
You got confused betweenargc(an int representing the number of arguments) andargv(an array of strings containing the command line arguments). Change: ``` mkdir(argc[1], 00755); ``` to: ``` mkdir(argv[1], 0755); ^^^^^^^ ``` (Note that I also removed a redundant0prefix from00755to make it0755- you only need a ...
If I have an array declared as ``` char arr[1] = ""; ``` What is actually stored in memory? What will a[0] be?
Strings are null-terminated. An empty string contains one element, the null-terminator itself, i.e,'\0'. ``` char arr[1] = ""; ``` is equivalent to: ``` char arr[1] = {'\0'}; ``` You can imagine how it's stored in the memory from this.
I'm trying to make a rudimentary countdown timer with the following code ``` #include <stdio.h> #include <unistd.h> int main(int argc, char *argv[]) { printf("Enter time in minutes:"); int x = 0; scanf("%d", &x); x = x*60; while(x!=0) { printf("Remaining time is %d\r", x); x--; ...
Standard output is line buffered by default. If it's ``` printf("Remaining time is %d\n", x); ``` Note the\nhere, it would output every time a\nis seen. However, in your case, you use the carriage return\ron purpose. The alternative method is to flush the standard out manually like this: ``` printf("Remaining time...
There is a header file in my project that contains this line: ``` typedef unsigned short uint16_t; ``` and in MinGW compiler , there is a file "stdint.h" that also has the same line: ``` typedef unsigned short uint16_t; ``` When I compile, I get the following error: error (dcc:1086):redeclaration of uint16_t Ca...
uint16_tis already defined instdint.has an unsigned 16 bit integer type. You should just omit your typedef.
I have this code.c in ubuntu in terminal but when I compile it with gcc this error appeared ``` cod2.c: In function ‘main’: cod2.c:9:11: error: subscripted value is neither array nor pointer nor vector ``` why is that? ``` int main(int argc , char ** argv){ mkdir(argc[1] , 00755); return 0; } ```
You got confused betweenargc(an int representing the number of arguments) andargv(an array of strings containing the command line arguments). Change: ``` mkdir(argc[1], 00755); ``` to: ``` mkdir(argv[1], 0755); ^^^^^^^ ``` (Note that I also removed a redundant0prefix from00755to make it0755- you only need a ...
If I have an array declared as ``` char arr[1] = ""; ``` What is actually stored in memory? What will a[0] be?
Strings are null-terminated. An empty string contains one element, the null-terminator itself, i.e,'\0'. ``` char arr[1] = ""; ``` is equivalent to: ``` char arr[1] = {'\0'}; ``` You can imagine how it's stored in the memory from this.
Since this is my first question after years of finding answers in this site, id like to say a big thanks to everyone. I want to useFANNin an embedded platform, and i am using UVision 4 to code in C. Since i am a C/C++ rookie, i cant figure out if i can / how i can use that library. When i try to simply include the fi...
You have to write your own "sys/time.h" for your embedded system. It must offer everything the original one does to be compatible with your external library. Wether you write one from scratch or wrap something around an existing code base which is compatible to your embedded device is up to you. You can also have a l...
I have a problem understanding how to access specified places in the char arrays in structs. ``` typedef struct Memory { char * bitmap[8]; char * memblock[64]; int i; //... }Memblock int somefunction(void) Memblock mem; ``` Lets say I've allocated the stuct, and now want to do the bitwise operation on bitmap:bitmap...
First of all fix char* bitmap[8] to char bitmap[8]. ``` typedef struct Memory { char bitmap[8]; char * memblock[64]; int i; //... }Memblock int somefunction(void) Memblock mem; ``` Then instead of using mem->bitmap[0] & 1 you need to use mem.bitmap[0] & 1 ,since mem is not a pointer to Memory.
I have created a (very simple) makefile: ``` DEBUG = -DDEBUG main: main.c add.c gcc $(DEBUG) main.c add.c -o main -lm ``` What I want (and don't understand how to do), is to create the makefile so that if the user printsmake debug, the code will compile with the debug option, but when printing onlymake, the debu...
You probably are looking for something like ``` main: main.c add.c gcc $(DEBUG) main.c add.c -o main -lm debug: DEBUG = -DDEBUG debug: main ```
I'm not sure why malloc is allocating so much space. Here's a snippet of the problem code: ``` char * hamming_string = NULL; void enter_params(){ printf("Enter the max length: "); scanf_s("%d", &max_length); hamming_string = (char *) malloc(max_length * sizeof(char)); // to test what's going on with the ha...
hamming_stringis not astringuntil one of its elements is a'\0'. Thestr*()functions can only be used on strings. Your program invokesUndefined Behaviour(by callingstrlen()with something that is not a string).
Why does this hang without first printing? ``` #include <stdio.h> void main() { printf("hello world"); while (1) {} } ```
Because you haven't flushed the standard output. Tryfflush. Even better, for C++ use... ``` std::cout << "hello world" << std::endl; ``` Separately, you'd have a better chance of it flushing itself if you added a\n, but not all implementations follow the Standard when it comes to such things.
``` struct { uint8_t foo; uint8_t bar; uint8_t baz; uint8_t foos[252]; uint8_t somethingOrOther; } A; struct { uint8_t foo; uint8_t bar; uint8_t baz; uint8_t somethingOrOther; uint8_t foos[252]; } B; ``` Does it matter that I've put foos on byte 3 in the first example, vs on b...
Given that the data type isuint8_t(equivalent tounsigned char), there is no need for padding in the structure, regardless of how it is ordered. So, you can reasonably assume in this case that every compiler will make that structure into 256 bytes, regardless of the order of the elements. If there were data elements ...
Since this is my first question after years of finding answers in this site, id like to say a big thanks to everyone. I want to useFANNin an embedded platform, and i am using UVision 4 to code in C. Since i am a C/C++ rookie, i cant figure out if i can / how i can use that library. When i try to simply include the fi...
You have to write your own "sys/time.h" for your embedded system. It must offer everything the original one does to be compatible with your external library. Wether you write one from scratch or wrap something around an existing code base which is compatible to your embedded device is up to you. You can also have a l...
I have a problem understanding how to access specified places in the char arrays in structs. ``` typedef struct Memory { char * bitmap[8]; char * memblock[64]; int i; //... }Memblock int somefunction(void) Memblock mem; ``` Lets say I've allocated the stuct, and now want to do the bitwise operation on bitmap:bitmap...
First of all fix char* bitmap[8] to char bitmap[8]. ``` typedef struct Memory { char bitmap[8]; char * memblock[64]; int i; //... }Memblock int somefunction(void) Memblock mem; ``` Then instead of using mem->bitmap[0] & 1 you need to use mem.bitmap[0] & 1 ,since mem is not a pointer to Memory.
I have created a (very simple) makefile: ``` DEBUG = -DDEBUG main: main.c add.c gcc $(DEBUG) main.c add.c -o main -lm ``` What I want (and don't understand how to do), is to create the makefile so that if the user printsmake debug, the code will compile with the debug option, but when printing onlymake, the debu...
You probably are looking for something like ``` main: main.c add.c gcc $(DEBUG) main.c add.c -o main -lm debug: DEBUG = -DDEBUG debug: main ```
I'm not sure why malloc is allocating so much space. Here's a snippet of the problem code: ``` char * hamming_string = NULL; void enter_params(){ printf("Enter the max length: "); scanf_s("%d", &max_length); hamming_string = (char *) malloc(max_length * sizeof(char)); // to test what's going on with the ha...
hamming_stringis not astringuntil one of its elements is a'\0'. Thestr*()functions can only be used on strings. Your program invokesUndefined Behaviour(by callingstrlen()with something that is not a string).
Why does this hang without first printing? ``` #include <stdio.h> void main() { printf("hello world"); while (1) {} } ```
Because you haven't flushed the standard output. Tryfflush. Even better, for C++ use... ``` std::cout << "hello world" << std::endl; ``` Separately, you'd have a better chance of it flushing itself if you added a\n, but not all implementations follow the Standard when it comes to such things.
``` struct { uint8_t foo; uint8_t bar; uint8_t baz; uint8_t foos[252]; uint8_t somethingOrOther; } A; struct { uint8_t foo; uint8_t bar; uint8_t baz; uint8_t somethingOrOther; uint8_t foos[252]; } B; ``` Does it matter that I've put foos on byte 3 in the first example, vs on b...
Given that the data type isuint8_t(equivalent tounsigned char), there is no need for padding in the structure, regardless of how it is ordered. So, you can reasonably assume in this case that every compiler will make that structure into 256 bytes, regardless of the order of the elements. If there were data elements ...
I'm not sure why malloc is allocating so much space. Here's a snippet of the problem code: ``` char * hamming_string = NULL; void enter_params(){ printf("Enter the max length: "); scanf_s("%d", &max_length); hamming_string = (char *) malloc(max_length * sizeof(char)); // to test what's going on with the ha...
hamming_stringis not astringuntil one of its elements is a'\0'. Thestr*()functions can only be used on strings. Your program invokesUndefined Behaviour(by callingstrlen()with something that is not a string).
Why does this hang without first printing? ``` #include <stdio.h> void main() { printf("hello world"); while (1) {} } ```
Because you haven't flushed the standard output. Tryfflush. Even better, for C++ use... ``` std::cout << "hello world" << std::endl; ``` Separately, you'd have a better chance of it flushing itself if you added a\n, but not all implementations follow the Standard when it comes to such things.
``` struct { uint8_t foo; uint8_t bar; uint8_t baz; uint8_t foos[252]; uint8_t somethingOrOther; } A; struct { uint8_t foo; uint8_t bar; uint8_t baz; uint8_t somethingOrOther; uint8_t foos[252]; } B; ``` Does it matter that I've put foos on byte 3 in the first example, vs on b...
Given that the data type isuint8_t(equivalent tounsigned char), there is no need for padding in the structure, regardless of how it is ordered. So, you can reasonably assume in this case that every compiler will make that structure into 256 bytes, regardless of the order of the elements. If there were data elements ...
I had an issue where my C program allocated input data correctly only for values less than 5. I found the error in the creation of the int array holding the values: I had used atoi(var-1) instead of atoi(var)-1. When var='5', atoi(var-1) is 0 when printed out. Why is the number "5" where the erroneous char to int c...
When you writeatoi(var - 1), wherevaris achar*, you are asking the functionatoito read the string which begins at the memory location one lower thanvarand convert that to an integer. In general, the character that is at the lower memory address could be anything. You just happened to have it break when yourchar*was'5...
When building R from source,http://cran.r-project.org/doc/manuals/r-release/R-admin.html#Other-Optionsdirects me to./configure --helpwhich lists 200 lines of flags I "might potentially" want to use: --enable-strict-barrier,--enable-lto,--with-lapack,--with-blas,--with-system-zlib,--with-system-tre,--with-internal-tzc...
Itisanswered in the manual, just in a different part of the manual (appendices). Linear algebra (BLAS, LAPACK, ATLAS) is documented inanother part of the R manual.Useful blog commentshereandhereregarding BLAS.zlib,pcre,xz,bzlibare discussed inanother part of the R manualgettextisthis
My question is is possible to pass array variable in robotc functions? Here is my attempt: ``` void writeToLog(char message) { printf("success"); } char h[10]=""; writeToLog(h) ``` N.B.ROBOTC is a robotics programming language that is a C-Based Programming Language.
I am not familiar with robotc. But in C, it is possible to pass array variable to functions. You have to change the writeToLog function definition to ``` void writeToLog(char *message) { ... } ```
I need to fill a byte array in c language by the possible enumerations. Here it is how I declare my byte array: ``` unsigned char byteArray[6]; ``` And now I hesitate if my enumrations should look likeMyEnum1orMyEnum2: ``` enum MyEnum1 { A1 = 0, B1 = 1, C1 = 2}; enum MyEnum2 { A2 = 0x00, B2 = 0x01, C2 = 0x02}; ```...
In your case no matter how you will organize yourenum. You can do it in both ways and the result will be the same.
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.Closed8 years ago.Improve this question I can't and string in c these strings . code ``` void main { char buffer[10]; int degrees=9; ...
Maybe you want this : ``` #include <stdio.h> void main() { char buffer[30]; // note it's 30 now, with 10 the buffer will overflow int degrees=9; sprintf(buffer, "turnAnticlockwise(%d)",degrees); printf("%s", buffer); } ``` This small program will output : ``` turnAnticlockwise(9) ```
``` typedef struct unit { struct unit * next; int year; int month; int day; struct unit revisions[3]; char subject[100]; }schedule; ``` The above code is giving me the following error: ``` array type has incomplete element type struct unit revisions[3]; ``` I'm guessing the problem is that a struct cannot contain...
your question contains the answer itself.struct unit * next; You can always use a pointer to the structure type inside the structure definition, and from your function, allocate memory and use it.
For instance if i had the following code ``` int f() { /*set struct value*/ struct test_2 t; t.j = 0; } ``` If i get an error such asstruct test_2not declared i was wondering which phase of the compilation detects this particular error? Also i was wondering which phase compilation would remove the comment from th...
It would depend on the compiler, but the most natural fits would be Lexical Analysis for the comments (since they're ignored by the rest of the process and are regular expressions), and Semantic Analysis for detecting that something hadn't been declared (since Parsing wouldn't keep a symbol table).
This is an extract from a header I found in a 3rd party library: ``` struct aiFileIO; struct aiFile; // aiFile write callback typedef size_t (*aiFileWrite) (struct aiFile*, const char*); // aiFileIO open callback typedef aiFile* (*aiFileOpen) (struct aiFileIO*, const char*); ``` Why does the last line not conta...
The only explanation I can think of is that the header was meant for C++, where you don'tneed totypedefstruct names. If the header is designed to be used from C, then that's a bug since the code won't build as C.
i have the following code: ``` #define NULL ((void*)0) void* Globalptr = NULL; void func(ptrtype* input) { ((ptrtype*)Globalptr) = input; } ``` I get Error on line((ptrtype*)Globalptr) = input;says " expression must be a modifiable lvalue"
You must make the data to match the variable (lvalue), and not change the type of the variable to match the data: ``` Globalptr = (void*)input; ``` But since you can convert any data pointer tovoid*in C, you can simply do: ``` Globalptr = input; ```
I am trying to build a sample code using Eclipse and ARM Sourcery Windows GCC C on Windows 8 machine. When I compile code : I get this error : Undefined reference to symbol 'sem_post@@GLIBC_2.4 The error doesn't say any line number or any location about the error, so I don't know which part of the code I should po...
sem_post()lives in the pthread library, so make sure you use the-pthreadflag when compiling and linking.
I'm attempting to take user input and pass that as the filename toexecve(). I usemalloc()to allocate enough memory forchar* filenamebefore I fill it with the path to the file I want executed. execve(), however, requires aconst char*, so it won't compile. Is there any way to bypass this? I've seen some people useexec...
What you are saying about "it won't compile sinceexecve()requires aconst char*" is nonsense. You can always pass a non-const variable to a const method parameter. So your problem should be somewhere else. Please post more code.
So lets say I have a character array calledstrof size 12, and I input 1000110 in the array, with str[0] = 1, str[1] = 0 etc... I tested the array by printing it in a for loop, it works. I then want to count how many integers are initiated in the array. In this case, the value should be: 7 Here is my code, for whatev...
You have a string that consists of characters. You need to compare against the character value: ``` if ( str[i] == '0' || str[i] == '1' ) ```
I have a matrix (5x5) of boolean values: ``` matrix = [[False for x in range(5)] for x in range(5)] matrix[0][3] = True matrix[2][2] = True F F F T F F X F F F F F T F F F F F F F F F F F F ``` Given an index, I need to find the closer cell which value is True. Where closer means: the cell that can be reached with ...
BFS- search the immediate neighbors, then the immediate neighbors of each of your immediate neighbors and so on... at each such step you'll be searching cells that are one step further than those of the previous step. also, keep track of which cells were already checked so you don't repeat them
Suppose i have a linked list node with a head pointer and i passed head to some other function like test(node *np) what happens if i free np inside this function test with head might or might not be pointing to the node?
According to the C standard usingfreewith improper pointer is undefined behavior: 7.22.3.3 Thefreefunction....Thefreefunction causes the space pointed to byptrto be deallocated, that is, made available for further allocation. Ifptris a null pointer, no action occurs. Otherwise, if the argument does not match a po...
I'v been use some module manager like npm for node.js or apt-get in ubuntu, I find it's really easy to build more. And I just want to know is there a cpm for module manage in c programming?
clibmay be the answer.https://github.com/clibs/clibit is proposed to offer some stand-alone "micro c libraries".
Given Bison Specification: %right TOK_ADD TOK_MUL I was wondering what would be the precedence order of TOK_ADD and TOK_MUL. Also in case i had Bison specification ``` %left TOKMUL TOKADD %left TOKDIV %left TOKSUB ``` I was wondering what would the precedence order of TOKMUL TOKADD TOKDIV and TOKSUB be
bison/yacc precedence order is lowest to highest -- the tokens on the first line listed have the lowest precedence while those on the last have the highest. Multiple tokens on the same line (TOKMULandTOKADDin your case) have the same precedence
I need to write a simple program in C which will print theUUIDof/dev/sda1. It does not have take any parameters (/dev/sda1can be hardcoded) I have no idea how this can be done in C, but hopefully this could be done in few lines of code. Could somebody please point me to the right direction, or perhaps sketch some co...
ERROR: type should be string, got "\nhttps://github.com/karelzak/util-linux/blob/master/misc-utils/blkid.cline 211\n\n```\n/* Get the uuid, label, type */\n iter = blkid_tag_iterate_begin(dev);\n while (blkid_tag_next(iter, &type, &value) == 0) {\n if (!strcmp(type, \"UUID\"))\n uuid = value;\n }\n blkid_tag_iterate_end(iter);\n```\n"
I'm attempting to take user input and pass that as the filename toexecve(). I usemalloc()to allocate enough memory forchar* filenamebefore I fill it with the path to the file I want executed. execve(), however, requires aconst char*, so it won't compile. Is there any way to bypass this? I've seen some people useexec...
What you are saying about "it won't compile sinceexecve()requires aconst char*" is nonsense. You can always pass a non-const variable to a const method parameter. So your problem should be somewhere else. Please post more code.
So lets say I have a character array calledstrof size 12, and I input 1000110 in the array, with str[0] = 1, str[1] = 0 etc... I tested the array by printing it in a for loop, it works. I then want to count how many integers are initiated in the array. In this case, the value should be: 7 Here is my code, for whatev...
You have a string that consists of characters. You need to compare against the character value: ``` if ( str[i] == '0' || str[i] == '1' ) ```
I have a matrix (5x5) of boolean values: ``` matrix = [[False for x in range(5)] for x in range(5)] matrix[0][3] = True matrix[2][2] = True F F F T F F X F F F F F T F F F F F F F F F F F F ``` Given an index, I need to find the closer cell which value is True. Where closer means: the cell that can be reached with ...
BFS- search the immediate neighbors, then the immediate neighbors of each of your immediate neighbors and so on... at each such step you'll be searching cells that are one step further than those of the previous step. also, keep track of which cells were already checked so you don't repeat them
Suppose i have a linked list node with a head pointer and i passed head to some other function like test(node *np) what happens if i free np inside this function test with head might or might not be pointing to the node?
According to the C standard usingfreewith improper pointer is undefined behavior: 7.22.3.3 Thefreefunction....Thefreefunction causes the space pointed to byptrto be deallocated, that is, made available for further allocation. Ifptris a null pointer, no action occurs. Otherwise, if the argument does not match a po...
Beginner at C here. I've tried searching for this kind of problem, but to no avail, I haven't found anything regarding this problem. So as the title says, I need to change the string with 'x' but my output looks like this: ``` Your SSID is: x Your SSID is: x Your SSID is: x... ``` (repeats until how many characters ...
Would work: ``` printf("Your SSID is:"); for(i=0;id[i] != '\0';i++) { printf("%c", 'x'); } printf("\n") ; ```
This question already has answers here:Segmentation fault on large array sizes(7 answers)Closed8 years ago. I have a C++ object in some part of my code like this: ``` class Object { public : float a, b, c; } ``` When I create a 2 dimensional array like this, it works fine : ``` Object myArray [500][500]; ``` Wh...
To create a huge array, you need to make it global. Local variables have a size limit. Another solution is to allocate the array dynamically.
I tried the following: ``` #include <stdio.h> int main(void) { signed int a = 5; unsigned int b = -5; printf("%d\n", a); printf("%d\n", b); return 0; } ``` and I get: ``` 5 -5 ``` So I don't understand whysignedandunsigneddon't work, should I get an error?
You have to use correct format specifiers that to get the correct result using function printf. Write ``` printf("%d\n", a); printf("%u\n", b); ``` The function simply interpretates internal representations of data according to the format specifiers.
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.Closed8 years ago.Improve...
The *a = *b, means that the content that is stored in the memory assinged to pointer b is going to be the content of pointer a.
in.h: ``` typedef struct token_t TOKEN; ``` in.c: ``` #include "token.h" struct token_t { char* start; int length; int type; }; ``` inmain.c: ``` #include "token.h" int main () { TOKEN* tokens; // here: ok TOKEN token; // here: Error: incomplete type is not allowed // ... } ``` The er...
You need to move the definition of thestructinto the header file: ``` /* token.h */ struct token_t { char* start; int length; int type; }; ```
I have written RSA using GMP packages. While taking plain text I've taken it as string usingscanf("%s",name);and then converted into gmp type. After running my program for 50 times,which was successfully executed, the scanf function haven't worked. So, I've read the input usingfgets (name, 100, stdin);andscanf ("%[^\n...
``` scanf("%s",name); ``` Will scan user input until it encounters a space,i.e, when you typehi bye, onlyhiwill be stored inname.On the other hand, ``` scanf ("%[^\n]%*c", name); ``` Will scan until it encounters a\nor an enter key. The%*ctellsscanfto scan a character and discard it. In your case,%*cdiscards the\nc...
Say I have a const char* string like this: ``` ../products/product_code1233213/image.jpg ``` I want to retrieve the second last part of this path string, which is the parent folder name of the jpg file, how would I do that?
You can usestrtok. ``` #include <string.h> #include <stdio.h> int main() { char str[] = "/products/product_code1233213/image.jpg"; char s[2] = "/"; char *token; /* get the first token */ token = strtok(str, s); /* walk through other tokens */ while( token != NULL ) { printf( " %s\n",...
From the 21st century C book: Static variables, even those inside of a function, are initialized when the program starts, before main, so you can’t initialize them with a nonconstant value.//this fails: can't call gsl_vector_alloc() before main() starts static gsl_vector *scratch = gsl_vector_alloc(20); Why can'...
What you quoted from the book is the answer, i.e. because it wouldn't be compliant to the C standard. ``` All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals. ``` Although I believe something like this is possible in C++ under certain...
Recently I started learningCby myself, so might be a bit newbie question. I have compiled the following commands: ``` #include <stdio.h> int main() { int arr[5]={0}; int arr2[5]={0}; printf("%d\n",arr[5]); //here output: 2130567168 printf("%d\n",arr2[5]); //here output: 0 return 0; } ``` can anybody expla...
Bothprintfs produce undefined behavior, because they are accessing elements past the end of their corresponding arrays. The valid range for indexes of C arrays is zero throughlength-1, so for both arrays in your program that would be 0..4, inclusive. Accessing element at index 5 is past the end of the array, so diffe...
I am learning C and have a question about structs. I have a ``` struct myStruct { char member1[16]; char member2[10]; char member3[4]; }; ``` This should take at least 30 bytes of memory to store. Would it be possible to copy all of this data into the variablechar foo[30]? What would be the syntax?
You can't just directly copy the whole thing, because the compiler may arbitrarily decide how to pad/pack this structure. You'll need threememcpycalls: ``` struct myStruct s; // initialize s memcpy(foo, s.member1, sizeof s.member1); memcpy(foo + sizeof s.member1, ...
I can't belive what's happen in my program ``` double den = 180*3600*10000 ; ``` in debugging a got this value -2109934592.0000000 any help please ??? you can try this simple code ``` #include<stdio.h> #include<math.h> int main ( int argc , char *argv ) { double denominator = 10000*180*3600 ; printf("%f \n", d...
With the full code in the question we can now see it's an integer overflow. ``` 10000 * 180 * 3600 = 6,480,000,000. ``` This is greater than 2,147,483,648 which is the max value of a 32-bit signed int. The results of the multiplication overflows to -2,109,934,592 and is then converted to double. To get the right r...
I want to know what a "const" keyword before a function in 'C' does. For example: ``` extern const int func1(int x[], const struct dummy_s* dummy) ``` Thanks in advance
If you turn on warnings you will have two: ``` warning: type specifier missing, defaults to 'int' [-Wimplicit-int] warning: 'const' type qualifier on return type has no effect [-Wignored-qualifiers] ``` which easily allows you to conclude that this: ``` extern const func1(int x[], const struct dummy_s* dummy) ``` ...
I have to modify .c program, but i have very limited knowledge of c programming. How can i change input string '3.10.2014' to output string '2014-10-03' ? ``` char *in = '3.10.2014' char *out = something(*in) ``` thank you
First change the call to: ``` char date[] = "3.10.2014"; change_date(date); ``` This makesdateinto an array which you can actually modify, as opposed to a string literal which you cannot. Then writechange_date(), using e.g.sscanf()andsprintf(): ``` void change_date(char *s) { int y, m, d; if(sscanf(s, "%d.%d....
Consider the following code i managed to write: ``` #include <stdio.h> #define FOR(A, B, C) for(A; B; C++) int main() { FOR(i=0, i<10, i) printf("%i", i); return 1; } ``` The output is:0123456789 If i doFOR(i=5, i<10, i)then respectively the output is56789 My questions are is that legal? Will it caus...
Yes it's a "legal" macro, but no, it does not work like a realforloop. Your macro won't handle this: ``` int a, b; for(a = 0, b = 4711; a < b; ++a); ``` for instance, since you can't distinguish the,used to build a longer initializing expression to the one used to separate the expressions that make up the parts: `...
I'm trying to read from/proc/<PID>/mapsfile. Iptrace(PTRACE_ATTACH, <PID>)before reading (so, the process is supposed to be suspended). The code that reads looks like this: ``` while(fgets(line_buf, BUFSIZ, maps_fd) != NULL){ ... } ``` but it's not ending (infinite loop). I did aprintf line_bufand in turns out fget...
I can't find the reference right now, but this was a known bug/regression in certain kernel versions. The problem is almost surely that you're running on a buggy kernel and need to replace it with a less-buggy one. If I can find a link to the issue report I'll add it.
After converting a file with doubles to floats the compiler (MSCV2005) warns about conversions fromdoubletofloatfor in code constants like ``` ... float r; r = (q1 + q2) * 0.5; ... ``` Evenq1, q2are both floats0.5seems to be treated asdouble. How to adapt this behavious, so that all in-code constants are treated a...
Use anfsuffix to indicate that the constant is to have typefloat: ``` float q1 = ...; float q2 = ...; float r = (q1 + q2) * 0.5f; ``` The standard (§6.4.4.2 Floating constants) says: An unsuffixed floating constant has typedouble. If suffixed by the letterforF, it has typefloat. If suffixed by the letterlorL, it ...
This question already has answers here:changing pointers in functions, c(4 answers)Closed8 years ago. I have a program, which has a node called head. I want to set head to NULL, however I want to do it inside a void. So I pass the head node to the method: ``` void removeNode(node* head) { head = NULL; } ``` However...
You will want to do this instead: ``` void removeNode(node** head) { (*head) = NULL; } ``` This changes the actual pointer toNULL, so that it no longer points to anything.
Is there's a function that can draw text and fit it inside a rectangle (the function will make the size of the text smaller as appropriate to make it fit or something). I checked the parameters forDrawText()but I don't think it supports such a feature.
Maybe you can use GetTextMetrics to check if the text fits inside the rectangle, and if it doesn't, reduce the current font size and repeat the measurement. GetTextMetrics: http://msdn.microsoft.com/en-us/library/windows/desktop/dd144941%28v=vs.85%29.aspx
I have a hierarchy like this in my project Libraryxfolderx.hx.cyfoldery.hy.csamplesampleTestsFrameworksProducts I added a $(SRCROOT)/Library in my Header search paths so i can call my headers inside the library folder. My question is do i still add a directory for it? like if x.c wants to include y.h do i place #inc...
I can think of the following ways of#includeingy.hinx.c. Use path relative to$(SRCROOT)/Library#include <yfolder/y.h>Use path relative tox.c#include "../yfolder/y.h"
During clean compile warning, I met following code: ``` char *strcpy(char *dest, char *src) { unsigned int i; while( dest[i] = src[i] )//assignment in condition i++; return dest; } ``` the base function of the code should be OK, but compiler warn that theassignment in condition, does this part ...
All kinds of warnings need to be cleaned. This warning was introduced because=and==is often confused by programmers (hello, Pascal!), and your intent may be explicitly stated by adding parentheses around assignment expression: ``` if ((x = y)) // no warning ```
I am new in c programming, and I am trying to understand thesizeoffunction. Please help me understand how this program works: ``` #include<stdio.h> main( ) { printf ( "\n%d %d %d", sizeof ( '3'), sizeof ( "3" ), sizeof ( 3 ) ) ; } ``` I am getting output as4 2 4. However, I am not able to understand the reason...
sizeof ( '3'), it is the size ofcharacter constantwhich isintso you are getting value as4on your machine.sizeof ( "3" ), it is size of string i.e.2.String"3"is made of 2 character('3'+'\0')="3". And we knowsizeof(char)is 1.sizeof ( 3 ), it is size ofintwhich is4on your machine.
I'm trying to ready a set of values from a .txt and store them into an array in C. I've got it working but for some reason it's only getting every other value, seemingly only the even-indexed values I guess. ``` for (k=0,total=0; fscanf(lab,"%lf",&y[k]) != EOF && k<=N-1;total++, k++) { fscanf(lab,"%lf",&y...
You are calling fscanf twice per iteration. Once in the test fscanf (...) != EOF, then inside the loop.
Yay. Segmentation fault. However, I've narrowed it done to the exact line which is causing the segmentation fault. Here are the relevant chunks of code: So here is a struct I've defined. ``` typedef struct { int placeID; char *city; char *continent; char *cultural; char *outdoors; int dist_f...
You need to allocate memory to the struct pointer first: ``` place_t *temp_place=malloc(sizeof(struct place_t)); //allocate memory first temp_place->placeID=tmp; //assign values ```
This question already has answers here:My program skip getting input data? [duplicate](7 answers)Closed8 years ago. I am having problem scanning char variable , my code is ``` #include <stdio.h> #include <conio.h> void main() { clrscr(); int a; float b; char c; printf("Enter value for int variable \n"); scanf("%d...
because of the storedenterkey press [considered as character input]. use onegetch();before the thirdscanf(). alternatively, use(scanf(" %c",&c);)[mind the space before%c] which will get rid of any number of whitespace [buffered] character present before actual input.
This question already has answers here:My program skip getting input data? [duplicate](7 answers)Closed8 years ago. I am having problem scanning char variable , my code is ``` #include <stdio.h> #include <conio.h> void main() { clrscr(); int a; float b; char c; printf("Enter value for int variable \n"); scanf("%d...
because of the storedenterkey press [considered as character input]. use onegetch();before the thirdscanf(). alternatively, use(scanf(" %c",&c);)[mind the space before%c] which will get rid of any number of whitespace [buffered] character present before actual input.
``` #include <stdio.h> #include <stdlib.h> void main () { system("dir"); } ``` I have read in many C++ books wheresystem()is used to execute command line programs. But when I tried the same command in C, it worked perfectly. So my question is whether its a standard C or C++ function? Please be liberal as I am new ...
As system function is declared in stdlib.h, it can be considered a C function. But in C++, stdlib.h is merged into the std namespace and is located in the cstdlib include in this form. So the correct answer is "both".
Is there an option that I can use to separate parts of my GUI with lines in Glade 3? I want some widgets to be separated from the others; for example I would like to put them in a box.
Use GtkSeparator; its icon is the vertical line in the Control and Display section of the tool palette.
I developed a program in which I use a http client with libcurl. I want to find out the source tcp port used by libcurl in a tcp session. How can I do that ?
curl_easy_getinfowith theCURLINFO_LOCALPORToption!