question
stringlengths
25
894
answer
stringlengths
4
863
I'm creating a shared (.DLL) library and I keep getting this message from the compiler (gcc): ``` json.c:1:0: warning: -fPIC ignored for target (all code is position independent) ``` What does it mean that all code is position independent? How a position dependent code looks like?
What does it mean that all code is position independent? It means that on your platform,allcode is compiledas if-fPICis on command line, whether you specify it or not (and the flag is therefore redundant). You can safely ignore that warning.
I'm creating a shared (.DLL) library and I keep getting this message from the compiler (gcc): ``` json.c:1:0: warning: -fPIC ignored for target (all code is position independent) ``` What does it mean that all code is position independent? How a position dependent code looks like?
What does it mean that all code is position independent? It means that on your platform,allcode is compiledas if-fPICis on command line, whether you specify it or not (and the flag is therefore redundant). You can safely ignore that warning.
The question is more specifically this one: How many bit-field entries can I add in a structure? For example: ``` struct SMyStruct { unsigned int m_data1 : 3; unsigned int m_data2 : 1; unsigned int m_data3 : 7; // ... unsigned long long m_datan : 42; }; ``` May the total of bits exceed 32 or 64 (or w...
It's not limited, what is important is that the number of bit-fields can not be grater than the number of bit's of the data type, for example: ``` typedef struct _Structure { int field1:32; // OK int field2:40; // Error, int is 32 bit size char field3:4; // OK char field4:9; // Error, char is 8 bit size }...
Find the time complexity of following code. Answer given is O(log(n)*n^1/2), but I am not getting it. I want someone to explain this. ``` i=n; while(i>0) { k=1; for(j=1;j<=n;j+=k) k++; i=i/2; } ```
Take this code segment: ``` k=1; for(j=1;j<=n;j+=k) k++; ``` The values ofjover various iterations will be1, 3, 6, 10, 15, 21, 28, .... Note that these numbers have closed form(m+1)(m+2)/2, wheremis the number of iterations that have gone by. If we want to know how many iterations this loop will run for, we need ...
I've looked at several examples and none quite match my problem. I'm trying to define an array of struct, no biggie, but when I do this in Xcode using pure C, I get a "Expected Expression" error that's driving me nuts. The Code is as follows: ``` struct myType { unsigned char varName1; unsigned char varName2...
``` myArray[0] = (struct myType) {1,2,3}; ```
I am trying to trim the end of a ANSI C string but it keeps seg faulting on thetrimfunction. ``` #include <stdio.h> #include <string.h> void trim (char *s) { int i; while (isspace (*s)) s++; // skip left side white spaces for (i = strlen (s) - 1; (isspace (s[i])); i--) ; // skip right side white spa...
Thetrimfunction is fine, there are two errors inmain: 1.stris a string literal, which should be modified. 2. The call toprintfis wrong, becausetrimdoesn't return anything. ``` int main(void) { char str[] = "Hello World "; trim(str); printf("%s\n", str); } ```
This question already has answers here:self referential struct definition?(9 answers)Closed9 years ago. Please help me to figure out a very basic confusion as follows, ``` struct node { struct node *next; // no compile error } ``` is ok, but the following gives an compile error(unknown type). I know it is ...
C allows you to have pointers to incomplete types. struct node *nextis a forward reference to struct node, but since you're only declaring a pointer to that type, the compiler doesn't mind. This is explicitly allowed, and it enables building structures that refer to each other. You don't need a complete type to decl...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in thehelp center.Closed9 years ago.Improve this question I want to write a program that calculates if a number is a multiple of some other ...
For generating all possibilities, a Brute force algorithm will suffice: Loop over all possible values foraand subtract the sum2afrom 25. Nest similar loops forbusing the remainder. If the remainder after subtracting3bis a multiple of 4, then loop over all possible values ofcand outputa,b, andcas a combination.
I have a strange question, I am wondering if there is a way to add/edit a string (or something that could be accessed via the C program (inside, ie not an external file)) after it has been compiled? The purpose is to change a URL on an Windows program via PHP on Linux (obviously I cannot just compile it).
Many posix platforms come with the programstringswhich will read through a binary file searching for strings. There is an option to print out the offset of the strings. For example: ``` strings -td myexec ``` From there you can use a hex editor but the main problem is that you wouldn't be able to make a stringbigg...
I am running an epoll loop and sometimes my call to epoll_wait returns -1 with errno set to EINTR. Sometimes, I want this to end the epoll loop, like in the case of SIGTERM or SIGINT. But I have this code compiled with the -pg flag, so periodic SIGPROF (27) signals are raised that stop my loop. So... is it possible t...
Add signal handlers on SIGTERM and SIGINT. Inside those handlers you set a variable that you check in your main epoll loop
After execution, result was very strange: ``` #include <stdio.h> int main(){ int a,b; printf("enter two numbers :"); scanf("%d%d",&a,&b); if(a>b){ printf("maximum number is %d",&a); } else{ printf("maximum number is %d",&b); } return 0; } ``` After enter two numbers in console result was...
You are trying to print the address ofintnot its value. Do this: ``` if(a>b){ printf("maximum number is %d",a); } else{ printf("maximum number is %d",b); } ``` &operator returns the address ofaorb.
This is a simple code to store a person's name and number in a file.the problem occurs when i also want to include the person's contact number.the error occurs after the contact number is scanned. ``` #include <stdio.h> #include <stdlib.h> main() { FILE *fp;//file pointer char *name,*number; char filename[]="testfile...
you did not malloc() the memory for name and number!
I have to implement a calculator in C. It gets 3 arguments (int, char, int) where char can be +, -, x or /. I must implement the calculator with a jump table which points to the 4 corresponding functions (e.g. plus(int x, int y)). I know how to access the functions in the jump table but I must not use a switch stateme...
Look at thestrchr()function. ``` // Call with oper = '+', '-', 'x' or '/'. unsigned int op_to_index(char ch) { const char *ops = "+-x/"; return strchr(ops, op) - ops; } ```
Below is the prototype of an ioctl call ``` long ioctl(struct file *f, unsigned int cmd, unsigned long arg); ``` Why third argument of an ioctl is unsigned long by default? Some times we pass a pointer to it. But it is using unsigned long.
In kernelunsigned longis often used as a substitution for pointers, for pointers always have this size on every architecture.Ioctlsmay take an integer as an argument as well, so this makes sense here. This must be defined for eachioctl. Please mind, that ioctls are deprecated andunlocked_ioctlsmust be used in current...
I have an NSData packet with data in it. I need to convert the byte at range 8, 1 to an int. To get the data at that location I do the following. ``` NSData *byte = [packet subdataWithRange:NSMakeRange(8, 1)]; ``` If I NSLog byte ``` <01> ``` How do I think convert this to an int? This is probably the most basic o...
use-[NSData bytes]to get raw buffer and read from it ``` int i = *((char *)[byte bytes]) ``` or use-[NSData getBytes:length:] ``` char buff; [bytes getBytes:&buff length:1]; int i = buff; ``` make sure you are reading fromchar *notint *, otherwise you are accessing invalid memory location, which may or may not cra...
What does theENTmean inENOENT? Shouldn't the error: No such file or directory just be named byENOFILE? Is there any story or reason?
It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories. It's abbreviated because C compilers at the dawn of time didn't support more than 8 characters in symbols.
I am running an epoll loop and sometimes my call to epoll_wait returns -1 with errno set to EINTR. Sometimes, I want this to end the epoll loop, like in the case of SIGTERM or SIGINT. But I have this code compiled with the -pg flag, so periodic SIGPROF (27) signals are raised that stop my loop. So... is it possible t...
Add signal handlers on SIGTERM and SIGINT. Inside those handlers you set a variable that you check in your main epoll loop
After execution, result was very strange: ``` #include <stdio.h> int main(){ int a,b; printf("enter two numbers :"); scanf("%d%d",&a,&b); if(a>b){ printf("maximum number is %d",&a); } else{ printf("maximum number is %d",&b); } return 0; } ``` After enter two numbers in console result was...
You are trying to print the address ofintnot its value. Do this: ``` if(a>b){ printf("maximum number is %d",a); } else{ printf("maximum number is %d",b); } ``` &operator returns the address ofaorb.
This is a simple code to store a person's name and number in a file.the problem occurs when i also want to include the person's contact number.the error occurs after the contact number is scanned. ``` #include <stdio.h> #include <stdlib.h> main() { FILE *fp;//file pointer char *name,*number; char filename[]="testfile...
you did not malloc() the memory for name and number!
I have to implement a calculator in C. It gets 3 arguments (int, char, int) where char can be +, -, x or /. I must implement the calculator with a jump table which points to the 4 corresponding functions (e.g. plus(int x, int y)). I know how to access the functions in the jump table but I must not use a switch stateme...
Look at thestrchr()function. ``` // Call with oper = '+', '-', 'x' or '/'. unsigned int op_to_index(char ch) { const char *ops = "+-x/"; return strchr(ops, op) - ops; } ```
Below is the prototype of an ioctl call ``` long ioctl(struct file *f, unsigned int cmd, unsigned long arg); ``` Why third argument of an ioctl is unsigned long by default? Some times we pass a pointer to it. But it is using unsigned long.
In kernelunsigned longis often used as a substitution for pointers, for pointers always have this size on every architecture.Ioctlsmay take an integer as an argument as well, so this makes sense here. This must be defined for eachioctl. Please mind, that ioctls are deprecated andunlocked_ioctlsmust be used in current...
I have an NSData packet with data in it. I need to convert the byte at range 8, 1 to an int. To get the data at that location I do the following. ``` NSData *byte = [packet subdataWithRange:NSMakeRange(8, 1)]; ``` If I NSLog byte ``` <01> ``` How do I think convert this to an int? This is probably the most basic o...
use-[NSData bytes]to get raw buffer and read from it ``` int i = *((char *)[byte bytes]) ``` or use-[NSData getBytes:length:] ``` char buff; [bytes getBytes:&buff length:1]; int i = buff; ``` make sure you are reading fromchar *notint *, otherwise you are accessing invalid memory location, which may or may not cra...
What does theENTmean inENOENT? Shouldn't the error: No such file or directory just be named byENOFILE? Is there any story or reason?
It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories. It's abbreviated because C compilers at the dawn of time didn't support more than 8 characters in symbols.
Imagine i have the following piece of C-code where foo() produces a side effect and returns an integer: ``` if(bar) { foo(); return 0; } ``` Now, say I really like making my code compact, possibly at the reader's expense, and I change it into this: ``` if (bar) return foo() && 0; ``` Can I be sure thes...
Yes, those two are the same.foo()will always be called (assumingbaris true).
So the linux.words file is a\nseparated list of words. I've tried to access it with fopen as follows: ``` { FILE* words; words = fopen("~/usr/share/dict/words", "r"); char* dictionary[10]; if (words != NULL) { for (int i = 0; i < 10; i++) { fscanf(words, "%s", dictiona...
You are not allocating the space for the words that you are reading from the file. ``` char* dictionary[10]; ... // for each word dictionary[i]= malloc(WORD_SIZE); ... ```
Following assert doesn't fails, though it should fail according to my understanding. Please correct me. ``` #include <stdio.h> #include <assert.h> void custom_free(int **temp){ free(*temp); } int main(){ int *ptr = malloc(1024); custom_free(&ptr); assert(ptr); // doesn't fails ..why? } ```
Callingfreedoesn't change the value of a pointer. If you want toNULLfreed memory you'll have to do it yourself ``` void custom_free(int **temp){ free(*temp); *temp = NULL; } ```
I have the following example code: ``` void doAlloc(int **p) { *p = (int *)malloc(sizeof(int)); **p = 80; } int main() { int *ptr2; doAlloc(&ptr2); printf("%d\n", *ptr2); free(ptr2); } ``` If I understand correctly,ptr2is a pointer variable, and&ptr2is "address of" that pointer variable in memory. My q...
Very simply, if you have ``` int a; ``` then ``` &a ``` Is of typeint* In your case, you have to consider an extra pointer for all your occurrences.
I am running across a problem with typedefs. ``` typedef char cool_array_t[ARRAY_SIZE]; cool_array_t* out; // do stuff with out cool_array_t test = *out; ``` The error I am getting is the following: incompatible types when assigning to type ‘cool_array_t’ from type ‘char *’ I tried casting out to cool_array_t b...
You cannot assign to arrays. You need to usememcpyor a wrappingstruct. ``` struct cool_array_t { char data[ARRAY_SIZE]; }; struct cool_array_t* out; // do stuff with out struct cool_array_t test = *out; ```
i have such input stringA,B: A ' B * A B ' * + i'm trying to divide it usingstrtokhere is my code and output ``` int main(int argc, char **argv) { char *vars; char *formula; vars = strtok(argv[1],":"); formula = strtok(NULL,":"); printf("%s %s\n", vars,formula); } A,B <null> ``` why, when i'm ...
Most probablyargv[1]contains onlyA,B:, because shell encounters whitespaces as separators of command-line arguments. To have the whole sequence inargv[1], you need to use quotes, i.e.: ``` ./myprogram "A,B: A ' B * A B ' * +" ``` Try printing outargv[1]to make sure you get correct arguments.
My code: ``` char function [100]; switch (function [i]) { case '+' : { } break; case '*': { }break; case '\'' :{ }break; default: { printf ("argument %c not recognized \n", function [i]); return 1; } } return 0; ``` I'm executing program...
You are missing a break ``` case '\'': { if (wskaznikStosu < 1) { printf ("\nZa dużo operandów \n"); return 1;} else { int a = stos [wskaznikStosu - 1]; wskaznikStosu --; stos [wskaznikStosu] = not (a); wskaznikStosu ++; } } // YOU ARE MISSING A BREAK ...
I almost only find C++ posts and not C, when I try to find an answer for this. For built in types as int, char etc. is there any performance difference between pass-by-value and by const pointers? Is it still good programming practice to use the const keyword when passing-by-value? ``` int PassByValue(int value) { ...
Pass by const pointer is never faster than by value as long as the value is less or equal the size of a pointer (sizeof). It also is more annoying and sometimes even wrong (stack variables).
This might be a simple question, but I want to make sure. I want some comments in my .c files to use symbols not supported in the default encoding. If I save the file as UTF-8 for instance, and I only use symbols in comments, is there any way this can affect the compiler in any way? Need to be sure of this.
No, the preprocessor will strip all of that out anyway.
I am tring to convert a string into a floating-point value. Take a look at my small program: ``` #include <stdio.h> int main() { char string[3] = "42"; double value = atof(string); printf("Floating-point value: %f\n", value); return 0; } ``` When I run it, I get this: ``` Floating-p...
``` char string[2] = "42"; ``` should be ``` char string[3] = "42"; ``` the size of"42"array is 3 bytes as you have to count the trailing null character. If you want usechar string[2]for the declaration, yourstringwill not be null terminated. Then you alsohave toincludestdlib.hfile foratofdeclaration: ``` #incude...
Quick question about the order in which functions are executed. My code looks like the following: ``` int values() { 'code' motors(); } int motors() { 'code' values(); } int main() { values(); } ``` After it reads main() and runs values(), it's not aware of motors() so it doesn't run it (I think). I can't put it b...
You can just provide the declarations, and define the functions afterwards. ``` //declarations int values(); int motors(); //definitions int main() { values(); } int values() { motors(); } int motors() { values(); } ```
What does it mean to define an array with enum variable as array size? For example I have the following code: ``` typedef enum { D_ROM_RDE_GROUP_0 = 0x0, D_ROM_RDE_GROUP_1, D_ROM_RDE_MAX_GROUPS }E_ROM_RDE_GROUPS; U_08 pPlaneCopy[D_ROM_RDE_MAX_GROUPS]; ``` I don't understand it... Thanks for the help.
The first thing to remember is that enumeration values are compile-time constant. The other thing is that enumeration values (unless initialized to a specific value) increases. So in your caseD_ROM_RDE_GROUP_0is equal to0,D_ROM_RDE_GROUP_1is equal to1andD_ROM_RDE_MAX_GROUPSis equal to2. This means that when you decla...
So the linux.words file is a\nseparated list of words. I've tried to access it with fopen as follows: ``` { FILE* words; words = fopen("~/usr/share/dict/words", "r"); char* dictionary[10]; if (words != NULL) { for (int i = 0; i < 10; i++) { fscanf(words, "%s", dictiona...
You are not allocating the space for the words that you are reading from the file. ``` char* dictionary[10]; ... // for each word dictionary[i]= malloc(WORD_SIZE); ... ```
Following assert doesn't fails, though it should fail according to my understanding. Please correct me. ``` #include <stdio.h> #include <assert.h> void custom_free(int **temp){ free(*temp); } int main(){ int *ptr = malloc(1024); custom_free(&ptr); assert(ptr); // doesn't fails ..why? } ```
Callingfreedoesn't change the value of a pointer. If you want toNULLfreed memory you'll have to do it yourself ``` void custom_free(int **temp){ free(*temp); *temp = NULL; } ```
I have the following example code: ``` void doAlloc(int **p) { *p = (int *)malloc(sizeof(int)); **p = 80; } int main() { int *ptr2; doAlloc(&ptr2); printf("%d\n", *ptr2); free(ptr2); } ``` If I understand correctly,ptr2is a pointer variable, and&ptr2is "address of" that pointer variable in memory. My q...
Very simply, if you have ``` int a; ``` then ``` &a ``` Is of typeint* In your case, you have to consider an extra pointer for all your occurrences.
I am running across a problem with typedefs. ``` typedef char cool_array_t[ARRAY_SIZE]; cool_array_t* out; // do stuff with out cool_array_t test = *out; ``` The error I am getting is the following: incompatible types when assigning to type ‘cool_array_t’ from type ‘char *’ I tried casting out to cool_array_t b...
You cannot assign to arrays. You need to usememcpyor a wrappingstruct. ``` struct cool_array_t { char data[ARRAY_SIZE]; }; struct cool_array_t* out; // do stuff with out struct cool_array_t test = *out; ```
i have such input stringA,B: A ' B * A B ' * + i'm trying to divide it usingstrtokhere is my code and output ``` int main(int argc, char **argv) { char *vars; char *formula; vars = strtok(argv[1],":"); formula = strtok(NULL,":"); printf("%s %s\n", vars,formula); } A,B <null> ``` why, when i'm ...
Most probablyargv[1]contains onlyA,B:, because shell encounters whitespaces as separators of command-line arguments. To have the whole sequence inargv[1], you need to use quotes, i.e.: ``` ./myprogram "A,B: A ' B * A B ' * +" ``` Try printing outargv[1]to make sure you get correct arguments.
My code: ``` char function [100]; switch (function [i]) { case '+' : { } break; case '*': { }break; case '\'' :{ }break; default: { printf ("argument %c not recognized \n", function [i]); return 1; } } return 0; ``` I'm executing program...
You are missing a break ``` case '\'': { if (wskaznikStosu < 1) { printf ("\nZa dużo operandów \n"); return 1;} else { int a = stos [wskaznikStosu - 1]; wskaznikStosu --; stos [wskaznikStosu] = not (a); wskaznikStosu ++; } } // YOU ARE MISSING A BREAK ...
I almost only find C++ posts and not C, when I try to find an answer for this. For built in types as int, char etc. is there any performance difference between pass-by-value and by const pointers? Is it still good programming practice to use the const keyword when passing-by-value? ``` int PassByValue(int value) { ...
Pass by const pointer is never faster than by value as long as the value is less or equal the size of a pointer (sizeof). It also is more annoying and sometimes even wrong (stack variables).
This might be a simple question, but I want to make sure. I want some comments in my .c files to use symbols not supported in the default encoding. If I save the file as UTF-8 for instance, and I only use symbols in comments, is there any way this can affect the compiler in any way? Need to be sure of this.
No, the preprocessor will strip all of that out anyway.
I am tring to convert a string into a floating-point value. Take a look at my small program: ``` #include <stdio.h> int main() { char string[3] = "42"; double value = atof(string); printf("Floating-point value: %f\n", value); return 0; } ``` When I run it, I get this: ``` Floating-p...
``` char string[2] = "42"; ``` should be ``` char string[3] = "42"; ``` the size of"42"array is 3 bytes as you have to count the trailing null character. If you want usechar string[2]for the declaration, yourstringwill not be null terminated. Then you alsohave toincludestdlib.hfile foratofdeclaration: ``` #incude...
Quick question about the order in which functions are executed. My code looks like the following: ``` int values() { 'code' motors(); } int motors() { 'code' values(); } int main() { values(); } ``` After it reads main() and runs values(), it's not aware of motors() so it doesn't run it (I think). I can't put it b...
You can just provide the declarations, and define the functions afterwards. ``` //declarations int values(); int motors(); //definitions int main() { values(); } int values() { motors(); } int motors() { values(); } ```
What does it mean to define an array with enum variable as array size? For example I have the following code: ``` typedef enum { D_ROM_RDE_GROUP_0 = 0x0, D_ROM_RDE_GROUP_1, D_ROM_RDE_MAX_GROUPS }E_ROM_RDE_GROUPS; U_08 pPlaneCopy[D_ROM_RDE_MAX_GROUPS]; ``` I don't understand it... Thanks for the help.
The first thing to remember is that enumeration values are compile-time constant. The other thing is that enumeration values (unless initialized to a specific value) increases. So in your caseD_ROM_RDE_GROUP_0is equal to0,D_ROM_RDE_GROUP_1is equal to1andD_ROM_RDE_MAX_GROUPSis equal to2. This means that when you decla...
``` #include<linux/fs.h> #include<linux/uaccess.h> #include<linux/slab.h> #include<linux/gfp.h> //#include<linux/types.h> //#include<linux/kernel.h> //#include<linux/module.h> char *my_buff = (char*)kmalloc(100,GFP_KERNEL); char *buff = "Linux Device Drivers programming!"; ``` This is part of the program. I'm getti...
You're initializing a static member, means the compiler needs to know what is the value is at compile time. You're trying to assign a value that isn't knowable to the compiler at compile time but knows at run time which is causing the error. Try assigning it in a function as below, ``` char *my_buff; main() { my...
I have a char array inside a struct. ``` myStruct->string; ``` I can actually print themyStruct->stringand everything is there, the memory is also allocated correctly. The problem is when I try to find'\n'I am trying to count how many new lines. Here is the code: ``` while(myStruct->string) { if(strchr('\n', m...
Your use of strchr() here does not really make sense to me. I would suggest the following: ``` char* ptr = mystruct->string;//make a copy of the pointer so that the original is not changed while(ptr) { if( (*ptr) == '\n' ) myStruct-->numbLines++; ptr++; } ```
I'm quite new to programming. I've learnt about loop for a while(about 1 month haha). I've done a number of excercises and so far, I've used mainly for loop. I THINK that they are the same, because in the end, you can achieve the same result with any loop. Can anyone enlight me about this? When should we use a for loo...
forloops andwhileloops generatealmostthe exact same code underneath. The idea behind using aforis when you need an index or iterator of some sort. Awhileis generally used to check a simple boolean condition. More specifically, if you're trying to loop over a collection (array, list, etc.) use afor. If you're checkin...
I was wondering if there is a way I can store a NULL value or an address at an address relative to a pointer by using pointer arithmetic in C. ``` int *p; p = NULL; // is possible int *p, *q; p + 1 = NULL; // ERROR: lvalue required as left operand of assignment p + 1 = q; // ERROR: lvalue required as left oper...
You would need to do something like this, assumingppoints to a valid piece of memory that you have rights to writing to: ``` int **p = something; p[1] = NULL; p[1] = q; ```
Say a pointer is pointing at an object at some address. Later, because there is not enough memory, the OS swaps some pages out of the memory and the object is in one of the page and the pointer is not. Then, the page that has the object is swapped in later to a different location in memory. What happens to the addr...
The address is a an address to virtual memory in the first place. So the address does not need to change – the OS will make sure that the next time you access memory under that address, the address is mapped to the correct physical address.
I tried a simple struct. ``` #include<stdio.h> struct test { int i; int j; }; int main() { struct test t; t.i=1; t.j=2; printf("t:%d, i:%d, j:%d\n", t, t.i, t.j); } ``` the output is incorrect as: ``` "t:1, i:2, j:1 " ``` if I change the printf sentence to ``` printf("i:%d, j:%d\n", t.i, t.j...
The pattern you giveprintf()tells it how it should read the sequence of parameters. You tellprintf()to read a%dbut gives it astruct testinstead of anint. This messes the whole thing becausestruct testis dumped in the stack and it takes a lot more space than anintwould. printf()patterns can only support primitives and...
As the Question already tells: I want to know, is there a ASCII character which will be treat by C in/out without any effect? As example when I write (WhereYwould represent this character) ``` printf ("abcYdYfg"); ``` the output should be: abcdfg And this control character also shall have no effect on any standa...
You can try and use0x1d,0x1e,0x1f, those are the group, record and unit separators. They are intended for exactly what you are trying to do. SeeASCII, the history That being said, I don't think you want to use special characters in this way, instead usememmove(3)as @R suggests in the comments to you question.
Exists in C method for finding a substring in a string? If not, how to effectively deal with this problem? In for cycle? And what is the correct syntax in c? ``` const char subString[] = { "car", "blue", "red"}; char String[] = "I love red color and i hate blue color"; for .... String lenght... { printf("I ...
For null terminated C strings: strstr()
I'm writing my program and i need to get a pointer from c-string. For example, i have a string like "0x3b021e01" and as an output i want a legal pointer void *ptr == 0x3021e101. I tried this approach: ``` char *addr = "0x3021e101"; // this address is just an example of 32-bit addr uint32_t iaddr = from_ch_to_hex(ad...
0x3b021e101 is an odd number, so you would expect alignment errors. By the way, unless you know by other means that the address is valid, say by having a pointer to that address, why don't you just use that pointer?
I've defined var like ``` typedef struct{ float x; float y; float z; } 3DPOINT; ``` then, in my code, I set an array that contains 3DPOINT ``` 3DPOINT myArray[1280]; ``` I properly fill this array and now I need to write each position into txt file. ``` std::ofstream fs("c:\\testvalues.txt"); for (in...
This looks like a homework problem, but the << operator of fstream does the conversion for you. ``` fs<<myArray[i].x<<"\t"<<myArray[i].y<<"\t"<<myArray[i].z<<endl; ``` The "\t"-s are tabs, you can also use simple spaces if you'd like.
I am new to assembly and I wonder why this function for adding two 64bit ints doesn't calculate properly: add.asm ``` bits 32 section .text global _add64 _add64: ; adding a and b enter 0,0 mov eax,[ebp+8] ; la mov edx,[ebp+12] ; ha add eax,[ebp+16] ; la+= lb adc edx,[ebp+20] ; ha+= hb with cf ...
The assembly function looks OK to me. I strongly suspect the%Ldspecifier is wrong. -1863462912 is the low 32 bits of 200000000000. Try%lld.
I have to implement the hist command includng !k and !! The 2 functions: ``` void addInHistory(char **history,char *command,int *list_size,int history_capacity) { int index=*(list_size); if(command[0]!='\n') { if(index==history_capacity-1) { printf("History is full.Deleting commands."); }...
For a C solution ``` char current_command[COMMAND_SIZE]; strcpy(current_command,command); history[index++]=current_command; ``` should be ``` history[index++]= strdup(command); ``` Be sure to free it when you are done with it.
Here is a draft of a code. I wanted to know if it is correct to use array[j++]. Also if correct, will j increment first and then assign value or other way round ``` int i=0, j=0; int array[10]; for(i=0;i<10;i++) { array[j++] = i; /*Is this valid? the j++ part inside an array*/ } ```
Yes, it's correct, but a bit confusing to read. It's better like this: ``` for (int i = 0, j = 0; i != 10; ++i, ++j) { array[j] = i; } ``` Or simply: ``` for (int i = 0; i != 10; ++i) { array[i] = i; } ```
I want to refer a pointer to an array by another pointer. Example: ``` void exp() { double var[2]; exp1(&var[0]); printf("\n varvalue is %lf\n",var[0]); } void exp1(double *var) { //updating the value *var[0]=4.0; exp2(&var[0]); } void exp2(double *var) { *var[0]=7.0; } ``` This should...
Inexp1andexp2the variablevaris a pointer. So using normal array subscript is the same as dereferencing the variable. You try to dereference the variablestwice. A good thing to know is that*varis the same asvar[0]. Or to be more precise*(var + x)is the same asvar[x]. (And as a curiosity, due to the commutative nature ...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions concerning problems with code you've written mustdescribe the specific problem— andinclude valid codeto reproduce it — in the question itself. SeeSSCCE.orgfor guidance.Closed9 years ago.Improve this question `...
Equality and floating point numbers do not go down well. You have rounding errors. Need to put in some tolerance.
Exists in C method for finding a substring in a string? If not, how to effectively deal with this problem? In for cycle? And what is the correct syntax in c? ``` const char subString[] = { "car", "blue", "red"}; char String[] = "I love red color and i hate blue color"; for .... String lenght... { printf("I ...
For null terminated C strings: strstr()
I'm writing my program and i need to get a pointer from c-string. For example, i have a string like "0x3b021e01" and as an output i want a legal pointer void *ptr == 0x3021e101. I tried this approach: ``` char *addr = "0x3021e101"; // this address is just an example of 32-bit addr uint32_t iaddr = from_ch_to_hex(ad...
0x3b021e101 is an odd number, so you would expect alignment errors. By the way, unless you know by other means that the address is valid, say by having a pointer to that address, why don't you just use that pointer?
I've defined var like ``` typedef struct{ float x; float y; float z; } 3DPOINT; ``` then, in my code, I set an array that contains 3DPOINT ``` 3DPOINT myArray[1280]; ``` I properly fill this array and now I need to write each position into txt file. ``` std::ofstream fs("c:\\testvalues.txt"); for (in...
This looks like a homework problem, but the << operator of fstream does the conversion for you. ``` fs<<myArray[i].x<<"\t"<<myArray[i].y<<"\t"<<myArray[i].z<<endl; ``` The "\t"-s are tabs, you can also use simple spaces if you'd like.
I am new to assembly and I wonder why this function for adding two 64bit ints doesn't calculate properly: add.asm ``` bits 32 section .text global _add64 _add64: ; adding a and b enter 0,0 mov eax,[ebp+8] ; la mov edx,[ebp+12] ; ha add eax,[ebp+16] ; la+= lb adc edx,[ebp+20] ; ha+= hb with cf ...
The assembly function looks OK to me. I strongly suspect the%Ldspecifier is wrong. -1863462912 is the low 32 bits of 200000000000. Try%lld.
I have to implement the hist command includng !k and !! The 2 functions: ``` void addInHistory(char **history,char *command,int *list_size,int history_capacity) { int index=*(list_size); if(command[0]!='\n') { if(index==history_capacity-1) { printf("History is full.Deleting commands."); }...
For a C solution ``` char current_command[COMMAND_SIZE]; strcpy(current_command,command); history[index++]=current_command; ``` should be ``` history[index++]= strdup(command); ``` Be sure to free it when you are done with it.
Here is a draft of a code. I wanted to know if it is correct to use array[j++]. Also if correct, will j increment first and then assign value or other way round ``` int i=0, j=0; int array[10]; for(i=0;i<10;i++) { array[j++] = i; /*Is this valid? the j++ part inside an array*/ } ```
Yes, it's correct, but a bit confusing to read. It's better like this: ``` for (int i = 0, j = 0; i != 10; ++i, ++j) { array[j] = i; } ``` Or simply: ``` for (int i = 0; i != 10; ++i) { array[i] = i; } ```
I want to refer a pointer to an array by another pointer. Example: ``` void exp() { double var[2]; exp1(&var[0]); printf("\n varvalue is %lf\n",var[0]); } void exp1(double *var) { //updating the value *var[0]=4.0; exp2(&var[0]); } void exp2(double *var) { *var[0]=7.0; } ``` This should...
Inexp1andexp2the variablevaris a pointer. So using normal array subscript is the same as dereferencing the variable. You try to dereference the variablestwice. A good thing to know is that*varis the same asvar[0]. Or to be more precise*(var + x)is the same asvar[x]. (And as a curiosity, due to the commutative nature ...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions concerning problems with code you've written mustdescribe the specific problem— andinclude valid codeto reproduce it — in the question itself. SeeSSCCE.orgfor guidance.Closed9 years ago.Improve this question `...
Equality and floating point numbers do not go down well. You have rounding errors. Need to put in some tolerance.
Using this example for macClick Here I am getting OpenCL to crash for big arrays (Put NUM_VALUE=10000). Any suggestions on why that would be?
You should run the program in a debugger, like gdb to know for sure. it could be one of these allocations: ``` float* test_in = (float*)malloc(sizeof(cl_float) * NUM_VALUES); void* mem_in = gcl_malloc(sizeof(cl_float) * NUM_VALUES, test_in, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR); void* mem_out = gcl_malloc(sizeo...
Probably my brain is not working properly now... I wonder why I receive mentioned error in my code: ``` int ** zm; zm = (int**)calloc(1, sizeof(int*)); *zm = (int*)calloc(1, sizeof(int)); *zm[0] = 5; *zm = (int*)realloc(*zm, 2*sizeof(int)); *zm[1] = 10; // Access violation reading location 0xFFFFFFFFFFFFFFFF ``` Cou...
Wrong indexing, try(*zm)[1]instead. And check for errors from library calls.
I am creating a console application in C. This is a game in which characters are falling down and user has to press that specific key on the keyboard. I don't know how to detect which key is pressed by the user without pausing the falling characters. When I use scanf the Program waits for input and everything pauses. ...
There is a function calledkbhit()or_kbhitit is in the<conio.h>library it returnstrueorfalsedepending whether a key was hit. So you can go with something like this: ``` while (1){ if ( _kbhit() ) key_code = _getch(); // do stuff depending on key_code else continue; ``` Also usegetch()...
Usually I solve the general compilation errors on my own but with the one I am facing, I m having a hard time to fix. I am porting Android CAF kernel to my device from KitKat branch. The error (forbidden warning) is arch/arm/mach-msm/acpuclock-8960.c:208:2: Initialization from incompatible pointer type [enabled by d...
I work-around-ed the issue by white-listing the file in gcc wrapper script.
I can't understand the description of the "a" and "a+" option in the C fopen api documentation. The option in "a+" is append and update. What is the meaning of the word update here?
Here is what the man pages (man fopen) say: aOpen for appending (writing at end of file). The file is created if it does not exist. The stream is positioned at the end of the file.a+Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for rea...
I am checking a piece of code. Everything is correct but concept I am not able to understand. ``` double a = 0.001; double b = 0.001; double c = a * b; printf ("%lf", c); ``` While debugging in visual c++ when i am pointing mouse over c after 3rd line it is displaying 9.999999999999995e-007 but while printing it is...
This is the result of rounding performed by printf. The printf format %lf rounds to a default precision. From the top of my head, I think the default is 6, that is why you get 0.000001. The debugger shows the actual content of the double. Due to the nature of floating point arithmetic, the result of 0.001 * 0.001 is...
I have a separate folder for my includes because its a part of a larger application, but I use precompiled headers to save time. However, that means I need 2 or more separate stdafx considering I am these standard libraries in my header files as well.
No, that's not working correctly. Your own header files should NEVER reference "stdafx.h". Instead, they may safely assume that it is already included. If you've got multiple projects in your solution, each in their own directory, then each project can contain a separatestdafx.hwithout problems.
Now and then I get this compilation error when compiling a c-file in Eclipse. c:/mingw/bin/../lib/gcc/mingw32/4.7.2/../../../../mingw32/bin/ld.exe: cannot open output file main.exe: Permission denied It happends when I have made a change in the source-code - but not always. I know how to solve this* but I would lik...
You said it yourself, it happens because the program being compiled is still running. In Windows, you can't make changes to the exe file of a program when it's running. It's fantastically annoying, and one of those things that (to me) make Windows slightly less comfortable than e.g. Linux for development.
Many of folks here are telling me to stop usingclrscr(),getch()etc. and I have started learning C++ with the standard library and now that I want to follow the standard library how would I stop the output from immediate exit after run? ``` include <iostream.h> include <conio.h> // Instead of using this void main...
You can directly run the binary from command line. In that case after the program is finished executing the output will still be in the terminal and you can see it. Else if you are using an IDE which closes the terminal as soon as the execution is complete, you can use any blocking operation. The simplest isscanf (" ...
Here is thesummationlogic which performs addition without using+operator as below, ``` int add(int a, int b) { const char *c=0; return &(&c[a])[b]; } ``` Can anyone make me understand howreturnstatement boils to addition ofa&b.
Just remember that sincea[b]is the same as*(a + b), there's an implicit add being done whenever you index an array. That means that&a[b]isa + bsince the address-of and dereference operators cancel out. Then, withcset to0, we can substitute: ``` &(&c[a])[b] = &(&*(0 + a))[b] = &(a)[b] = &a[b] = &*(a + b) = a + b ``` ...
In the following two struct definition, what is the difference among them? ``` struct A { int var[]; }; struct B { int var[0]; }; struct C { int *var; }; ``` I think in case of using those structures, they are the same. Is there a special meaning behind them?
The difference betweenAandBis that the second one is illegal. Array declarations that specify0as the size are always unconditionally illegal in standard C. If your compiler accepts this declaration, it is a non-standard extension of your compiler. Meanwhile, the array declaration inAis a C99 feature that declares a f...
I have the following lines of code which is needed to be written across many files in a project:- ``` #if SOME_CHECK foo(x, y, z); #endif ``` For this, I am planning to wrap the above 3 lines of code into a single macro like this- ``` #define foo(x, y, z) #if SOME_CHECK \ foo(x, y, z); \ #endif ``` But, this i...
Why not do this? ``` #if SOME_CHECK ... The actual function #else #define foo(x,y,z) #endif ``` Whereby any occurrence offoowill be zapped thenSOME_CHECKis set. Otherwise the function is called.
``` #include <stdio.h> #include <string.h> #include "formatCheck.h" int main() { char input[32]; char format[32] printf("enter your format : "); fgets(input,sizeof(input),stdin); sscanf(input,"%s",format); //my problem //if user don't enter format it will exit. if() ...
When user hits only enter,input[0] contains \n ``` fgets(input,sizeof(input),stdin); if(input[0]=='\n') printf("empty string"); ```
I have a snippet of C code: I want to add a new line character at certain intervals. The problem is, when I add it in theifblock, on the next iteration,strcattakes it away, then concatsson, and then puts the\nat the end. I can think of any other way to do this sostrcatdoes not remove the\nthat I want to add. Any id...
hmm... if curPos points to the the next available position in the array, than I would do this. curPos + 1 points after the current '\0' termination of ans, since arrays in C are indexed starting at 0. ``` if (i % 8 == 0 && i != 0) { ans[curPos++] = '\n'; ans[curPos] = '\0'; /* always null terminate a ...
``` row = n + 1; col = n + 1; //used n+1 and i=-1 to avoid segmentation faults board = malloc(row*sizeof(char *)); for(i=-1;i<row;i++) { board[i] = malloc(col*sizeof(char)); if(board[i] == NULL) { printf("Out of memory"); exit(EXIT_FAILURE); } } for(i=-1; i < n+1; ++i) { ...
arrays cannot have negative index in C. at the line:for(i = -1; i < row; i++) I am very sure, there is an off by one error here, wherefreeis freeing one extra block that was notmalloc()ed at the end, and you must be getting a segfault error.
In my iPhone app, I have to use MQTT's C based static library to send and receive its payload, the payload must be void *, I need to send messages such as text, picture and voice This is my sending method, I warp all kind of payloads into NSData object. And the message is a struct which have the void *payload ``` `+ ...
NSData has a method- (const void *)bytes. So this should help resolve the type conflict you are facing. ``` NSUInteger len = [mqPayLoad length]; void *typedData = malloc(len); memcpy(typedData, [mqPayLoad bytes], len); pubmsg.payloadlen = typedData; ``` Since bytes returns aconst void*its better to use amemcopy()rat...
I want to code a program that scans each line and print it. Also this process should keep on when the specific line was detected. Here is my file content : ``` 1 2 3 4 5 6 7 8 9 ``` and the code : ``` #include<stdio.h> #include<stdlib.h> #include<string.h> FILE *file; int main(){ file=fopen("numbers.txt","r"); ...
strcmpreturns non-zero if the strings donotmatch, and zero if they do. Change your test: ``` if( 0 == strcmp(line,"6") ) break; ```
This question already has answers here:What does the question mark character ('?') mean?(8 answers)Closed9 years ago. I am reading up on macros and i wanted to know what this #define does? I don't understand the "?" and the ":". Is it saying that if a ``` #define min(a,b) (a < b ? a : b) ```
That's not a macro feature, that's a core C feature, a ternary operator called the conditional operator. ``` x = a < b ? a : b ``` is essentially: ``` if (a < b) x = a else x = b ``` i.e.:(cond ? a : b)has the value ofaifcondis true, otherwiseb.
I have a simple function that is giving me this error: error: expected delcaration specifiers or '...' before 'time' here is the code in the file: ``` #include <stdlib.h> #include <time.h> srand(time(NULL)); float random_number(float min, float max) { float difference = (max - min); return (((float)(diffe...
In the C language, all code that is executed at runtime must be inside a function. Put the call tosrand()inside an init function.
I'm trying to compile a C program using libxml2 in Eclipse. It seems like my code doesn't have problems, but there are errors when I build my project. The error output is in this screenshot:https://drive.google.com/file/d/0BwV-0_2diIaaQlZHM2Fwa2R0LWc/edit Before this error, I had an “Undefined reference to” error, ...
I solved my problem I just need to write -nostartfiles in the Linker Flags box :D To find "Linker Flags" box go to Your Project > Properties > C/C++Build > Settings > GCC C Linker > Miscellaneous That's it. Thanks for help.
I don't know where to search for this (probably the standard but still don't know what to search for), so I will ask this here. If in some executionarray[i2]will be set toarray[i]wherei2happens to be equal toi, then is this defined behavior? I'm usingC99(withgcc 4.8.1), looking at the assembly withgcc -S, I don't se...
This is absolutely defined behaviour. The right-hand-side of an assignment is calculated first, then assigned to the left-hand-side. Note that the left-hand-side must resolve to an lvalue.
In my c++ program I have various files open at a point where it does afork(). After forking the program duplicates itself and run. The child process will share all opened file handles. My question is, 'Is there a way to know what are various files that are open? such that I can close those file handles and reopen wit...
It's possible to see what files are opened in a given process on linux by checking out/proc/<pid>/fd/*(or/proc/self/fdif you want the current process). Each file there is a sym link named for the corresponding fd, and the link points to the opened file, which you can find by usingreadlink(). You can redirect any part...
I want to code a program that scans each line and print it. Also this process should keep on when the specific line was detected. Here is my file content : ``` 1 2 3 4 5 6 7 8 9 ``` and the code : ``` #include<stdio.h> #include<stdlib.h> #include<string.h> FILE *file; int main(){ file=fopen("numbers.txt","r"); ...
strcmpreturns non-zero if the strings donotmatch, and zero if they do. Change your test: ``` if( 0 == strcmp(line,"6") ) break; ```
This question already has answers here:What does the question mark character ('?') mean?(8 answers)Closed9 years ago. I am reading up on macros and i wanted to know what this #define does? I don't understand the "?" and the ":". Is it saying that if a ``` #define min(a,b) (a < b ? a : b) ```
That's not a macro feature, that's a core C feature, a ternary operator called the conditional operator. ``` x = a < b ? a : b ``` is essentially: ``` if (a < b) x = a else x = b ``` i.e.:(cond ? a : b)has the value ofaifcondis true, otherwiseb.
I have a simple function that is giving me this error: error: expected delcaration specifiers or '...' before 'time' here is the code in the file: ``` #include <stdlib.h> #include <time.h> srand(time(NULL)); float random_number(float min, float max) { float difference = (max - min); return (((float)(diffe...
In the C language, all code that is executed at runtime must be inside a function. Put the call tosrand()inside an init function.
I'm trying to compile a C program using libxml2 in Eclipse. It seems like my code doesn't have problems, but there are errors when I build my project. The error output is in this screenshot:https://drive.google.com/file/d/0BwV-0_2diIaaQlZHM2Fwa2R0LWc/edit Before this error, I had an “Undefined reference to” error, ...
I solved my problem I just need to write -nostartfiles in the Linker Flags box :D To find "Linker Flags" box go to Your Project > Properties > C/C++Build > Settings > GCC C Linker > Miscellaneous That's it. Thanks for help.
I don't know where to search for this (probably the standard but still don't know what to search for), so I will ask this here. If in some executionarray[i2]will be set toarray[i]wherei2happens to be equal toi, then is this defined behavior? I'm usingC99(withgcc 4.8.1), looking at the assembly withgcc -S, I don't se...
This is absolutely defined behaviour. The right-hand-side of an assignment is calculated first, then assigned to the left-hand-side. Note that the left-hand-side must resolve to an lvalue.
In my c++ program I have various files open at a point where it does afork(). After forking the program duplicates itself and run. The child process will share all opened file handles. My question is, 'Is there a way to know what are various files that are open? such that I can close those file handles and reopen wit...
It's possible to see what files are opened in a given process on linux by checking out/proc/<pid>/fd/*(or/proc/self/fdif you want the current process). Each file there is a sym link named for the corresponding fd, and the link points to the opened file, which you can find by usingreadlink(). You can redirect any part...
I need to implement a 32-bit Fixed-point on a 16-bit system. My compiler seems to be giving me an "warning: integer overflow in expression". I'm not sure what I'm missing anything :S . I'll provide a dumbed down version of my code below. Any advice would be appreciate :) ``` #include <stdint.h> typedef int32_t Q22; ...
YourQ22baseis 16-bit on a 16-bitintsystem, you need to cast it toQ22so your*expression is done in at least a 32-bit type. ``` #define Q22_Convert(_a) ((Q22)(_a * (Q22) Q22base)) ```
So I was trying to compile a code which has aSHA1function .. I included following header: ``` #include <openssl/sha.h> ``` And I got the following error while compiling: ``` test.c:9:5: error: 'SHA1' is deprecated: first deprecated in OS X 10.7 [-Werror,-Wdeprecated-declarations] SHA1(msg, strlen(msg), hs); ^ ``...
You can still use it. Deprecated does not mean not available. It's a recommendation to use a different hashing algorithm. You need to link to libcrypto - add-lcryptoto libraries to link to. If you're using more of openssl, you'll also need to link in libssl, using-lssl. so, for example if your test code is test.c, y...
I tried to write Series below in C:series :(1^1),(2^(1/2)),(6^(1/4)),(24^(1/8)),...,((n!)^((1/2)^n)). C Code: ``` #include <stdio.h> #include <math.h> int fact(int x){ if (x==1) return 1; else return x*fact(x-1); } int main(){ int x,y; scanf("%d",&x); y=x; x=fact(x); y=pow(0.5,y-1);...
Because the variableyisint, so storing the return value ofpow()in it truncates. Readthe manual page forpow(). Please check how you enable all warnings in your compiler, andlook at the compiler output.