question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
This question already has answers here:fork() branches more than expected?(3 answers)Closed9 years ago.
Can anyone, please, explain how does this code work ?
```
int main()
{
printf("Hello");
fork();
printf("World");
}
```
Prints:
```
HelloWorldHelloWorld
```
My exact question is, whyhellois printed twice. ... |
The reason is: buffered output. "Hello" is in the buffer but not yet put out when you do the fork, so the forked process starts with the same buffer including the same word "Hello". Then, both the parent and the child output "World" so the total output is "HelloWorld" for both of them.
|
I have a file (pointed to by *data) which begins with a struct.
I would like to get to the value of nsectionheaders in memory so that I can use it.
I've tried this, but it's returning a strangely large negative value. How do I get it to return the right value?
```
void read_file_header(void *data) {
int offset... |
The line
```
memcpy(&num_sec_headers, &pointer, sizeof(short));
```
is incorrect. You are taking the address of the pointer, instead of just using pointer:
```
memcpy(&num_sec_headers, pointer, sizeof(short));
```
|
I was solving C programming Questions and I came across this
```
#include<stdio.h>
int main()
{
int x=100,y=200,z=300;
printf("%d..%d..%d");
}
```
I expected an error but the output was300..200..100
Can anyone explain this output?
|
%dinprintfexpectsinttype argument. You are passing no arguments. Its a constraint violation and ultimately your program invokesundefined behavior.
|
I use ncurs for an application which dispays data to users in real-time.
the user can do string input of normalchartype. e.g a-z, A-Z 0-9 etc. So I cannot use those keys to do other things like change windows or quit.
Now it seemed like a good idea to use the F-keys but someKEY_F(x)are not recognized on some termina... |
Personally I favour using one of the modifier keys with letters, it is something of a defacto standard in ncurses apps to use the letter keys with control held down for special functions.
This approach instantly gives you 26 * 2 + 9 hotkey combos for special functions, plenty for most apps.
Please take a look at gnu... |
I have just started learning C through book K&R.
This is my code.
```
#include <stdio.h>
int main (){
int c;
char value = ((c = getchar()) != EOF);
while (value){
printf(" %c\n", c);
printf("%d :: value : %d\n",__LINE__,value);
value = ((c = getchar()) != EOF);
}
return 0;
... |
Not twice it's only once. Another one is your input.
For example, you input 'a', the console will display 'a' first, then you program will print one more time when run to the statement:
```
printf(" %c\n", c);
```
|
This question already has answers here:fork() branches more than expected?(3 answers)Closed9 years ago.
Can anyone, please, explain how does this code work ?
```
int main()
{
printf("Hello");
fork();
printf("World");
}
```
Prints:
```
HelloWorldHelloWorld
```
My exact question is, whyhellois printed twice. ... |
The reason is: buffered output. "Hello" is in the buffer but not yet put out when you do the fork, so the forked process starts with the same buffer including the same word "Hello". Then, both the parent and the child output "World" so the total output is "HelloWorld" for both of them.
|
I have a file (pointed to by *data) which begins with a struct.
I would like to get to the value of nsectionheaders in memory so that I can use it.
I've tried this, but it's returning a strangely large negative value. How do I get it to return the right value?
```
void read_file_header(void *data) {
int offset... |
The line
```
memcpy(&num_sec_headers, &pointer, sizeof(short));
```
is incorrect. You are taking the address of the pointer, instead of just using pointer:
```
memcpy(&num_sec_headers, pointer, sizeof(short));
```
|
I was solving C programming Questions and I came across this
```
#include<stdio.h>
int main()
{
int x=100,y=200,z=300;
printf("%d..%d..%d");
}
```
I expected an error but the output was300..200..100
Can anyone explain this output?
|
%dinprintfexpectsinttype argument. You are passing no arguments. Its a constraint violation and ultimately your program invokesundefined behavior.
|
I use ncurs for an application which dispays data to users in real-time.
the user can do string input of normalchartype. e.g a-z, A-Z 0-9 etc. So I cannot use those keys to do other things like change windows or quit.
Now it seemed like a good idea to use the F-keys but someKEY_F(x)are not recognized on some termina... |
Personally I favour using one of the modifier keys with letters, it is something of a defacto standard in ncurses apps to use the letter keys with control held down for special functions.
This approach instantly gives you 26 * 2 + 9 hotkey combos for special functions, plenty for most apps.
Please take a look at gnu... |
I have just started learning C through book K&R.
This is my code.
```
#include <stdio.h>
int main (){
int c;
char value = ((c = getchar()) != EOF);
while (value){
printf(" %c\n", c);
printf("%d :: value : %d\n",__LINE__,value);
value = ((c = getchar()) != EOF);
}
return 0;
... |
Not twice it's only once. Another one is your input.
For example, you input 'a', the console will display 'a' first, then you program will print one more time when run to the statement:
```
printf(" %c\n", c);
```
|
Suppose I have, in C99,for(int j=0; j < t->k; j++),t->kdoes not change throughout the loop iteration. Does the compiler optimize this line, or there will be one dereferencing operation per loop iteration?
In other words, would
```
tmpk = t->k;
for(int j = 0; j < tmpk; j++)
```
be better for a large number of iterat... |
In the general case this depends on whethertis declaredrestrict; in the absence of an explicit aliasing restriction the compiler cannot assume that no other pointer provides a path to modifyk.
Of course, if the compiler can prove thatt->kis invariant by inspection of the loop body, it may choose to move the dereferen... |
I'm using Code::Blocks 13.12 IDE on Xubuntu 14.04 for writing C and C++ code, and in spite of correctly finding header files by the compiler, the IDE is not capable to automatically open included outside of the project tree files with "Open include file" command, including standard headers.
Is there any C::B configur... |
It seems to be a bug in the "Code completion" plugin which is resolved after plugin is disabled and enabled again from the "Manage Plugins ..." dialog.
|
I have the next code and I don't understand the pointer to pointer assignment in "dest" variable. Could someone please explain the meaning of this code?
```
#include <string.h>
#include <stdlib.h>
int main(void){
char s1[] = "012345678";
char dest;
dest = *(char * ) malloc(strlen(s1));
}
```
Thank you
|
This code doesn't make sense. It usesmallocto allocate memory of size 9, and then puts the first character of that allocated memory into dest. The problem is that the first character of the allocated memory can be anything, since allocated memory is not guaranteed to be initialized.
|
What happens if we free an automatic variable usingfree()?
What about in the following code: ifnisstaticdoes it get automatically free'd after the last loop iteration, can wefreeit, or what?
```
for(count = 0; count < 5; count++) {
static int i += 1
}
```
|
What happens if we free an automatic variable usingfree()?
It will invokeundefined behavior.
Argument tofreemust be a pointer that was returned by memory allocation function(malloc,calloc,realloc). The argument may also be a null pointer, in which case the call offreehas no effect.
|
The following piece of C code compiles under gcc 4.7, on a Debian (run withgcc -c filename.c)
```
typedef int array_type[3];
int a[] = {1,2,3};
int* asd1(void){
return a;
}
array_type* asd2(void){
return &a;
}
```
Instead of using thetypedefI want to use the actual type. However, if I replacearray_type*with ... |
```
int (*asd2(void))[3]{
return &a;
}
```
seecdecl
|
Is Enum's inCreplacement like#define?
For example if I have a flag list like:
```
enum{
STATE_0 = 0x1<<0,
STATE_1 = 0x1<<1,
STATE_2 = 0x1<<2,
STATE_3 = 0x1<<3,
.
.
.
}
```
when the code compiled will the values have the evaluated results of statement or exact statement like using#define.
For example will ST... |
Enums in C are not working like #defines. Enums are part of the language and are not processed by the pre-processor, soSTATE_2will be evaluated as 4.
|
Is there any C or C++ function which can produce the same output of this python code (SHA512 with salt)?
```
import crypt;
crypt.crypt('test', '$6$Salte2Ck$')
```
|
Hereare some explanations to Python'scryptfunction.So I think what you are looking for is the C functioncryptfromunistd.h.
|
I want to write a program in C that performs some function and then sleeps for some minutes.
During this sleep period I would like to do something and exit if a key is pressed.
```
int main()
{
while(1)
{
/*body*/
sleep(300);
}
/*some lines here*/
return 0;
}
```
Is there anyway t... |
Just don't sleep for 300 seconds but rather 300 x for 1 second and check for key press:
```
int main()
{
while(1)
{
/*body*/
for ( int i=0; i<300; i++ )
{
if (keypressed())
doSomething();
}
}
/*some lines here*/
return 0;
}
```
EDIT: Why... |
So I have a C++ project with a directory full of test source files and I'm writing a makefile to make them all at once. Instead of compiling each file separately, is there a way I can cd into my test directory and loop through each file, compiling them one by one?
Thanks in advance for the help!
|
makefile implicit rule can be used to make all the files which is available in the folder. Also wildcard function can be used to get the .c or .cpp files which is available in particular folder.
```
%.o : %.cpp
$(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@
```
Example:
```
FILENAME:= $(patsubst %.c,%.o,$(wildcard *.... |
The code I have has the following loops:
```
for (i = A[x]; i < N; i = i | (i + 1))
```
and,
```
for (i = A[x]; i >= 0; i = (i & (i + 1)) -1 )
```
I don't really understand these update statements. Are these clever ways of doing something trivial?
|
When code confuses you, experiment on it.
```
$ cat test.c
#include <stdio.h>
int main(void)
{
for (unsigned int i = 0; i < 256; i = i | (i + 1))
printf(" %04x", i);
putchar('\n');
return 0;
}
$ gcc -std=c99 test.c
$ ./a.out
0000 0001 0003 0007 000f 001f 003f 007f 00ff
```
So the first expression that con... |
Can I write a variable sized array using the following code?
I have executed it on Fedora. I used a pointeraand integerbto create the array,
so can I say that this array is a dynamic array?
```
main()
{
int * const a;
int b;
a[b];
b=5;
int i;
for(i=0;i<5;i++)
{
printf("%d\n",a... |
No, you can't create variable-length array using this code. When you use
```
int b;
```
bcan have any value. It can be 0, 4294967295, or any other number. Then, when you use
```
a[b];
```
acan have any random length each time use execute the program.
Next thing:awill not change it's size when you changebvalue:
`... |
Hey what will be the the output of the following code, it is not working as it should.
```
int j=65;
printf("j>=65?%d:%c",j);
```
In this case it should print:j>=65, and then match the next%dwith thejso print65, and then%cis printinglhow thelis printed.
|
Instead of
```
Printf("j>=65?%d:%c",j);
```
there has to be at least
```
printf("j>=65?%d:%c",j);
```
The code has undefined behaviour because the number of format specifiers is greater than the number of following arguments.
I think you mean the following
```
printf( j >= 65 ? "%d" : "%c", j );
```
in this cas... |
Let's say we have anarray of m elementsand we want to changerandomlythe position ofexactly nof them, where of course 2 <= n <= m.
For example: if we have this array of10ints {1 2 3 4 5 6 7 8 9 10} and we ask for4of its elements to change positions randomly, a result could be {3 2 1 4 5 6 10 8 9 7}
What is the simple... |
Step1). Generate a list of n random unique numbers between 1 and m. This list should NOT be sorted. Eg, for your example, the list could have been [10,7,1,3]
Step 2) do something like :
```
int save = array[list[0]];
For (i=0; i<n-1; i++) {
Array[list[i]] = array[list[i+1]];
}
Array[list[n-1]] = save;
```
Edi... |
So I have a C++ project with a directory full of test source files and I'm writing a makefile to make them all at once. Instead of compiling each file separately, is there a way I can cd into my test directory and loop through each file, compiling them one by one?
Thanks in advance for the help!
|
makefile implicit rule can be used to make all the files which is available in the folder. Also wildcard function can be used to get the .c or .cpp files which is available in particular folder.
```
%.o : %.cpp
$(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@
```
Example:
```
FILENAME:= $(patsubst %.c,%.o,$(wildcard *.... |
The code I have has the following loops:
```
for (i = A[x]; i < N; i = i | (i + 1))
```
and,
```
for (i = A[x]; i >= 0; i = (i & (i + 1)) -1 )
```
I don't really understand these update statements. Are these clever ways of doing something trivial?
|
When code confuses you, experiment on it.
```
$ cat test.c
#include <stdio.h>
int main(void)
{
for (unsigned int i = 0; i < 256; i = i | (i + 1))
printf(" %04x", i);
putchar('\n');
return 0;
}
$ gcc -std=c99 test.c
$ ./a.out
0000 0001 0003 0007 000f 001f 003f 007f 00ff
```
So the first expression that con... |
Can I write a variable sized array using the following code?
I have executed it on Fedora. I used a pointeraand integerbto create the array,
so can I say that this array is a dynamic array?
```
main()
{
int * const a;
int b;
a[b];
b=5;
int i;
for(i=0;i<5;i++)
{
printf("%d\n",a... |
No, you can't create variable-length array using this code. When you use
```
int b;
```
bcan have any value. It can be 0, 4294967295, or any other number. Then, when you use
```
a[b];
```
acan have any random length each time use execute the program.
Next thing:awill not change it's size when you changebvalue:
`... |
Hey what will be the the output of the following code, it is not working as it should.
```
int j=65;
printf("j>=65?%d:%c",j);
```
In this case it should print:j>=65, and then match the next%dwith thejso print65, and then%cis printinglhow thelis printed.
|
Instead of
```
Printf("j>=65?%d:%c",j);
```
there has to be at least
```
printf("j>=65?%d:%c",j);
```
The code has undefined behaviour because the number of format specifiers is greater than the number of following arguments.
I think you mean the following
```
printf( j >= 65 ? "%d" : "%c", j );
```
in this cas... |
Let's say we have anarray of m elementsand we want to changerandomlythe position ofexactly nof them, where of course 2 <= n <= m.
For example: if we have this array of10ints {1 2 3 4 5 6 7 8 9 10} and we ask for4of its elements to change positions randomly, a result could be {3 2 1 4 5 6 10 8 9 7}
What is the simple... |
Step1). Generate a list of n random unique numbers between 1 and m. This list should NOT be sorted. Eg, for your example, the list could have been [10,7,1,3]
Step 2) do something like :
```
int save = array[list[0]];
For (i=0; i<n-1; i++) {
Array[list[i]] = array[list[i+1]];
}
Array[list[n-1]] = save;
```
Edi... |
I was doing an example of the C language and tried example shown below. I thought it should print the stringStudy Tonight strings, but it is giving the outputStudy Tonight stringsStudyTonightWhy it is so ? I thought that even thechar str[7]array size is right.
```
#include <stdio.h>
#include <stdlib.h>
/*
*
*/
in... |
This:
```
char str[7]="strings";
```
Is already undefined behavior, as the initializer is 7 characters of text plus 1 null terminator, so you need 8 bytes of storage, not 7. Please turn on your compiler warnings and it will catch such trivial problems for you. If you use GCC or Clang, it's like this:
```
gcc -Wal... |
This question already has answers here:Do I cast the result of malloc?(29 answers)Closed9 years ago.
Why do we castmalloc, as in the following?
```
ptd = (double *) malloc(max * sizeof(double));
```
What ismalloc's normal return type? Why do weneedto cast it?
|
From a standard guide:
Declaration:
```
void *malloc(size_t size);
```
Allocates the requested memory and returns a pointer to it.
The requested size is size bytes.
The value of the space is indeterminate.
On success a pointer to the requested space is returned.
On failure a null pointer is returned.
That shoul... |
There's a presentation (video,slides) that demonstrates the use of QML in developingncursesapplications.
I've searched everywhere, but I couldn't find any documentation on the subject, does anyone have any idea on how to achieve what was done in the presentation?
|
Qt can be (Ncurses and Qt Interoperability) used to handle the async I/O details of an ncurses app even without QML nor any other high-level frameworks.
You could also expose some C++ class framework for text interfaces via QML. For example, as was done in the presentation, you could exposeCDK - the Curses Developmen... |
I'm getting segmentation fault with my following code. This is the max size in which I get no segmentation errorSIZE = 1000000if I increase it one zero more, I got segmentation error.
```
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <inttypes.h>
uint64_t SIZE = 10000000;
uint64_t getsum(int dat... |
You are exceeding the available stack space, therefore causing a segfault. If thedataarray is so big, it shouldn't be with automatic storage.
You should either define itstatic, globally, or allocate it on the heap.
|
Today I made a typo, and then found below code can be compiled successfully:
```
#include <stdio.h>
int main()
{
int i;
for (i=0;1,2,3,4,5;i++)
printf("%d\n", i);
}
```
I don't understand why
```
1,2,3,4,5
```
can be treated as a condition?
|
Yourforcondition is the expression1,2,3,4,5. This expression is evaluated usingC's comma operatorand yields5. The value5is a valid boolean expression that is true, therefore resulting in an infinite loop.
|
Currently, I have an application that does:
execlp(java_exec, java_args, etc, etc);
to launch a jar file.
Is there a way to also have it prependLD_PRELOAD="mylib.so"?
I couldn't find a way to tellexeclpto do:LD_PRELOAD="mylib.so" java -jar foo.jar
Any ideas how I can achieve this in C or C++ on Linux?
|
You should probably addLD_PRELOAD=mylib.soto*envp,execlpe()'s fourth arg.
|
This question already has answers here:What is the function of this statement *(long*)0=0;?(4 answers)Closed9 years ago.
So the line of code in question is:
```
*((int*)(0))=1;
```
Because I have so little experience with C/C++ and haven't tried very hard, I don't understand this simple expression. What does it mea... |
It's meant to crash the program, typically useful during debugging.
It'll dereference the NULL pointer and attempt to assign a value to that memory, which is theoretically just undefined behavior, but will result in an access violation exception on 99% of systems.
Typically, it's found in cases such as:
```
if ( !F... |
I've written plenty of C before, but I don't recognize this syntax:
```
static const char *names[] = {
[BOND_MODE_ROUNDROBIN] = "load balancing (round-robin)",
[BOND_MODE_ACTIVEBACKUP] = "fault-tolerance (active-backup)",
[BOND_MODE_XOR] = "load balancing (xor)",
[BOND_MODE_BROADCAST] = "fault-toleran... |
It's calleddesignated initializers, which is introduced in C99. GCC also supports it as an extension.
It's used to initialize structures and arrays, seeDesignated Initializersfor detail.
|
I have a problem understanding the output of the code. Any explanation please...
```
#include<stdio.h>
void main()
{
int x=2,y=5;
x*=y+1;
printf("%d",x);
}
```
The output is as 12. But as per my understandingx*=y+1;isx=x*y+1;but as per operator precedencex*yshould be evaluated followed byadding 1so it... |
It will be evaluated as
```
x = x * (y + 1);
```
so
```
x = 2 * ( 5 + 1 )
x = 12
```
|
I am trying to understand below code output:
```
int counter = 0;
int aMatrix[5][5];
register int *aPtr;
int i, j;
for (i=0; i<5; i++)
for (j=0; j<5; j++)
aMatrix[i][j] = counter++;
aPtr = &aMatrix[1][1]; printf("%d\n", aPtr[2]);
```
Referring to the sample code above, what will be the value of "aPtr[2]", aft... |
After the assignment, the matrix becomes:
```
0 1 2 3 4
5 6 7 8 9
...
```
With
```
aPtr = &aMatrix[1][1];
```
aPtr[0]is the same asaMatrix[1][1], soaPtr[2]is the same asaMatrix[1][3], which is8in the matrix.
|
I was wondering if there is a ALSA function that can tell which sample frequencies are supported by the recording using ALSA?
|
That would be thesnd_pcm_hw_params_get_rate_maxfunction.
For an example, seehw_params.c.
|
I have a large buffer of strings (basically 12GB) from a C app.
I would like to create PyString objects in C for an embedded Python interpreter without copying the strings. Is this possible?
|
I don't think that is possible for the basic reason that Python String objects areembeddedinto the PyObject structure. In other words, the Python string object is the PyObject_HEAD followed by the bytes of the string. You would have to have room in memory to put the PyObject_HEAD information around the existing b... |
Data are stored in the file as it's should,but when i re-launch the program they get vanished, and the file size returns to 0.
Here's what's i came up with so far:
```
if (!fp) {
fp=fopen("data.txt", "wb");
}
```
but it's doesn't work.
Thank you!
|
Let's look at the documentation forfopen():
We can ignore thebinwb, because it just makes things run in a binary mode.
If we look at the description ofw, we can see that it says that it destroys the contents of an existing file with the same name. That's the behavior you are seeing.
Instead of that, you probably ... |
I am at a loss with what is happening here. I need to convert a float to an int16_t and back. Here is the syntax:
```
int16_t val = (int16_t)round((float)0xFFFE/100 * angle);
//and back
float angle = ((float)100/0xFFFE * val;
```
When I use an initial angle value of -0.093081, it converts back. But when I use 182... |
0xFFFEisalmostthe maximum 16-bit number; and only for anunsigned16-bit number, at that. If you divide it by 100 and then multiply by 182, it's definitely going to overflow.
Let's do it fully in base 10 for clarity (0xFFFE is 65534):
```
65534 / 100 * -0.093081 = -60.99970254
65534 / 100 * 182.241211 = 119429.95... |
This question already has answers here:Multiple Ternary Operators(7 answers)Closed9 years ago.
Is it possible to write the equivalent compound "if" statement using the "?" operator in C? I want to write an "if - else if - else" statement and was wonder if I could utilize the "?" operator.
I believe the regular synta... |
```
foo =
(bar == 42) ? answerToEverything :
(bar == 23) ? bigMike :
useless;
```
|
I was wondering if there is a ALSA function that can tell which sample frequencies are supported by the recording using ALSA?
|
That would be thesnd_pcm_hw_params_get_rate_maxfunction.
For an example, seehw_params.c.
|
I have a large buffer of strings (basically 12GB) from a C app.
I would like to create PyString objects in C for an embedded Python interpreter without copying the strings. Is this possible?
|
I don't think that is possible for the basic reason that Python String objects areembeddedinto the PyObject structure. In other words, the Python string object is the PyObject_HEAD followed by the bytes of the string. You would have to have room in memory to put the PyObject_HEAD information around the existing b... |
Data are stored in the file as it's should,but when i re-launch the program they get vanished, and the file size returns to 0.
Here's what's i came up with so far:
```
if (!fp) {
fp=fopen("data.txt", "wb");
}
```
but it's doesn't work.
Thank you!
|
Let's look at the documentation forfopen():
We can ignore thebinwb, because it just makes things run in a binary mode.
If we look at the description ofw, we can see that it says that it destroys the contents of an existing file with the same name. That's the behavior you are seeing.
Instead of that, you probably ... |
I am at a loss with what is happening here. I need to convert a float to an int16_t and back. Here is the syntax:
```
int16_t val = (int16_t)round((float)0xFFFE/100 * angle);
//and back
float angle = ((float)100/0xFFFE * val;
```
When I use an initial angle value of -0.093081, it converts back. But when I use 182... |
0xFFFEisalmostthe maximum 16-bit number; and only for anunsigned16-bit number, at that. If you divide it by 100 and then multiply by 182, it's definitely going to overflow.
Let's do it fully in base 10 for clarity (0xFFFE is 65534):
```
65534 / 100 * -0.093081 = -60.99970254
65534 / 100 * 182.241211 = 119429.95... |
This question already has answers here:Multiple Ternary Operators(7 answers)Closed9 years ago.
Is it possible to write the equivalent compound "if" statement using the "?" operator in C? I want to write an "if - else if - else" statement and was wonder if I could utilize the "?" operator.
I believe the regular synta... |
```
foo =
(bar == 42) ? answerToEverything :
(bar == 23) ? bigMike :
useless;
```
|
I have a .h and .c file for an embedded project, which I want to unit testing in C++.
In .c file there are variable declarations:
```
uint8_t foo __at "NOINIT";
```
g++ throws error.
Has anybody a solution for this problem? (I prefer solutions which leave the .c changed)
I tried to add switch to g++:
```
-D__at=;/... |
I am a trained professional. Don't try to repeat this at home.
```
gcc \
-D'var1(v,l)=v ## l' \
-D'var(v,l)=var1(v,l)' \
-D'__at=; const char* var(dummy_x_,__LINE__)='
```
|
I have to following C code:
```
a.b[(c+d(e,f,g)**i)]->j<-k
```
Now I have to add code to make it compile.
Most of that isn't a problem but what really irritates me is thed(e,f,g)**ipart.**ias I understand is a pointer to a pointer, but I don't know how to handle it directly after a function call.
|
Just break it down:
```
d(e,f,g)**i
FunctionCall d with params e,f,g
Multiplied by
pointer-dereferce of i
```
Or:
```
d (e,f,g) * (*i)
Func. Params Multiply value-stored-at-pointer
```
|
If I use gcc as a driver, call all my source files .c and .h, can I be sure that I wont have any C++ source in my sources? Are there any gcc parameters to make sure that he throws errors in case any c++ is encountered in the source?
I am especially paranoid about include files, because I am not 100% sure whether I in... |
GCC will figure out itself whether it's a C or a C++ source code. How? It scans the file extension the file you passed has.Theseare the extensions accepted.
In case you want to force a specific language, use the-xflag (documented in the link above). Furthermore, you may check whether the macro__cplusplusis defined.
|
System command is used to execute the dos shell commands using the c program asif they were executed directly on command prompt itself.
color command working on the dos shell when applied directly but fails when used by the system() function.
|
SinceCOLORis an internal command and not a program, thesystem()function (normally) cannot recognize it.
However, you can try by using theCMDprogram, with parameter/K, in this way:
```
system("CMD.EXE /K COLOR 63 ");
```
|
Suppose*ptrpoints to a variable. What does*ptr,&ptr, andptreach mean?
Many times, I get confused between them. Do anyone mind clarifying between those statements and give some concrete examples?
|
Take the following variables in a function.
```
int i = 0;
int* ptr = &i;
```
In the function, the memory layout could look something like:
Memory corresponding toi:
```
+---+---+---+---+
| 0 |
+---+---+---+---+
^
|
Address of i
```
Memory corresponding toptr:
```
+---+---+---+---+
| address of i |
... |
Is there a function to return a keysym from a string representation of the key?
for example,SDL_GetKeySym("d") == SDLK_d
I need this to read a keysym from a config file, and of course I'm usingSDL_GetKeyNameto get a string representation of the key and then saving it to the config file.
|
SDL2 adds theSDL_GetKeyFromNamefunction, which does the inverse ofSDL_GetKeyName.
|
I am doing a win32 program with C and I do not know how to do a enum and switch case with UNICODE.
I receive from the client a named pipe with this structure
```
typedef struct {
TCHAR UtilOrigem[10];
TCHAR Comando[3]; // Comando
TCHAR Argumento1[10];
}cmd;
```
cmd.comando have values "00", "01", "02" .....
And I w... |
Try this:
```
int val = _ttoi(cmd.comando);
switch (val)
{
case 0:
...
break;
case 1:
...
break;
case 2:
...
break;
...
}
```
Or even simpler:
```
int val = 10*(cmd.comando[0]-L'0')+(cmd.comando[1]-L'0');
switch (val)
{
case 0:
...
break;
case 1:
...
break;
case 2:
...
break;
...... |
I have written a dissector for a custom protocol in Lua and I'm now going to refactor it in C. The issue is that the dissector requires some runtime arguments (decryption keys) that vary depending on the circumstances. In Lua this wasn't a problem since the required arguments can be hardcoded in and easily edited - sa... |
Make it a preference; see section 2.6 "User Preferences" in thedoc/README.dissectorfile in the Wireshark source. That way the user can set it through the Wireshark preferences dialogs or set it from the command line in Wireshark or TShark using the-ocommand-line flag.
|
```
void instert(NODE**root, int value)
{
...
insert(&(*root)->left,value);
...
}
void search(NODE*root, int value)
{
...
search(root->left, value);
...
}
```
Why we use "&" here: insert(&(*root)->left,value);
But we do not use "&" here: search(root->left, value);
|
The expression:
```
*root->left
```
Is equivalent to:
```
*(root->left)
```
Due to operator precedence.
So you need:
```
(*root)->left
```
If you want theleftmember that*rootpoints to.
And then:
```
&(*root)->left
```
Is the pointer to theleftmember of*root, which is then of typeNODE **, what theinsertfuncti... |
I have three variables- x,y and z in a C/C++ application. I would like to set x = y, when z == 3. I can do this using multiplication:
```
x = y * (z == 3)
```
but this is being called in a large loop and the IMUL will take 4 CPU cycles. I was hoping to find a bit manipulation which would take 1 CPU cycle.
EDIT: Com... |
Write:
```
if ( z == 3 )
x = y * 2;
else
x = y;
```
(or whatever else you edit your question to next) and activate your compiler. That's what compilers are for. You say what you want with compiler switches and the compiler does it better than you could.
|
I've got a very simple piece of C code that uses malloc and realloc, but it induces a seg fault if I change a value that was part of the first array.
```
#include <stdlib.h>
void increase(int** array)
{
int * new_array;
new_array = realloc(*array, 10 * sizeof(int));
if (new_array != NULL) {
*arr... |
You probably need:
```
(*array)[i] = 2;
```
The [] operator binds before the *, so your version was doing *(array[i]) which is, well, wrong.
|
This question already has answers here:Limit on the number of arguments to main in C(4 answers)Closed9 years ago.
I am writing an a general c program which accepts command line arguments and my doubt is no of command line arguments we can pass and why, on what factor does it depends.
|
The standard doesn't say nothing about the limit of arguments, soINT_MAX(typically2^31 - 1) is assumed.
On Linux, you get the maximum character length of arguments in a shell by running:
```
getconf ARG_MAX
```
More info
|
Im looking for a way to add the current date and time to a log file im opening
for now im using :
```
fopen("/var/log/SA_TEST","w");
```
How to make it
```
fopen("/var/log/SA_TEST_DATE_AND_TIME","w");
```
Thx a lot
(In c)
|
strftimecan be used to format the date an time :
```
#include <time.h>
char filename[40];
struct tm *timenow;
time_t now = time(NULL);
timenow = gmtime(&now);
strftime(filename, sizeof(filename), "/var/log/SA_TEST_%Y-%m-%d_%H:%M:%S", timenow);
fopen(filename,"w");
```
You can change the date an time format for w... |
I'm using Linux kernel 2.6.32 (x86_64) and can get TCP statistics by passingTCP_INFOtogetsockoptand receiving atcp_infostruct, which is defined in/usr/include/netinet/tcp.h.
Can I get similar statistics for UDP? (possibly fewer because there's no built-in congestion control and retransmission etc. but I'm satisfied w... |
TCP_INFO literally means info for TCP. The reason there aren't info for UDP is because it's stateless. There's no guaranteed transfer, not rtf, no window size, no much info to provide about.
If you really wanna grab some extra info, take a look atman 2 recvmsg, especially this
Ancillary data should only be accessed ... |
I have three variables- x,y and z in a C/C++ application. I would like to set x = y, when z == 3. I can do this using multiplication:
```
x = y * (z == 3)
```
but this is being called in a large loop and the IMUL will take 4 CPU cycles. I was hoping to find a bit manipulation which would take 1 CPU cycle.
EDIT: Com... |
Write:
```
if ( z == 3 )
x = y * 2;
else
x = y;
```
(or whatever else you edit your question to next) and activate your compiler. That's what compilers are for. You say what you want with compiler switches and the compiler does it better than you could.
|
I've got a very simple piece of C code that uses malloc and realloc, but it induces a seg fault if I change a value that was part of the first array.
```
#include <stdlib.h>
void increase(int** array)
{
int * new_array;
new_array = realloc(*array, 10 * sizeof(int));
if (new_array != NULL) {
*arr... |
You probably need:
```
(*array)[i] = 2;
```
The [] operator binds before the *, so your version was doing *(array[i]) which is, well, wrong.
|
This question already has answers here:Limit on the number of arguments to main in C(4 answers)Closed9 years ago.
I am writing an a general c program which accepts command line arguments and my doubt is no of command line arguments we can pass and why, on what factor does it depends.
|
The standard doesn't say nothing about the limit of arguments, soINT_MAX(typically2^31 - 1) is assumed.
On Linux, you get the maximum character length of arguments in a shell by running:
```
getconf ARG_MAX
```
More info
|
Im looking for a way to add the current date and time to a log file im opening
for now im using :
```
fopen("/var/log/SA_TEST","w");
```
How to make it
```
fopen("/var/log/SA_TEST_DATE_AND_TIME","w");
```
Thx a lot
(In c)
|
strftimecan be used to format the date an time :
```
#include <time.h>
char filename[40];
struct tm *timenow;
time_t now = time(NULL);
timenow = gmtime(&now);
strftime(filename, sizeof(filename), "/var/log/SA_TEST_%Y-%m-%d_%H:%M:%S", timenow);
fopen(filename,"w");
```
You can change the date an time format for w... |
I'm using Linux kernel 2.6.32 (x86_64) and can get TCP statistics by passingTCP_INFOtogetsockoptand receiving atcp_infostruct, which is defined in/usr/include/netinet/tcp.h.
Can I get similar statistics for UDP? (possibly fewer because there's no built-in congestion control and retransmission etc. but I'm satisfied w... |
TCP_INFO literally means info for TCP. The reason there aren't info for UDP is because it's stateless. There's no guaranteed transfer, not rtf, no window size, no much info to provide about.
If you really wanna grab some extra info, take a look atman 2 recvmsg, especially this
Ancillary data should only be accessed ... |
I am getting started with C and mruby. I have a program that calls to a Ruby function using the mrubymrb_load_stringfunction. I want to pass the argument from the C function to the Ruby function. How can I achieve this?
```
void on_key(const char *key) {
mrb_load_string(mrb, "input_received()"); // how do I pass ke... |
If your ruby function takes a string as a parameter input, then:
```
void on_key(const char *key) {
char arg[64];
sprintf(arg,"input_received(\"%s\")",key);//Embed key as an argument to the function
mrb_load_string(mrb, arg);
}
```
should do what you wanted.
|
Just installed librsync usingapt-get install librsync-devon ubuntu. I can link other libraries like thispkg-config --libs --cflags glib-2.0but I can't findlibrsyncusingpkg-config. How can I link it?
UPDATE:I very new to C and all this compiling linking stuff. Just learned how to find and link using pkg-config. But th... |
Your problem is not with C. The problem is most likely due to librsync NOT providing a package config file. Try:
```
pkg-config --list-all | grep -i rsync
```
If you get no response, librsync has no pkgconfig file available to the system. Instead of usingpkg-configto link librsync, just add-lrsyncto yourgcccommand l... |
At the moment my program is making asystem()call toifconfigto do this.
It seems a bit messy - maybeifconfigis not on the path, or in some non-standard location. And then I'd need to check for theiproute2equivalent in case of failure.
Is there a way to set this programmatically using C?
|
You can set the SIOCSIFMTU field in an ioctl call, something like this:
```
struct ifreq ifr;
ifr.ifr_addr.sa_family = AF_INET;//address family
strncpy(ifr.ifr_name, "eth0", sizeof(ifr.ifr_name));//interface name where you want to set the MTU
ifr.ifr_mtu = 9100; //your MTU size here
if (ioctl(sockfd, SIOCSIFMTU, (ca... |
Is it safe to run following program?
```
#include<stdio.h>
int main()
{
char *p="hello";
p="long string here";
printf("%s",p);
return 0;
}
```
I ran this and saw that it was giving the correct output. But, will the following statement be safe?
```
p="long string here";
```
Will it not cause ... |
The program is safe. Both strings are constants. Your pointer both starts and ends up pointing to a constant string, it just ends up pointing to a different one. No blocks of memory are copied or moved; there's no need to allocate anything.
Simply changing what a pointer references does not copy the new contents over... |
As far as I understand it, a dbus user connects to the session bus daemon if the environment defines two variables like:
```
DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-1cAnv4I,guid=3a453c40b5034f
DBUS_SESSION_BUS_PID=102
```
If the daemon stops and we start a new daemon by dbus-launch, we will get new values f... |
One way to get address after restart is to query corresponding X11 property:
dbus-daemon sets_DBUS_SESSION_BUS_ADDRESSproperty of_DBUS_SESSION_BUS_SELECTION_[hostname]_[uuid]selection owner (uuid is content of/var/lib/dbus/machine-id). This is the code I use to read the this value:https://github.com/sidorares/node-db... |
What does mean of "return p ? memcpy(p, s, len) : NULL;" in below code?
(More generally, what is the conditional operator,a ? b : c?)
```
char * strdup(const char * s)
{
size_t len = 1+strlen(s);
char *p = malloc(len);
return p ? memcpy(p, s, len) : NULL;
}
```
|
This syntax is called a ternary operator and you can think of it as of simplified if statement.return p ? memcpy(p, s, len) : NULL;is the same as:
```
if(p)
return memcpy(p, s, len);
else
return NULL;
```
memcpy()function returns a pointer to dest, which is a first argument of memcpy and in your case this is... |
Doesn't the array when declared in a loop sets to zero when the loop repeats?
I have an array and working with it this way..
```
while(i<n)
{
int a[1000];
//taking inputs in array..
/*some calculations with array..
the values in array may change*/
}
```
The next time when the loop repeats, array a i... |
The values of the array are uninitialized, they contain the"random"junkvalues that were on the stack.
Also the numbers in the array might be overwritten in each loop run. I.e. if you need the values to stay unaltered between the loops, then hoist the array declaration before thewhileloop.
Use
```
int a[1000] = {0};... |
This question already has answers here:current = current * 10 + (c - '0');(4 answers)Closed9 years ago.
I am currently going through K&R and I have a strong grasp of Java. One thing that comes up time and time again is- '0'. I believe it to be some sort of conversion, but I cannot glean from the book exactly what it ... |
Just like in Java, characters are represented as integral types.'0'has the value of the character0. Since the numbers are laid out so the value of'1' = '0' + 1this converts a character to a digit (given it is between'0'and'9').
|
I have a function that takes afloat**as an input variable,Jim. And I have another variable that was returned from a function of typevoid*. How do I castvoid*tofloat**? They should both be pointers to arrays of floats, but whyfloat**a pointer to a pointer? is this correct?
```
void* Joe;
float** Jim = *(float*) Joe;
`... |
The cast should be the same type as the variable on the left, so
```
float **Jim = (float**)&Joe;
```
|
I've recently built a Ruby C extension wrapping the library gorilla-audio. The library is simple enough, clean code, memory is accounted for, etc. However when I try to load the library into ruby it throws an error that reads:
The procedure entry point fclose could not be located in the dynamic linklibrary mscvrt-rub... |
I found the answer in case another person gets something like this; actually, it's two answers:
Don't cross compile, andI needed to link themsvcrtlibrary, as it holds all the default functions likefclose(), etc.
However, it didn't matter, because I was cross compiling anyways; I'll have to convert Ruby headers and ... |
How do you store a 16 bit binary in an array in C? What data type would I have to make the array? long int, float, char?
ex. data = {'1001111101110010', '1001101011010101','1000000011010010'}
|
Withinstdint.his the followingtypedef:
uint16_t
This integer type is exactly 16 bits in width. You can use it for your needs like this:
```
#include <stdint.h>
uint16_t arr[NUM_ELEMENTS] = {...};
```
|
I'm using LPCXpresso with LPC1768. I'm trying to implement few memory pools. I have my old code that allows this, so I'm fine there. What I'm unable to do is to prevent newlib from using it's own malloc. There are few functions in newlib calling malloc. I dodged them all, except for _Csys_alloc, which is unfortunately... |
It is perhaps simplest to let Newlib use its malloc as it wants and implement _sbrk() to limit its use and location to a static pool sized to just what is needed for library initialisation, then override malloc() for use in your own code - the linker will only link to standard library symbols if not previously found i... |
If I have the following function...
```
void function(double *array)
{
double a = array[3]; // Method 1
double b = *(array + 3); // Method 2
}
```
Assume the array has 5 elements (I do know the length of the array ahead of time).
The code compiles fine and runs ok. 'a' and 'b' do contain the expected value.
... |
E1[E2]is equivalent in C to(*((E1) + (E2)))by definition of[]operator.
Prefer the first notation as it is shorter and more readable.
|
the output of the function would be 4, but i am unable to understand why is this so. Its much appreciated if you can reason to what happens when for x%y, when y > x
```
int main()
{
int x=4%5;
printf("x=%d\n",x);
return 0;
}
```
|
4 / 5 = 0and0 * 5 + 4 = 4, so the remainder is4.
C defines%, the remainder operator, as (in c11, 6.5.5p6):
```
(a/b)*b + a%b shall equal a.
```
|
I expect that if I add 0.5 to a double and then truncate the value to round a double to the nearest integer. However, in the following code it doesn't work:
```
#include<stdio.h>
int main()
{
int a,b,d;
double c;
a = 54325;
b = 7858;
c = a/b;
c = c+0.5; /* rounding trick */
d = (int)c; ... |
```
c=a/b;
```
is an integer division as both operands of/are of integer types. This is the case even if herecis of typedouble.
To have a floating point division you need one operand of the/operator to be of floating point type:
```
c = (double) a / b;
```
|
Context
Here is my code
```
typedef struct {
int m;
int (*v)(int *restrict a);
} polo;
int toto(int *restrict a){
printf("hello %d\n",*a);
}
int main()
{
polo *kilo;
kilo->m = 84;
kilo->v = toto;
kilo->v(&kilo->m);
return 0;
}
```
Problem
Segfault.
I cannot get why. The same co... |
You need to reserve space forkilo:
polo *kilo = malloc(sizeof(*kilo));
or
polo *kilo = malloc(sizeof(polo));
Don't forget to callfree(kilo);at the end.
|
i have never written anything like it,
how do i check things like if a port is empty using c program
in Linux environment
thanks a lot.
ps looking for a way, by not using bind or connect and checking if it failed.
edit
i cant use bind or connect, looking for faster way to find 3k ports that are free in a row
|
Better way is to use next free port,You can also use 0 port bind will use the next available port.
You can get port selected by bind() by following code
```
struct sockaddr_in sin;
socklen_t len = sizeof(sin);
if (getsockname(sock, (struct sockaddr *)&sin, &len) != -1)
printf("port number %d\n", ntohs(sin.sin_port... |
which of the following is more efficient :
```
if (strcmp(str1,str2) != 0) {
...
}
```
OR
```
if (str1[0]!=str2[0] && strcmp(str1,str2) !=0 ) {
...
}
```
Ifstr2is always unique and there can be multiple str1.
|
There is no need of second version asstrcmpis usually implemented very smartly to compare multiple characters at once.
In second version, because of short-circuit property of&&, you may save a function call. You should benchmark both version for your requirements to get the correct idea.
But my suggestion still is, ... |
I have anunsigned shortvalue. It is binary data sampled from a radio source. I'd like to check if the data contains a particular byte, a signature byte.
To illustrate, theunsigned shortmight be
```
0100 1010 0111 0101 /* 0x4A75 */
```
and I want to check if it contains the byte
```
1010 0111 /* 0xA7 */
```
anywhe... |
Compare the least significant byte of yourshortobject with0xA7(i.e.,1010 0111) in a loop and shift yourshortvalue one bit to the right at each loop iteration.
|
I'm trying to mirror a raw (without image header) BGR image, 8 bit per pixel, using the following code:
```
void mirrorBGR(byte* src, byte* dst, UINT width, UINT height, UINT pitch_s, UINT pitch_d)
{
IppiSize size;
size.width = width;
size.height = height;
IppStatus status = ippiMi... |
Pitch is the scanline length for source & dest bitmaps.
If you use no padding, at least it should 640 (width) * 3 (bytes per pixel) = 1920
|
Im writing a docstring in doxygen within a C comment block, and I want to include a snippet that contains/* text */
I know I could include a file, but this is just 8 characters or so. and it needs to be/* text */, not// text(since Im documenting the behavior of a C source code parser).
Is there some way to escape th... |
In version 1.8.7.‍exists (see chapter 24 HTML commands of the documentation). Did you try (it is a bit of a trick):This parser C supports style formatted comments: /‍* text *‍/
|
I have anunsigned shortvalue. It is binary data sampled from a radio source. I'd like to check if the data contains a particular byte, a signature byte.
To illustrate, theunsigned shortmight be
```
0100 1010 0111 0101 /* 0x4A75 */
```
and I want to check if it contains the byte
```
1010 0111 /* 0xA7 */
```
anywhe... |
Compare the least significant byte of yourshortobject with0xA7(i.e.,1010 0111) in a loop and shift yourshortvalue one bit to the right at each loop iteration.
|
I'm trying to mirror a raw (without image header) BGR image, 8 bit per pixel, using the following code:
```
void mirrorBGR(byte* src, byte* dst, UINT width, UINT height, UINT pitch_s, UINT pitch_d)
{
IppiSize size;
size.width = width;
size.height = height;
IppStatus status = ippiMi... |
Pitch is the scanline length for source & dest bitmaps.
If you use no padding, at least it should 640 (width) * 3 (bytes per pixel) = 1920
|
Im writing a docstring in doxygen within a C comment block, and I want to include a snippet that contains/* text */
I know I could include a file, but this is just 8 characters or so. and it needs to be/* text */, not// text(since Im documenting the behavior of a C source code parser).
Is there some way to escape th... |
In version 1.8.7.‍exists (see chapter 24 HTML commands of the documentation). Did you try (it is a bit of a trick):This parser C supports style formatted comments: /‍* text *‍/
|
I would like to reverse an input character string and I use the the pointer which points to the last character and make it print the string while the pointer address decreases. However, I could not get the whole string. Could anyone tell me what is wrong?
```
//Reverse a charater string
#include<stdio.h>
int main()
{... |
You have declaredpas integer pointer. It should be a char pointer.
```
int *p;
```
should be
```
char *p;
```
|
```
double test3 = 1/7;
NSLog(@"The value of test3 = %1.6f",test3);
```
Result:
The value of test3 = 0.000000
Why won't it give me a fraction as a float value? It should say:
The value of test3 = 0.142857
What am I doing wrong?
|
You have to do1.0 / 7.0or1 / 7.0or1.0 / 7for the compiler to do floating point division.
1/7is simple integer division, which is0. Only the result of the integer division is casted and stored intest3and if both arguments are integers then you will get an integer returned.
To include random numbers (as mentioned in... |
I have a 1 lineinlinefunction which is part of a hotspot in my code. I would like to see if changing this to a macro would be beneficial. Writing as a function I did not have to worry about side effects. But how do I write a macro for this without side effects?
```
#define FLAG1_BIT 4
struct node
{
unsigned long ... |
First, keep in mind, I can see no reason why the compiler wouldn't inline it, so there's a every good chance this exercise will accomplish nothing at all.
The first rule to avoiding side-effects is to ensure that the parameter appears only once in the definition. Next, in the definition, wrap the parameter and the ... |
I have the following code, I declare themainObjstructure (user defined typeobj) before calling it in themainObj_initfunction. Do you know why Visual Studio underlinesmainObjlike it's not declared already?
```
#include <SDL.h>
#include <stdio.h>
typedef struct obj
{
SDL_Surface *pSprite;
SDL_Texture *pTexture... |
The problem is that this statement is wrong
```
mainObj->pSprite = SDL_LoadBMP(filename);
```
There shall be
```
mainObj.pSprite = SDL_LoadBMP(filename);
```
mainObjis not declared as a pointer.
|
Why is it that when I store the DATA of a double value in a char array if I get the data from the char array to another double, it returns a Float value?
In this:
```
double vals = 3.141592654;
char xvals[sizeof(vals)];
memcpy(&xvals, &vals, sizeof(xvals));
double y;
memcpy(&y, &xvals, sizeof(xvals));
std::cout<<y<... |
It does not "return a float value" :std::coutwill simply not print all those digits by default.
you can usestd::setprecison(from<iomanip>) to change the number of digits to be printed :
```
#include <iostream>
#include <iomanip>
int main()
{
double vals = 3.141592654;
std::cout << vals << "\n";
std::co... |
I would like to reverse an input character string and I use the the pointer which points to the last character and make it print the string while the pointer address decreases. However, I could not get the whole string. Could anyone tell me what is wrong?
```
//Reverse a charater string
#include<stdio.h>
int main()
{... |
You have declaredpas integer pointer. It should be a char pointer.
```
int *p;
```
should be
```
char *p;
```
|
This question already has answers here:What is the behavior of integer division?(6 answers)Closed9 years ago.
I have a piece of code that looks like this:
```
float nb = 100 / 42;
printf("%.2f", nb);
```
which I expect to print out2.38, but instead it prints out2.00.
The42is just an example. In the original code i... |
You need to specify the numbers as floating point themselves. Try this:
```
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
float nb = 100.0/42.0;
printf("%.2f\n", nb);
return 0;
}
```
|
Given following floating points variables with arbitrary value, in c/c++.
```
float a, b, c, d;
```
In following statements, can we assume any pair of them would always generate identical result?
```
float result_1 = a + b + c + d - c;
float result_2= a + b + c + (d - c);
float result_3 = a + b + d;
```
Also, is t... |
No, you can not assume this. I broke all three of your examples:(Live)
```
#include <iostream>
int main()
{
double a = 1, b = 1e100, c= 1e100, d= 1, c2 = .1, d2 = -.1, b2 = 1;
std::cout << ( a + b2 + c2 + d2 - c2 == a + b2 + c2 + (d2 - c2)) << "\n"
<< ( a + b2 + c + d - c == a + b2 + d) << "\n"
<< ( a... |
I'm not sure if this could be compile related, but the compiler I'm using is IAR 7.10.3.
I have a struct like follows:
```
struct A {
struct {
uint8_t x:1;
uint8_t y:2;
uint8_t z:5;
} b;
};
```
And initializes it like:
```
struct A a = {
.b = 0xFF,
};
```
Now when I look at the struct in memory,... |
```
struct A a = {
.b = 0xFF,
};
```
is parsed by your compiler as
```
struct A a = {
.b = {0xFF},
};
```
which is equivalent to
```
struct A a = {
.b = {0xFF, 0, 0},
};
```
Use:
```
struct A a = {
.b = {1, 3, 31},
};
```
to have all the bits of your bit-fields set to1. Or use an union with anuint8_tand... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.