question
stringlengths
25
894
answer
stringlengths
4
863
Writing to a constant variable using a pointer is giving run time error. ``` const int i; int *p; void main() { p = (int*)&i; *p = 10; // Causes runtime error } ``` But in a windows system everything is running from RAM itself. When I printed the address of const variables and normal variables, I can see that they are in different offsets. How does the system know that the address being accessed by the pointer is aconstone?
Strictly speaking, your code yields undefined behavior according to the C-language standard. In practice, the linker has probably placed the variableiin a RO section of the executable image. So the write-operation*p = 10resulted in a memory-access violation (akasegmentation fault).
I have this signature of a function: ``` void* cloneInt(const void* i); ``` Thisintrepresents a key for a hash function. I need to have this clone function as it is in my API for a generic implementation of a hash table (this function is a part of the int implementation, this function will be forwarded as a pointer to a function that my generic implementation will use). But I am having a problem understanding: how can you clone anint? I need to return a pointer that will point on the same value ofint, but a different place in the memory. This got me very much confused.
This will work: ``` #include <stdio.h> #include <stdlib.h> void* cloneInt(const void* i) { int *myInt = malloc(sizeof(int)); *myInt = *(int*)i; return myInt; } int main(int argc, char** argv) { int i=10; int *j; j = cloneInt(&i); printf("j: %d i: %d\n", *j, i); free(j); } ```
Writing to a constant variable using a pointer is giving run time error. ``` const int i; int *p; void main() { p = (int*)&i; *p = 10; // Causes runtime error } ``` But in a windows system everything is running from RAM itself. When I printed the address of const variables and normal variables, I can see that they are in different offsets. How does the system know that the address being accessed by the pointer is aconstone?
Strictly speaking, your code yields undefined behavior according to the C-language standard. In practice, the linker has probably placed the variableiin a RO section of the executable image. So the write-operation*p = 10resulted in a memory-access violation (akasegmentation fault).
If you have a function from a libraryf_func()and you know it's not reentrant, how would you use it in a threaded environment (POSIX)? You can't access the source code of the library.
You can wrap it in a mutex. Here is an example usage: ``` pthread_mutex_t f_func_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&f_func_mutex); f_func(); // if f_func has "side effects", such as setting a global, you'll want to grab // the value within the locked region: int local = global_set_by_f_func; pthread_mutex_unlock(&f_func_mutex); ```
On the C book, (second edition page 29), I read the following content: ``` /* getline: read a line into s, return length */ int getline(char s[], int lim) { int c, i; for(i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i) s[i] = c; if(c == '\n') { s[i] = c; ++i; } s[i] = '\0'; return i; } } ``` My question is: why it isi<lim-1but noti<limin the for condition test? (ps: lim is the maximum length of a line) Question 2: On C, isEOFcounted as a character?
Space needs to be reserved for the null-terminator\0that is appended to the string at the end of the loop. (This is how strings are modelled in C).EOF is a special value that denotes the end of a file. Note howgetchar()returns anint: this is chiefly so the value of EOF doesn't have to be within the range of achar.
If I gotchar* "12345"and I want to convert tointwith a recursive function, how can I do that ? This is a simple way how to convertchartointwith loop. ``` while (str[i]) { new_num *= 10; new_num += str[i++] - '0'; } ```
If "rexrsia/rxursia way" means the recursive way, here's one way to do it: ``` #include <stdio.h> #include <string.h> int convert_with_length(char* sz, int cch) { // base case: empty string if (cch == 0) { return 0; } // recursive case, use the last digit and recurse on the rest: // e.g. "12345" becomes 10 * convert("1234") + 5 return (sz[cch - 1] - '0') + (10 * convert_with_length(sz, cch - 1)); } int convert(char *sz) { return convert_with_length(sz, strlen(sz)); } int main() { char* str = "12345"; printf("result = %d\n", convert(str)); } ```
I have an executable file which performs data acquisition from an interfaced FPGA and stores it in a specific format. Once in a while, randomly, the acquisition code stops citing receive error. However, re-running the executable works. Hence one temporary arrangement is to run the executable in a shell script. The corresponding process needs to be monitored. If the acquisition stops (and the process ends), the script should re-run the executable. Any hints on how to go about it?
By your description, it sounds like you simply want an endless loop which calls the collector again and again. ``` while true; do collector done >output ``` Redirecting the output outside of the loop is more efficient (you only open the file for writing once) as well as simpler (you don't have to figure out within the loop whether to overwrite or append). If your collector doesn't produce data on standard output, then of course, this detail is moot.
The Thread-Information Block should be widely known, and can be used to access a few important information. But can I use it to save data? I've seen the structure has a slot for an arbitrary pointer at offset14h(x86) /28h(x86-64). Can I use this pointer to point to my own thread structure from my own scheduler? Or does it get overridden by something else?
You can use theTlsAlloc()function to allocate thread local storage. Each TLS index can save a pointer-sized value, so you can use a TLS slot to point to a larger allocated data structure if needed. SeeUsing Thread Local Storagefor an example.
I have compiled gstreamer 1.9.x according to theREADME section COMPILING FROM SOURCE TARBALLS. There was no error in compilation but once after compilation, to test whether compilation is successful(According to README), I have run the command"tools/gst-launch-1.0 -v fakesrc num_buffers=5 ! fakesink"but I am getting error "No such element or plugin 'fakesrc'". I even tried gst-inspect-1.0 to check how many plugin installed, It is only showing two plugins(bin,pipeline).
It got fixed after running this command ``` sudo ldconfig ``` Hope it may help someone.
For example, ``` int x = 10; *(&x) = 20; printf("%d \n",x); // output is 20 ``` According to ISO C11-6.5.3.2 paragraph 4, it says that The unary * operator denotes indirection. If the operand points to a function, the result is a function designator; if it points to an object, the result is an lvalue designating the object. If the operand has type ‘‘pointer to type’’, the result has type ‘‘type’’. If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined. Since the operand&xis neither function designator nor object designator (it is a pointer to type int), I expected undefined behaviour but it works just fine! What am I missing?
The operator&xindicates the address of variablex. When you use an asterisk in front of it, this indicates thecontent at the address of variablex, which is simplyx. The operators*and&neutralize each other, when used like that.
This question already has answers here:SegFault after scanf?(4 answers)Closed7 years ago. As per what I know, %d expects an int value. I don't understand why gcc compiler is saying that it expects int* instead. Here is my code: ``` #include<stdio.h> #include<stdlib.h> struct student { int rn, m[5]; char nm[25]; }; int main() { struct student* s[5]; struct student **q=s; int i = 0; printf("Enter data"); for(i=0;i<5;i++) { printf("\nStudent %d:\n",i+1); printf("Roll number: "); scanf("%d",(s[i])->rn); printf("\n%d",s[i]->rn); } } ``` And here is the warning: ``` warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=] scanf("%d",(s[i])->rn); ```
scanf reads a value into an int, it takes an pointer to the variable to read into. ``` scanf("%d",&((s[i])->rn)); ```
Why is it that when*qis used in 1D array it gives the value in the array whereas*pin 2D array gives an address instead. Isn't*pointer_namesupposed to tell what is stored, so why is output an address instead of40(the value in array)? ``` #include<stdio.h> int main(){ int a[3][4] = { {40, 1, 2, 3} , {4, 5, 6, 7} , {8, 9, 10, 11} }; int (*p)[4] = a; int b[4] = {3,4,8,5}; int *q = b; printf("%d, %d",*q, *p);// output- 3, 10485040 return 0; } ```
Becausepis a pointer to an array. When you dereferencepthe array will decay to a pointer to the first element. Doing*pand&(*p)[0]is equivalent (and also equivalent to&a[0][0]). If you want to print the first element then you need to dereferencebothpointers, i.e.**p.
C Question as this way as in the title. How to display the string variable in field for three characters longer than length of this variable. code: ``` char name[10]; int length; printf("Enter your name: "); scanf("%s", name); length = strlen(name) + 3; ``` And what then? It should be something like that: ``` Enter your name: XXX " XXX" ```
The simplest way to achieve this is to simply add 3 spaces before the%s: ``` printf(" %s\n", name); ``` You can also use a variable length specifier (if you want to learn how it works): ``` printf("%*s\n", length+3, name); ```
I have recently started following the CS50 course on Edx. I'm stuck on the second problem set as when I try to compile my code, this message comes up: ``` expected identifier or '(' in C ``` If you need my code, here it is: ``` #include <stdio.h> #include <cs50.h> int main (int argc, string argv[]) int key; { if (argc != 2) { printf("error\n"); } else { key = atoi(argv[1]); if (key == 0 || key < 0) { printf("error"); } else { printf("%i\n", key); } } } ``` If there is anything else wrong with my code, could you please hint it for me?
``` int main (int argc, string argv[]) { int key; ``` needs to be inside the bracket
I'm doing a project in which I am using the TI CC3200 LaunchPad to detect my bedroom's temperature, real-time. I followed all the AWS IOT C SDK to my Windows machine, downloaded the security keys / certificates, and created a new "thing"in my AWS IOT console. However, it's not clear what are the actual steps to run the sample application and truly test the connection of my device to the Amazon cloud.
I'd suggest to not use bare CC3200, at least for the beginning. There are ready to use CC3200 solutions, like MWS (seehere), probably you can find something else. But AFAIK MWS (or eventhis) is able to connect AWS. Later, then you will understand how it works you can decide either continue to use MWS (etc) or rewrite everything from scratch.
C Question as this way as in the title. How to display the string variable in field for three characters longer than length of this variable. code: ``` char name[10]; int length; printf("Enter your name: "); scanf("%s", name); length = strlen(name) + 3; ``` And what then? It should be something like that: ``` Enter your name: XXX " XXX" ```
The simplest way to achieve this is to simply add 3 spaces before the%s: ``` printf(" %s\n", name); ``` You can also use a variable length specifier (if you want to learn how it works): ``` printf("%*s\n", length+3, name); ```
I have recently started following the CS50 course on Edx. I'm stuck on the second problem set as when I try to compile my code, this message comes up: ``` expected identifier or '(' in C ``` If you need my code, here it is: ``` #include <stdio.h> #include <cs50.h> int main (int argc, string argv[]) int key; { if (argc != 2) { printf("error\n"); } else { key = atoi(argv[1]); if (key == 0 || key < 0) { printf("error"); } else { printf("%i\n", key); } } } ``` If there is anything else wrong with my code, could you please hint it for me?
``` int main (int argc, string argv[]) { int key; ``` needs to be inside the bracket
I'm doing a project in which I am using the TI CC3200 LaunchPad to detect my bedroom's temperature, real-time. I followed all the AWS IOT C SDK to my Windows machine, downloaded the security keys / certificates, and created a new "thing"in my AWS IOT console. However, it's not clear what are the actual steps to run the sample application and truly test the connection of my device to the Amazon cloud.
I'd suggest to not use bare CC3200, at least for the beginning. There are ready to use CC3200 solutions, like MWS (seehere), probably you can find something else. But AFAIK MWS (or eventhis) is able to connect AWS. Later, then you will understand how it works you can decide either continue to use MWS (etc) or rewrite everything from scratch.
I'm doing a project in which I am using the TI CC3200 LaunchPad to detect my bedroom's temperature, real-time. I followed all the AWS IOT C SDK to my Windows machine, downloaded the security keys / certificates, and created a new "thing"in my AWS IOT console. However, it's not clear what are the actual steps to run the sample application and truly test the connection of my device to the Amazon cloud.
I'd suggest to not use bare CC3200, at least for the beginning. There are ready to use CC3200 solutions, like MWS (seehere), probably you can find something else. But AFAIK MWS (or eventhis) is able to connect AWS. Later, then you will understand how it works you can decide either continue to use MWS (etc) or rewrite everything from scratch.
I am just learning C I have written the following: ``` void main(void) { unsigned int curr_dat = 0; // The current dat file to use unsigned char ch = 0; // Key entered at keyboard unsigned char lastkey = 0; // Last key entered (movement command) FILE *fp; } ``` However i am getting these errors when trying to compile:error C2065: 'FILE' : undeclared identifiererror C2065: 'fp' : undeclared identifierwarning C4552: '*' : operator has no effect; expected operator with side-effect I'm unsure why as i believeFILEis a valid identifier in C I am using Developer Command Prompt for VS2012 to compile
FILEis declared instdio.h. Add#include <stdio.h>to the top of your file.
So I browsed some of the same questions and found a working answer. I was just wondering if someone can explain to me the last line of the code from this answer: Read text from a file and realloc when needed ``` fgets(linebuffer + (maxlinelen/2 - 1), maxlinelen/2 + 1, fp); //this line ``` Thank you very much!
The writer is trying to read into the second half of the array. In order to do that, the base address must be higher. Hence the first argumentlinebuffer + (maxlinelen/2 - 1). It's taking the base address of the array, and adding half the array's length to it. But since the array is half as long, the writer halves the size of the array. Hence the second argument,maxlinelen/2 + 1.
``` int a = 0, b = 0, c = -1; if (b = a || b == ++c ) a+=3; ``` Why are the values of a,b and c 3 , 1, 0 respectively? More specifically, why is b 1 and not 0?
Because||has higher precedence than=, so it's being parsed as if you'd written. ``` if (b = (a || (b == ++c))) ``` This calculatesa || (b == ++c). This is true becauseb == 0and++c == 0, sob == ++cis true, and true is1. Add parentheses to get what you want: ``` if ((b = a) || (b == ++c)) ``` But IMHO it's generally best to avoid writing such complex expressions. Do them as separate statements: ``` b = a; if (b || b == ++c) ```
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed7 years ago.Improve this question ``` FILE *fp; char name[50]; fp=fopen("stu.txt","r"); while(fgets(name,50,fp)!=NULL) { printf(" %s",name); fgets(name,50,fp); } fclose(fp); ``` In my file there are 4 names in 4 different lines but the output only displays the 1st and the 3rd name.What's wrong?I know it's very basic but this has taken up a lot of my time.
You're (f)getting in thewhilestatementandinside the loop block, so you're advancing the file position without utilizing what you've read in the internal call. Try this: ``` while(fgets(name,50,fp)!=NULL) { printf(" %s",name); } ```
Is ZeroMQ or RabbitMQ asynchronous, even when it is utilized in C programming?
Yes, both ZeroMQ and RabbitMQ support asynchronous modes of operation, and this applies to the C client library implementations for both (as of this writing).
This question already has answers here:C: transitive (double) assignments(6 answers)Closed7 years ago. I came across this code today: ``` for (i = 0; i < level; i++) { a[i] = b[i] = c[i] = 0; } ``` What is the meaning of the code located inside the for loop?
``` a[i] = b[i] = c[i] = 0; ``` is parsed as: ``` a[i] = (b[i] = (c[i] = 0)); ``` and has the same effect as: ``` a[i] = 0; b[i] = 0; c[i] = 0; ```
In C, printing tostandard output(stdout) is easy, withprintffromstdio.h. However, how can I print tostandard error(stderr)? We can usefprintfto achieve it apparently, but its syntax seems strange. Maybe we can useprintfto print to standard error?
The syntax is almost the same asprintf. Withprintfyou give the string format and its contents ie: ``` printf("my %s has %d chars\n", "string format", 30); ``` Withfprintfit is the same, except now you are also specifying the place to print to: ``` FILE *myFile; ... fprintf(myFile, "my %s has %d chars\n", "string format", 30); ``` Or in your case: ``` fprintf(stderr, "my %s has %d chars\n", "string format", 30); ```
Say I have an array ``` int A[2][2]; ``` and I want to initialize only the first row with a list of constants like so ``` A[0] = { 1, 2 }; ``` Unfortunately the compiler returns. error: ``` expected expression before '{' token_. ``` Although this example is small, think big. I know there are some obtuse ways of doing it but it would shock me if there wasn't an efficient solution.
Initializers do not work like that. You should initialize it at the time of declaration as ``` int A[2][2] = { {1, 2} }; // Rest elements will be initialized to 0 ``` or using designated initializer ``` int A[2][2] = { [0] = {1, 2} }; // C99 and later ```
Can I pass a character array tofopen? For example: ``` fopen(s, "r"); ``` Wheresis declared as a character array and is null terminated.
smust be a pointer to a null terminated character array. Theman pagesconfirm this ``` FILE *fopen(const char *path, const char *mode); ``` You can see that it must be null terminated, since nosizeargument is given.
``` int a = 0, b = 0, c = -1; if (b = a || b == ++c ) a+=3; ``` Why are the values of a,b and c 3 , 1, 0 respectively? More specifically, why is b 1 and not 0?
Because||has higher precedence than=, so it's being parsed as if you'd written. ``` if (b = (a || (b == ++c))) ``` This calculatesa || (b == ++c). This is true becauseb == 0and++c == 0, sob == ++cis true, and true is1. Add parentheses to get what you want: ``` if ((b = a) || (b == ++c)) ``` But IMHO it's generally best to avoid writing such complex expressions. Do them as separate statements: ``` b = a; if (b || b == ++c) ```
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed7 years ago.Improve this question ``` FILE *fp; char name[50]; fp=fopen("stu.txt","r"); while(fgets(name,50,fp)!=NULL) { printf(" %s",name); fgets(name,50,fp); } fclose(fp); ``` In my file there are 4 names in 4 different lines but the output only displays the 1st and the 3rd name.What's wrong?I know it's very basic but this has taken up a lot of my time.
You're (f)getting in thewhilestatementandinside the loop block, so you're advancing the file position without utilizing what you've read in the internal call. Try this: ``` while(fgets(name,50,fp)!=NULL) { printf(" %s",name); } ```
Is ZeroMQ or RabbitMQ asynchronous, even when it is utilized in C programming?
Yes, both ZeroMQ and RabbitMQ support asynchronous modes of operation, and this applies to the C client library implementations for both (as of this writing).
This question already has answers here:C: transitive (double) assignments(6 answers)Closed7 years ago. I came across this code today: ``` for (i = 0; i < level; i++) { a[i] = b[i] = c[i] = 0; } ``` What is the meaning of the code located inside the for loop?
``` a[i] = b[i] = c[i] = 0; ``` is parsed as: ``` a[i] = (b[i] = (c[i] = 0)); ``` and has the same effect as: ``` a[i] = 0; b[i] = 0; c[i] = 0; ```
In C, printing tostandard output(stdout) is easy, withprintffromstdio.h. However, how can I print tostandard error(stderr)? We can usefprintfto achieve it apparently, but its syntax seems strange. Maybe we can useprintfto print to standard error?
The syntax is almost the same asprintf. Withprintfyou give the string format and its contents ie: ``` printf("my %s has %d chars\n", "string format", 30); ``` Withfprintfit is the same, except now you are also specifying the place to print to: ``` FILE *myFile; ... fprintf(myFile, "my %s has %d chars\n", "string format", 30); ``` Or in your case: ``` fprintf(stderr, "my %s has %d chars\n", "string format", 30); ```
Say I have an array ``` int A[2][2]; ``` and I want to initialize only the first row with a list of constants like so ``` A[0] = { 1, 2 }; ``` Unfortunately the compiler returns. error: ``` expected expression before '{' token_. ``` Although this example is small, think big. I know there are some obtuse ways of doing it but it would shock me if there wasn't an efficient solution.
Initializers do not work like that. You should initialize it at the time of declaration as ``` int A[2][2] = { {1, 2} }; // Rest elements will be initialized to 0 ``` or using designated initializer ``` int A[2][2] = { [0] = {1, 2} }; // C99 and later ```
Can I pass a character array tofopen? For example: ``` fopen(s, "r"); ``` Wheresis declared as a character array and is null terminated.
smust be a pointer to a null terminated character array. Theman pagesconfirm this ``` FILE *fopen(const char *path, const char *mode); ``` You can see that it must be null terminated, since nosizeargument is given.
Suppose I have this array: ``` uint8_t arr[10]; ``` located at address0x00. Then I want to assign part of it to uint32_t value. Aggregatin of arr[1], arr[2], arr[3] and arr[4] to 32 bit integer. Here is an example: ``` uint8_t arr[10]; uint32_t i; i = *( (uint32_t *)&arr[1] ); ``` What bothers me is thatarr[1]is located at address not multiple of four(at address 0x01). So the question is: what would happen on 32bit platform? Is this legal, does it have some disadvantages compared to standarduint32assignments?
It's illegal, because it breaks strict aliasing rules, resulting inundefined behaviour. Usememcpyinstead: ``` memcpy(&i, &arr[1], sizeof(i)); ``` But do notice that this code assumes host endianness. If you need endianness independent code, use bit shifting and masking to combine 4 values in to integer, or swap bytes aftermemcpy(compilers usually offer some kind intrisics for this).
As part of my C code I run python script,(one of the .dll files runs the script) ``` getcwd(directory); ret_value = ShellExecute(NULL,NULL,"myScript.py",NULL,directory,0); ``` This is the folder of the program after build. If I run the .exe from the folder every thing works. The bug:If I search program .exe outside the folder and run it the script doesn't run. Search:If I run it from here the script doesn't run.
GetModuleFileNameW() function retrieves the fully qualified path for the file that contains the specified module. This way you can find absolute path of the .dll and use _chdir and change the current working directory to that path.
``` #include<Windows.h> #include<direct.h> int main() { _chdir`("C:\\Program Files (x86)\\VideoLAN\\VLC"); system("vlc C:\\Users\\Documents\\Wildlife.wmv"); return 0; } ``` By using the above code i am successfully able to run the video using vlc player but as the video finishes,still the VLC player window doesn't get close.How to shut the VLC player window? Please post your valuable suggestion
Use option--play-and-exitorvlc://quit, namely system("vlc file:///C:\\Users\\Documents\\Wildlife.wmv --play-and-exit"); or system("vlc file:///C:\\Users\\Documents\\Wildlife.wmv --vlc://quit"); If you want to use another system call to terminate it, try this on Windows: system("taskkill /im vlc.exe");
``` void func(int num){ if(num< 3){ printf("%d ", num); func(num+ 1); printf("%d ", num); } } ``` Suppose I call this function with func(0). Why is the result 0 1 2 2 1 0 ? I don't know why it's decreasing.
Here's a stack trace ``` f(0) print 0 f(1) print 1 f(2) print 2 f(3) // 3 < 3 == false print 2 print 1 print 0 ```
Say I have a filefoo.cand there is noMakefile, when I callmake foothe implicit rules ofmakeconveniently kick in and compilefoo.c. Is there an easy way to add a couple flags such as-gand-Wallinto the implicit rules? I've seen that I could use pattern rules in aMakefile, but I'd rather have these flags in the implicit rules apply across the entirety of my local machine (mac OS).
You can prependCFLAGSto the command line: ``` CFLAGS='-g -Wall' make foo ```
This a part of my code: ``` int h = height+1; int w = width+1; char board[h][w]; board[0][w] = 'a'; board[1][0] = '|'; printf("%c, %c", board[0][w], board[1][0]); ``` but when i compile and run it i get this: ``` |, | ``` what am I doing wrong?
You invokedundefined behaviorby accessing out-of-range of array. Allocate enough elements or use correct index. former example: ``` int h = height+1; int w = width+1; char board[h][w+1]; /* allocate w+1 elements instead of w */ board[0][w] = 'a'; board[1][0] = '|'; printf("%c, %c", board[0][w], board[1][0]); ``` latter example: ``` int h = height+1; int w = width+1; char board[h][w]; board[0][w-1] = 'a'; /* use w-1 instead of w */ board[1][0] = '|'; printf("%c, %c", board[0][w-1], board[1][0]); /* use w-1 instead of w */ ```
I have a .txt file contains only0and1like data. All I need to do is loop through the file, collecting 8 bits in an unsigned char by using the<<operator to move each bit up into place, and then write each assembled byte to ASCII. ``` bit_files *tmp; tmp = (bit_files *)malloc(sizeof(bit_files)); char a; char byte; FILE *first_file,*final_file; first_file=fopen("file1","rb"); final_file=fopen("file2","wb"); tmp->bitCount = 0; while (a=fgetc(first_file)!=EOF){ byte=tmp->bitBuffer<<=a; tmp->bitCount++; if (tmp->bitCount==8){ fputc(byte,final_file); tmp->bitBuffer=0; tmp->bitCount=0; } } fclose(first_file); fclose(final_file); ```
There is a bug in byte=tmp->bitBuffer<<=a; You are overwriting you byte-value from the previouse bit... try something like this instead: Byte = Byte | (tmp->bitBuffer<<=a);
Set PriorityWhat are all possible priorities in KPRIORITY in win kernel?
From thedocumentation for KeQueryPriorityThread: Thread priorities range from 0 to 31, where 0 is the lowest priority and 31 is the highest.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question (This is a very basic question, but I can't seem to find an answer because it involves||, which is a problematic search term.) Since a char can be interpreted as a boolean in a conditional like this: ``` if (str[i]) ... if (c) ... ``` where '\0' is considered falsey and any other character is truthy, I was expecting this to work too: ``` char c = str[i] || 'x'; ``` but it's always giving a value of 1. Is there a simple shorthand in C for this? I've become used to it in JavaScript, and I find it clear and concise.
The ternary operator is what you are looking for: ``` char c = str[i] ? str[i] : 'x'; ``` Exaplanation: ifstr[i]is truthy, assign value ofstr[i]to variablec, other case assign letter'x'.
I am reading from a file usingfgetcand doing that makes it so that I have a char. However, I want to convert this char to a string such that I can use thestrtokfunction upon it. How would I go about doing this? ``` int xp; while(1) { xp = fgetc(filename); char xpchar = xp; //convert xpchar into a string } ```
Simply create an array with two items, your character and the null terminator: ``` char str[] = {ch, '\0'}; ``` Or if you will, use a compound literal to do the same: ``` (char[]){ch, '\0'} ``` Compound literals can be used to convert your character directly, inside an expression: ``` printf("%s", (char[]){ch, '\0'} ); ```
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question (This is a very basic question, but I can't seem to find an answer because it involves||, which is a problematic search term.) Since a char can be interpreted as a boolean in a conditional like this: ``` if (str[i]) ... if (c) ... ``` where '\0' is considered falsey and any other character is truthy, I was expecting this to work too: ``` char c = str[i] || 'x'; ``` but it's always giving a value of 1. Is there a simple shorthand in C for this? I've become used to it in JavaScript, and I find it clear and concise.
The ternary operator is what you are looking for: ``` char c = str[i] ? str[i] : 'x'; ``` Exaplanation: ifstr[i]is truthy, assign value ofstr[i]to variablec, other case assign letter'x'.
``` for (icnt = 1; icnt <= (ino1 / 2) && (ino2 / 2) ; icnt++) ``` and ``` for (icnt = 1; icnt <= (ino1 / 2) && icnt <= (ino2 / 2) ; icnt++) ``` Bothforloops gives same output still then what is the difference between both statements ? I tried to find out flow of program, can someone explain me what is the difference
Both loops iterate the same number of times only by chance, probably becauseino1 <= ino2. The first loop iterates whileicnt <= ino1 / 2andino2 / 2 != 0, which is very different from the second loop condition whereicntmust be less or equal tobothino1 / 2andino2 / 2.
I'm trying to make a tiny program where you input for example 1 + 2 and the output should be the sum of those two numbers. But it keeps crashing and or won't do anything. What's going on? ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main(){ char *op; char *first; char *second; printf("Enter operation\n"); scanf(" %s%s%s", &first, &op, &second); int num1; int num2; int num3; int add; num1 = atoi(first); num2 = atoi(op); num3 = atoi(second); add = num1 + num3; printf("Sum = %i\n",add); return 0; } ```
atoitakes argument asconst char *and notchar. Your variables are of typecharwhere asatoiconverts string tointtype. Also you passchar *as argument to%dinscanf, that results in undefined behavour. ``` scanf(" %d%d%d", &first, &op, &second) ^^^^^^ expects int * not char * ```
I have a question regarding char pointers. I am reading a file in C, usingfgets. This is a short overview so you can understand what I would like to do: ``` char configline[configmax_len + 1]; //configmax_len is the max value I need while(fgets(configline, sizeof(configline), config){ //config is the file char *configvalue = strtok(configline, " "); if (configvalue[0] == "#"){ continue; } … } ``` char * configvalueis a pointer to the current line being read. What I would like to check is if the first character of the line is a "#". However when I do the if statement:if (configvalue[0] == "#"), the compiler throws an error:comparison between pointer and integer. How could I check if the first character of the string a pointer is pointing to is a certain value?
try using ``` if (configvalue[0] == '#'){ ``` this should compile nicely
I have this struct: ``` typedef struct { UINT8 a; UINT8 len; BYTE *data; } MyStruct; ``` and this binary array [0x00, 0x03, 0x08, 0x09, 0x0a] which is assigned to a void* variable "BINDATA". How can I cast BINDATA to MyStruct and be able to access its "data" field? I tried: ``` MyStruct *myStruct = (MyStruct*) BINDATA; ``` After that I was able to access: ``` myStruct->a; //gave me 0x00 myStruct->len; //gave me 0x03 ``` But I could not access ``` myStruct->data; ``` without memory access violation. I guess this is because "data" address pointer gets set to 0x08 and not its value.
Instead ofBYTE *datayou should useBYTE data[0]or (if your compiler doesn't like this)BYTE data[1]. The difference between pointer and array here is crucial - array is "data that is right here" while pointer is "data somewhere else" which is not your case.
I am starting to write an app which I want to be multiplatform and I am stuck on the part of deciding which UI framework should I use. That's where my question comes from: Is it possible to have a fixed GTK theme for an application instead of using system active theme? I want my application to look the same across Windows, OS X and Linux instead of trying to look like it's using system native controls.
"instead of using system active theme? " do you mean by: "active"-> "native" YES, from Gtk+3.0 ,you can use fixed GTK theme by using css themes,it is cross-platform(but it seems QT is even better when crossing platform,in my opinion). here are some articles about default theme and how to change themes: https://blogs.gnome.org/mclasen/2014/06/13/a-new-default-theme-for-gtk/ https://developer.gnome.org/gtk3/stable/gtk-migrating-GtkStyleContext.html
I've used OpenSSLBIGNUMto implement some cryptosystems and I am now wondering if it also offers big decimal support. I could not find anything in the documentation but perhaps there is an extension/add-on somewhere preferably in C (not C++)? Note: I am aware of GMP and NTL, I am not looking for those.
Does OpenSSL offer Big Decimal support? No.
In C++ we can generate true random numbers (if your hardware supports) with random_device. And i am writing a implementation of One-time Pad algorithm with C. Is there a way to generate true random numbers in C? I writing with C for speed and some another reasons. If i use a PRNG, it is will be unsafe. ``` char *KeyGenerate(unsigned long long StringLength) { std::random_device TrueRandomNumberGenerator; char *Key = (char *) malloc(StringLength + 1); for(unsigned long long I = 0; I < StringLength; I++) { Key[I] = TrueRandomNumberGenerator(); } Key[StringLength] = '\0'; return Key; } ```
The C standard library is very very tiny. To get true random numbers, you will need to use OS-specific APIs. In Linux systems, you can get a stream of cryptographically-strong random bytes from the/dev/urandomfile.
I runcalloc(1024 * 1024 * 1024, sizeof(int));I check my program's usage and it's zero but I never made a call tofree Edit: Running Debian Jessie Edit 2: I am using the top as the system monitor
Linux does lazy memory allocation. Only when a page fault occurs on a page marked as allocated does Linux actually consider it as being used. Try writing to a byte inside the allocated data and checking the memory usage again. For more information on memory allocation in Linux, checkhttp://www.tldp.org/LDP/tlk/mm/memory.html. Additionally, even though calloc zeroes the allocated memory, it can still be done in a lazy way that leads to the behavior you described. SeeHow to lazy allocate zeroed memory?.
If enter key is pressed,scanf()stops taking inputs hereafter. I've tried many ways: changing data to string and comparing it to null, comparing to ASCII. But, I could not preventscanffrom terminating when user presses enter.
Read a line of text usingfgets.Iffgetsis able read the line without error, usesscanfto read the number from the line.Ifsscanfis successful, use the number. Otherwise, go to error handling code. ``` char line[LINE_SIZE]; if ( fgets(line, LINE_SIZE, stdin) != NULL ) { int number; if ( sscanf(line, "%d", &number) == 1 ) { // Use the number } else { // Deal with error } } ```
I have this struct: ``` typedef struct { UINT8 a; UINT8 len; BYTE *data; } MyStruct; ``` and this binary array [0x00, 0x03, 0x08, 0x09, 0x0a] which is assigned to a void* variable "BINDATA". How can I cast BINDATA to MyStruct and be able to access its "data" field? I tried: ``` MyStruct *myStruct = (MyStruct*) BINDATA; ``` After that I was able to access: ``` myStruct->a; //gave me 0x00 myStruct->len; //gave me 0x03 ``` But I could not access ``` myStruct->data; ``` without memory access violation. I guess this is because "data" address pointer gets set to 0x08 and not its value.
Instead ofBYTE *datayou should useBYTE data[0]or (if your compiler doesn't like this)BYTE data[1]. The difference between pointer and array here is crucial - array is "data that is right here" while pointer is "data somewhere else" which is not your case.
Is there anyway to do the following in C? ``` float *t = (float*)malloc(t_size*sizeof(float)); t = { 1,0,0, -1,0,0, 0,1,0 }; ``` Similar to how the following is standard ``` float t[9] = { 1,0,0, -1,0,0, 0,1,0 }; ```
As asked, acsoultion can be done usingcompound literals ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { #define t_size 9 float *t = malloc(t_size*sizeof(*t)); if (t != NULL) { memcpy(t, (float[t_size]){1,0,0,-1,0,0,0,1,0}, t_size*sizeof(*t)); for (size_t i=0; i<t_size; i++) printf("t[%zu] = %g\n", i, t[i]); } free(t); return 0; } ```
What does this syntax inCmean? ``` EventEntry tTab[] = { {LEVEL, wLP0000FF00}, {0xFFFF, wL0000Ign} }; ``` I see just an array and something very similar to struct. So,tTabis an array of EventEntries, isnt it?
This is a declaration for an array ofEventEntryobjects, which are probablystructs with atypedef(although they could also be arrays). This syntax defines an array of two items. The fields of the initial item are initialized with{LEVEL, wLP0000FF00}, and the content of{0xFFFF, wL0000Ign}goes into the second element. This is an old initialization syntax. New and improved one lets you designate the fields being initialized by name: ``` EventEntry tTab[] = { {.field1 = LEVEL, .field2 = wLP0000FF00}, {.field1 = 0xFFFF, .field2 = wL0000Ign} }; ```
``` #include<stdio.h> #include<conio.h> #include<stdlib.h> void main() { int n; void towers(int n,char from, char to,char aux); clrscr(); printf("\n\t\t PROGRAM FOR TOWERS OF HANOI"); printf("\n\nEnter The Total number of Disks : "); scanf("%d",n); towers(n,'A','C','B'); getch(); } void towers(int n,char from,char to, char aux) { if(n==1) { printf("\nMove disk 1 from %c peg to %c peg",from,to); return; } towers(n-1,from,aux,to); printf("\n Move disk %d from %c peg to %c peg",n,from,to); towers(n-1,aux,to,from); } ```
Use scanf("%d",&n); instead of scanf("%d",n); becuase it requires the address of variable n to the scanf function to store the value. so,that address is specified through &n.
Is there anyway to do the following in C? ``` float *t = (float*)malloc(t_size*sizeof(float)); t = { 1,0,0, -1,0,0, 0,1,0 }; ``` Similar to how the following is standard ``` float t[9] = { 1,0,0, -1,0,0, 0,1,0 }; ```
As asked, acsoultion can be done usingcompound literals ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { #define t_size 9 float *t = malloc(t_size*sizeof(*t)); if (t != NULL) { memcpy(t, (float[t_size]){1,0,0,-1,0,0,0,1,0}, t_size*sizeof(*t)); for (size_t i=0; i<t_size; i++) printf("t[%zu] = %g\n", i, t[i]); } free(t); return 0; } ```
What does this syntax inCmean? ``` EventEntry tTab[] = { {LEVEL, wLP0000FF00}, {0xFFFF, wL0000Ign} }; ``` I see just an array and something very similar to struct. So,tTabis an array of EventEntries, isnt it?
This is a declaration for an array ofEventEntryobjects, which are probablystructs with atypedef(although they could also be arrays). This syntax defines an array of two items. The fields of the initial item are initialized with{LEVEL, wLP0000FF00}, and the content of{0xFFFF, wL0000Ign}goes into the second element. This is an old initialization syntax. New and improved one lets you designate the fields being initialized by name: ``` EventEntry tTab[] = { {.field1 = LEVEL, .field2 = wLP0000FF00}, {.field1 = 0xFFFF, .field2 = wL0000Ign} }; ```
``` #include<stdio.h> #include<conio.h> #include<stdlib.h> void main() { int n; void towers(int n,char from, char to,char aux); clrscr(); printf("\n\t\t PROGRAM FOR TOWERS OF HANOI"); printf("\n\nEnter The Total number of Disks : "); scanf("%d",n); towers(n,'A','C','B'); getch(); } void towers(int n,char from,char to, char aux) { if(n==1) { printf("\nMove disk 1 from %c peg to %c peg",from,to); return; } towers(n-1,from,aux,to); printf("\n Move disk %d from %c peg to %c peg",n,from,to); towers(n-1,aux,to,from); } ```
Use scanf("%d",&n); instead of scanf("%d",n); becuase it requires the address of variable n to the scanf function to store the value. so,that address is specified through &n.
Say I made and compiled a small program inCto count the bytes of a file, calledfilebyte. To run it I would use./filebyte Now I want to make it universal on bash, like for example to run a php file, I would usebashcommandphp file.php, same way I would like to run my program,filebyte filename. How do I do this? Thanks!
I often create abin/directory in my home directory, for small custom applications. You then need to add that directory to your PATH, which is a list of colon-separated paths that your shell searches for executables when you type a name on thr command line. This is usually accomplished by putting this in your~/.bashrcfile: ``` PATH="$PATH:~/bin" ```
Suppose I have a function: void add(int a, int b , int c); and I have an array which contains 3 integer values: int L[] = {1,2,3}; Now I want to pass these values to add without writingadd(L[0],L[1],L[2]).I mean is there a way of creating a Single input from multiple inputs and passing it to the function which will treat that single input as multiple inputs ??.
You could try this ``` int L[] = {1,2,3}; add(L, 3); ``` where ``` void add(int *x, int length) { // use x[0], x[1], etc. } ``` But I am not sure why you are having problem with your current approach. Another option would probably be to encapsulate those three integers into a structure and pass the structure along.
Can anybody tell me why the loop does not exit whenever I press letter X? How to make the program not get the value of backspace and enter into the array? ``` #include <stdio.h> #include <stdlib.h> #include<math.h> #define N 2 #define M 4 int main() { int i,j,a[N][M]; for(i=0;i<N;i++) { for(j=0;j<M;j++) { scanf("%c",&a[i][j]); if(a[i][j]=='X') break; } if(a[i][j]=='X') break; } return 0; } ```
Changescanf("%c",&a[i][j]);toscanf(" %c",&a[i][j]); This allows for any spaces to be bypassed before scanning the character.
I'm using winsock to receive udp messages 256 bits long. I use 8 32-bit integers to hold the data. ``` int32_t dataReceived[8]; recvfrom(client, (char *)&dataReceived, 8 * sizeof(int), 0, &fromAddr, &fromLen); ``` I need to grab specific bits like, bit #100, #225, #55, etc. So some bits will be in dataReceived[3], some in dataReceived[4], etc. I was thinking I need to bitshift each array, but things got complicated. Am I approaching this all wrong?
Why are you usingint32_ttype for buffer elements and notuint32_t? I usually use something like this: ``` int bit_needed = 100; uint32_t the_bit = dataReceived[bit_needed>>5] & (1U << (bit_needed & 0x1F)); ``` Or you can use this one (but it won't work for sign in signed integers): ``` int bit_needed = 100; uint32_t the_bit = (dataReceived[bit_needed>>5] >> (bit_needed & 0x1F)) & 1U; ``` In other answers you can access only lowes 8bits in each int32_t.
This question already has answers here:What is the difference between char s[] and char *s?(14 answers)Closed7 years ago. ``` void main(){ char *const p="Hello"; p++; // causes error object p non modifiable } void main(){ char A[10]="ANSHU"; A++; // here causes lvalue problem } ``` So, my question is, what is difference between these two programs and next question is that is array's declaration like this ``` int *const A; ```
In the first program you declaredpasconst, regardless of its type. So you cannot assign to it after the first initialization.p++tries to assign topthe value ofp+1and thus fails. In the second program you used an array. The name of the array,Ais actually like alabel. You can use it as an address to pass on, but you can't change it.
Using GNUindent, when I usedgnustyle, I will end up with a source like this: ``` void compute_column_indices(u32 size, s32 * ind) { ... } ``` But I don't want the return value (void) to sit on its own line. Thelinuxstyle does it but it introduces other style aspects I don't like. This is what I want to have done: ``` void compute_column_indices(u32 size, s32 * ind) { ... } ``` What switch to use to accomplish this? I stared at the man page and I can't find it.
Argh, I found it! It is--procnames-start-linesoption (or-pslfor short).
So I was able to pass an Ada function using Ada_function'Address to a C_function. Here is the C function: ``` void Create_Process(int * status, void * function) { pthread_t new_thread; //creating function with the given function and no arguments. *status = pthread_create(&new_thread, NULL, function, NULL); } ``` This worked perfectly fine. My problem is when I try to use this same function in C++. It fails at compiling with the error: ``` error: invalid conversion from ‘void*’ to ‘void* (*)(void*)’ [-fpermissive] *status = pthread_create(&new_thread, NULL, function, NULL); ``` Is there any reason that this works / compiles in C but not C++?
Implicit type conversions in C++ are much more strict than in C. Thevoid * functionparameter can't be used as function pointer in C++ or C... You needvoid* (*function)(void*)in your function prototype.
``` #include <stdio.h> int main() { int a = -1, b = -10, c = 5; if (a > b) printf("Hello World"); else printf("Get out World");;;;;; } ``` Can anybody tell me why line number 8 still works, with multiple semicolons?
Anempty statementis legal in C. Since;is thestatement terminator, multiple;are syntactically valid. Sometimes this is even useful: such as thefor (;;) {/*code here*/}idiom. (Although some compilers will warn you in appropriate instances). Do note that, conceptually at least, the excess;in that line arenotpart of theifblock.
This question already has answers here:Platform independent size_t Format specifiers in c?(3 answers)Closed7 years ago. I'm using Visual Studio 2015 to build a project on 32bit platform and on 64 bit platform. Sizeof returns an unsigned int in the 32 bit platform and an unsigned __int64 in the 64 bit platform. I have the following code : ``` printf ("limit is %u. \n",sizeof(var)); ``` I need to compile the same code on both platforms. Using the format specifier %u gives a warning in 64bit, using %I64u gives a warning in 32bit. Is there a way to use a formatspecifier on both platforms without writing the printf 2 times (with ifdef _WIN32). I have a lot of these warnings in my project. This would be a lot of work and wouldn't look 'clean'.
Thetypeofsizeofis asize_t. Use%zuas the format specifier for that type. It's guaranteed to be well-defined for all platforms.
The below code snippet is the wrong one.......but seems to work correctly ``` #include <stdio.h> void fun(char* msg); int main() { char* str = "Hello"; printf("%s\n",str); fun(&str); printf("%s\n",str); return 0; } void fun(char* msg){ *msg = "World"; } ``` And now the correct code snippet ``` #include <stdio.h> void fun(char** msg); int main() { char* str = "Hello"; printf("%s\n",str); fun(&str); printf("%s\n",str); return 0; } void fun(char** msg){ *msg = "World"; } ``` The objective of the above code is to modify the value of str.Both codes produce the same output but why does the wrong code seems to work correctly in this case.
The first one should not compile, because&stris achar**, but the function is declared to take achar*. Additionally, in*msg = "World";,"World"is achar*but*msgis a singlechar.
Consider the following snippet: ``` int func(char *ptr); ... n += func(p + n); ``` Does this code yield undefined behaviour, since the function's argument depends on lvalue? I'd assume that a compiler would calculate a result of function, and then incrementp + n, or this probably is compiler specific?
There is a sequence point before a function enter in function call. It means that every value computation and the side effects associated with an argument are completed before function entered in a function call. C11-§6.5.2.2/10: There is a sequence point after the evaluations of the function designator and the actual arguments but before the actual call. So, in case of ``` n += func(p + n); ``` p + nwill be calculated before the function call.
I want to implement a real time clock and timer , that prints on screen current time like this. : " HOURS:MINUTES:SECONDS " Is it safe to use : ``` While(1){ .....Do sth sleep(1); .....Do sth } ``` and then ``` seconds+=1; ``` For measure of one second pass?
You will have to check whether in your particular embedded system, sleep(1) will sleep the system for 1 second. In many of the embedded boards I have used, sleep takes the argument in milliseconds. So for 1 second sleep you would have to use sleep(1000). If you are not too worried about accuracy then yes you can use this method. however, this will not be as accurate as you using a timer or an RTC. so for example if you want your system to do something when seconds reaches 30, a better way might be to setup a timer or an RTC alarm (based on what your embedded platform has) to more accurately measure out that time.
why is the while loop written in this code with no body? what does it do? The index and length are both integers and I am reading from a txt file. ``` // ignore alphabetical strings too long to be words if (index > LENGTH) { // consume remainder of alphabetical string while ((c = fgetc(fp)) != EOF && isalpha(c)); // prepare for new word index = 0; } ```
Once it has parsed string of lengthLENGTH, it should ignore all the subsequent characters. Thus, in the body of the while loop: ``` c = fgetc(fp)) != EOF //get c from file pointer and check if it is not EOF isalpha(c) //and also it is an alphabet because alphabets can only make a word ``` If both conditions are true, keep parsing and ignoring. Moment you encounter a character other than alphabet or just an EOF, reset index and ma be go to next line.
I am going through the InterfacingWithCcookbookfrom Kx, and trying to create a mixed list of two symbols, then append a symbol to it. This keeps crashing my kdb process when I load it in a shared object. So this simple code crashes ``` K msgs = knk(2, ktn(KS, 0), ktn(KS, 0)); K syms=kK(msgs)[0]; S sym=ss("IBM"); js(&syms, sym); <-- this line seg faults ``` But this code not using a list works just fine ``` K syms=ktn(KS,0); S sym=ss("IBM"); js(&syms,sym); ``` The way I understand it is that knk gives me a mixed list, and I can access elements of that list using kk function. What am I missing here?
Found the answer. I was using KXVER version 3 when my kdb version/libs/includes were version 2. I changed that to two and it works fine now. In case it helps someone.
This question already has answers here:How do function pointers in C work?(12 answers)Closed7 years ago. What does this c code do? ``` { int (*func)(); func = (int (*)()) code; (int)(*func)(); } ``` Especially I confused about subj.
It's a cast to a function pointer. The sequenceint (*)()is for a function pointer that takes an indeterminate number of arguments, and returns anint. Wrapping it in parentheses like(int (*)()), when combined with an expression, is casting the result of the expression. The code you present, with comments: ``` // Declare a variable `func` which is a pointer to a function int (*func)(); // Cast the result of the expression `code` and assign it to the variable `func` func = (int (*)()) code; // Use the variable `func` to call the code, cast the result to `int` (redundant) // The returned value is also discarded (int)(*func)(); ```
From this page:http://linux.die.net/man/2/mprotect I understand the flags except for PROT_EXEC. What is the effect of calling ``` mprotect(ptr, size, PROT_EXEC); ```
From the manual page you link to: PROT_EXECThe memory can be executed. It marks the memory as executable, meaning it can contain code you can call and run.
I am using ffmpeg to decode videos. I am aware that the error I am getting is due to the frame/sliceHeader is decoded and the Picture Parameter Set information is not there. I am just curious if anyone knows a way to get rid of this error? My video is successfully decoding but in the debugger this error makes the metadata hard to read. The error is : ``` non existing PPS 0 referenced decode_slice_header error no frame! ``` ******** My code is in C ******
Check the FFmpegloggingfacilities - you can useav_log_set_callbackto provide your own logging callback and either just ignore everything, or filter by log level, it is up to you.
``` #include <stdio.h> int main(void) { double x = 0.12345678901234567890123456789; printf("%0.16f\n", x); return 0; }; ``` In the code above I'm initializingxwith literal that is too large to be represented by the IEEE 754 double. On my PC with gcc 4.9.2 it works well. The literal is rounded to the nearest value that fits into double. I'm wondering what happens behind the scene (on the compiler level) in this case? Does this behaviour depend on the platform? Is it legal?
When you writedouble x = 0.1;, the decimal number you have written is rounded to the nearestdouble. So what happens when you write0.12345678901234567890123456789is not fundamentally different. The behavior is essentially implementation-defined, but most compilers will use the nearest representabledoublein place of the constant. The C standardspecifiesthat it has to be either thedoubleimmediately above or the one immediately below.
Supposestruct Ais a structure of Linux kernel code, and there may be many instances ofstruct Abeing created and destroyed in a running Linux kernel, How can I know the number of instances ofstruct Aexisting right now?
In general you can't, unless you can see that the structure is only instantiated in a single way (if there is a constructor/factory function). For structures often used on the stack, there is typically no such function (although it's certainly possible since structure instances can be returned as values). C doesn't provide any way to do this automatically, you'd have to build it yourself which would require finding all places where instances are created.
What actuallybelongsto the "character type" in C11 — besidescharof course? To be more precise, the special exceptions for the character type (for example thatanyobject can be accessed by an lvalue expression of character type — see §6.5/7 in C11 standard), to which concrete types do they apply? Theyseemto apply touint8_tandint8_tfromstdint.h, but is this guaranteed? On the other hand gcc doesn't regardchar16_tfromuchar.has a "character type".
Onlychar,signed charandunsigned char1. The typesuint8_t,int8_t,char16_t, or any type in the formintN_torcharN_t, may or may not be synonyms for a character type. 1(Quoted from: ISO/IEC 9899:201x 6.2.5 Types 15)The three types char, signed char, and unsigned char are collectively called the character types.
This question already has answers here:Why is the data type needed in pointer declarations?(8 answers)Closed7 years ago. What actually happens while declaring a pointer of a specific type? Is there any use to specify a type to a pointer other than pointer Arithmetic or Indexing?
One of the reasons could be that when you dereference the pointer we should know how many bytes to read right? Dereferencingcharpointer would imply taking one byte from memory while forintit could be 4 bytes.
Can I assign one sempahore to other semaphore, will both behave as the same, for eg.(this vxworks code) ``` mySemId = semCreate(...) tempSemId = mySemId; semTake(tempSemId,...); ... semGive(mySemId). ``` will the above code snippet work in locking the resource. Secondly, if this works is there a coding standard or practice that does not allow this kind of processing.
vxWorks semaphore IDs are copyable, and the copy is "just as good" as the original, so the code sample shown here is not wrong. It does not seem a particularly good idea, though. It's hard to tell from this snippet what the entire code looks like, and in a larger block of code, I think it would be difficult to tell which semaphore(s) are being Taken and which are being Given. (This is not a C language question: vxWorks semaphores are mainly usablefromC, but are notdefined bythe language.)
This question already has an answer here:Go equivalent of a void pointer in C(1 answer)Closed7 years ago. I am already familiar with C and I've been working on improving my Golang skills. Anyone know how to create something reminiscent of a void * in Golang? For example: ``` struct Node { void *data; struct Node *next; struct Node *prev; } ```
You have to use an empty interface, (interface {}), and modify it to what you want. (Source). This is known as an empty interface, and it can embodyanytype.
I'm working on an online CTF challenge and I need to somehow give raw bytes to this compiled C program. I've tried the following using python: ``` ./program `python -c 'print "\x00\x00"'` ``` ... but for some reason that doesn't seem to be giving me what I'm expecting. Is there some conversion/formatting that's happening that I'm not aware of? I would expect this to give raw bytes as an argument.
Command line args in C are an array of 0 terminated strings. There is no way to pass "raw bytes" (any 0 byte won't behave as expected). I'd suggest passing either reading the bytes from stdin or from a file specified on the command line.
I don't understand howthis xxhashfunction is able to add larger values than uint32 can store. Can someone explain why this wizardry is possible? ``` static const U32 PRIME32_1 = 2654435761U; static const U32 PRIME32_2 = 2246822519U; ... U32 v1 = seed + PRIME32_1 + PRIME32_2; ```
The standard requires that the standard unsigned integral types handle overflow/underflow by 'wrapping' the value moduloFOO_MAX + 1. (e.g.UINT32_MAXis the macro holding the maximum value ofuint32_t) AssumingU32refers touint32_t, the additions are performed modulo4294967296.
I don't understand howthis xxhashfunction is able to add larger values than uint32 can store. Can someone explain why this wizardry is possible? ``` static const U32 PRIME32_1 = 2654435761U; static const U32 PRIME32_2 = 2246822519U; ... U32 v1 = seed + PRIME32_1 + PRIME32_2; ```
The standard requires that the standard unsigned integral types handle overflow/underflow by 'wrapping' the value moduloFOO_MAX + 1. (e.g.UINT32_MAXis the macro holding the maximum value ofuint32_t) AssumingU32refers touint32_t, the additions are performed modulo4294967296.
I want to make a circular counter in C programming. First variable can store value from 0-3. Second variable asks the value from user (from 0-3). Third variable asks user to move either left or right If third variable is left the second variable should move left: ``` 3->2 2->1 1->0 0->3 ``` Similarly if third variable is right the second variable should move right: ``` 0->1 1->2 2->3 3->0 ```
``` #include <stdio.h> int main(void) { int max = 3, num, i; num = 0; for (i = 0; i < 10; i++) { printf("%d\n", num); num = (num + 1) % (max + 1); } puts("--"); num = max; for (i = 0; i < 10; i++) { printf("%d\n", num); num = (max - -num) % (max + 1); } return 0; } ``` Output: ``` 0 1 2 3 0 1 2 3 0 1 -- 3 2 1 0 3 2 1 0 3 2 ```
I would like a check box to be automatically unchecked when a certain value is reached. But I can't find an option to set the state of a check box
Send it aBM_SETCHECKmessage: ``` SendMessage(hWndOfCheckbox, BM_SETCHECK, BST_UNCHECKED, 0); ``` Alternatively, use theButton_SetCheckmacro, that expands to the same call toSendMessage(but doesn't expose unused formal parameters): ``` Button_SetCheck(hWndOfCheckbox, BST_UNCHECKED); ```
As far as I know, the derefence operator*returns the value stored in the pointer address. What I'm confused by is the behavior when the operator is used with pointer of an array. For example, ``` int a[4][2]; ``` Thenais internally converted to pointer of first element of array of 4 elements of 2 ints. Then which value does*areturn? I'm really confused!
The type ofaisint[4][2], so the type of*a(or equivalentlya[0]) isint[2]. It isnotthe same asa[0][0]. If you do this: ``` int a[4][2]; printf("%d\n",*a); ``` The compiler will tell you this: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘int *’ Since an array (in this case one of typeint [2]) is being passed to a function, it decays to a pointer to the first element in this context. If on the other hand you had**a, that is equivalent toa[0][0]and has typeint.
I can successfully compile and run the LED blinky example from my Windows-7 using mbed online IDE, which runs on my NUCLEO F091C board. How can I implement printf? There's an example 'Nucleo_printf' which outputs to serial. However, I haven't found instruction on how to get serial from Nucleo to PC.
I found the answer:https://developer.mbed.org/handbook/SerialPC Turns out, serial outputs through the Nucleo's USB port to a virtual COM port on Windows-7.
I am trying to load a simple c function I wrote to lua so I can use it in my lua coding. I'm trying to compile it with:gcc ./main.c -llua -ldl -lm -o lualibland I'm receiving an error:ld: library not found for -lluaclang: error: linker command failed with exit code 1 (use -v to see invocation) Say I remove -llua, then all my luaL_checkinteger/luaL_setfuncs functions are undefined symbols so I'm assuming I need to compile with the lua library. Any ideas on how I can find this library to compile with my c code? I'm running lua 5.2
You are most probably missing lua shared library (liblua). E.g. On my distro, correct package to install would beliblua50-dev_5.0.3-7_amd64.deb(or similar)
I'm trying to understand a C program which includes a .h file with the line ``` #define random ((float) rand() / (float)((1 << 31) - 1)) ``` The C program also includes<math.h>. My guess is that this simply produces a random number from a uniform distribution on the interval [0,1]; is this correct?
Ostensibly yes. But it's wrong in two principal ways: UseRAND_MAXinstead. That's what it's there for. It might be much smaller than1 << 31 - 1.1 << 31will give youundefined behaviouron a platform with a32 bitintor less, which is remarkably common. Don't do that! Note that if you don't want to ever recover the value 1, (as is often the case), then useRAND_MAX + 1.0on the denominator. The1.0forces evaluation in floating point: you run the risk of overflowing an integral type if you writeRAND_MAX + 1.
I have learnt that logical operator are guaranteed that their evaluation are from left-to right but I was wondering what are the order of evaluation of comparison operator. For instanceexpression1 < expression2in other words is it guaranteed thatexpression1will be first evaluated beforeexpression2.
According to the standard: J.1 Unspecified behaviorThe following are unspecified:....— The order in which subexpressions are evaluated and the order in which side effects take place, except as specified for the function-call(),&&,||,?:, and comma operators (6.5).
i am writing a driver code, to read some register values from x86., when i ran my user space application i got the below error. ioctl:Inappropriate ioctl for device here is the code sniff.. ``` fd = open_drvfile(); if(ioctl(fd, IOCTL_MSR_CMDS, (long long)msr_start) == -1 ) { perror("ioctl:"); exit (0); } ``` and open_drvfile() just open(create and open) the char file as below ``` fd = open("/dev/" DEV_NAME, O_RDWR|O_CREAT); if (fd == -1) { perror("Failed to open /dev/" DEV_NAME); } return fd; ``` can some one point where i made mistake on this?
A char device implies that it shall be created withmknod(), and not withO_CREATunderopen()flags(which will create a regular file, not a char device). (see question comments).
I'm trying to understand a C program which includes a .h file with the line ``` #define random ((float) rand() / (float)((1 << 31) - 1)) ``` The C program also includes<math.h>. My guess is that this simply produces a random number from a uniform distribution on the interval [0,1]; is this correct?
Ostensibly yes. But it's wrong in two principal ways: UseRAND_MAXinstead. That's what it's there for. It might be much smaller than1 << 31 - 1.1 << 31will give youundefined behaviouron a platform with a32 bitintor less, which is remarkably common. Don't do that! Note that if you don't want to ever recover the value 1, (as is often the case), then useRAND_MAX + 1.0on the denominator. The1.0forces evaluation in floating point: you run the risk of overflowing an integral type if you writeRAND_MAX + 1.
I have learnt that logical operator are guaranteed that their evaluation are from left-to right but I was wondering what are the order of evaluation of comparison operator. For instanceexpression1 < expression2in other words is it guaranteed thatexpression1will be first evaluated beforeexpression2.
According to the standard: J.1 Unspecified behaviorThe following are unspecified:....— The order in which subexpressions are evaluated and the order in which side effects take place, except as specified for the function-call(),&&,||,?:, and comma operators (6.5).
i am writing a driver code, to read some register values from x86., when i ran my user space application i got the below error. ioctl:Inappropriate ioctl for device here is the code sniff.. ``` fd = open_drvfile(); if(ioctl(fd, IOCTL_MSR_CMDS, (long long)msr_start) == -1 ) { perror("ioctl:"); exit (0); } ``` and open_drvfile() just open(create and open) the char file as below ``` fd = open("/dev/" DEV_NAME, O_RDWR|O_CREAT); if (fd == -1) { perror("Failed to open /dev/" DEV_NAME); } return fd; ``` can some one point where i made mistake on this?
A char device implies that it shall be created withmknod(), and not withO_CREATunderopen()flags(which will create a regular file, not a char device). (see question comments).
I have basic query about ioremap used to map device IO addressed into kernel's virtual memory. I would like to know if returned address from ioremap is passed to routines like virt_to_phys(), would it return back Device IO address ? Thanks
virt_to_phys()is only valid for virtual addresses within the kernel linear map, since it's just some fast address arithmetic, not a full software table walk. The linear map normally only covers RAM. The virtual address returned byioremap(), however, will usually (probably always, but I don't have the patience to check every implementation) be a vmalloc address, so if you pass that tovirt_to_phys()you'll get nonsense back.