question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I'm trying to make each object filefoo.odependent on its source filefoo.c. For some reason, using * to make each dependent on every source file (so thatfoo.odepends onfoo.c, bar.c, etc.works but using % gives an error.
My directory structure is has just one source file right now, but I'm planning to add more. The error I get is:
```
$(PATHO)%.o:: $(PATHT)*.c # This compiles properly
recipe
$(PATHO)%.o:: $(PATHT)%.c # This causes error 'No rule to make target'
recipe
```
EDIT: I clarified my question, apologies for any confusion.
|
When%in a target pattern matches, the%in the prerequisites expand to the matched part in the target.
For example, let's say you have a rule
```
%.o: %.c
$(CC) $(CFLAGS) -c $^
```
Whenfoo.omatches the rule target (%.o), the prerequisite isfoo.c.
This is explained in for example the GNU Make manual, sectionIntroduction to Pattern Rules, and works the same in all make variants.
|
I have checked a lot of sources, but I didn't understand what's the difference between single pointer and double pointers exactly, like when I use *string, I can fill it with many strings, and when I use **string, I can do the same thing.
Can any one give me a simple example that could make me understand ?, and how can I use malloc for both of them?.
|
** is a pointer to an existing pointer *
I would review this link for a detailed explanationHow do pointer to pointers work in C?
For malloc, there are plenty of examples on this site
|
I'm trying to make each object filefoo.odependent on its source filefoo.c. For some reason, using * to make each dependent on every source file (so thatfoo.odepends onfoo.c, bar.c, etc.works but using % gives an error.
My directory structure is has just one source file right now, but I'm planning to add more. The error I get is:
```
$(PATHO)%.o:: $(PATHT)*.c # This compiles properly
recipe
$(PATHO)%.o:: $(PATHT)%.c # This causes error 'No rule to make target'
recipe
```
EDIT: I clarified my question, apologies for any confusion.
|
When%in a target pattern matches, the%in the prerequisites expand to the matched part in the target.
For example, let's say you have a rule
```
%.o: %.c
$(CC) $(CFLAGS) -c $^
```
Whenfoo.omatches the rule target (%.o), the prerequisite isfoo.c.
This is explained in for example the GNU Make manual, sectionIntroduction to Pattern Rules, and works the same in all make variants.
|
I have checked a lot of sources, but I didn't understand what's the difference between single pointer and double pointers exactly, like when I use *string, I can fill it with many strings, and when I use **string, I can do the same thing.
Can any one give me a simple example that could make me understand ?, and how can I use malloc for both of them?.
|
** is a pointer to an existing pointer *
I would review this link for a detailed explanationHow do pointer to pointers work in C?
For malloc, there are plenty of examples on this site
|
I adopted the code fromthisanswer in order to draw an overlay window, which stays on top of all windows, always. But I find that this window keeps flickering whenever there is a keypress or a button click. I wanted to know if this can be stopped somehow. Increasing the time did not help me, as my terminal was frozen for few seconds when I increased time to5000000000
The code was tested onUbuntu 16.04 LTS.
|
I could not find a solution using theXCompositesuite of functions. However, you can easily achieve the same effect with (in my opinion) much more flexibility and pure X11 viaCWOverrideRedirect. You can see example usage for it here:https://stackoverflow.com/a/57780772/4204557
|
I am trying to retrieve session ID which client has presented as a part of client hello in a resumed session, Unfortunately i have access to only application layer, Is there a way i can extract it from SSL structure or any Openssl API available for the same
|
You can try to set message callback using the APISSL_CTX_set_msg_callback. This will give all the handshake messages which are sent or received. In this, you can try to parseClientHellomessage and retrieve theSession ID.
|
```
int decade;
float jeo;
PRINT("Enter Decade point =\r\n");
scanf("%d",&decade);
print_decimal(decade);
PRINT("\r\n");
jeo=(1/(1+decade));
PRINT("Decade point =");
print_decimal(jeo);//my function for showing floating point number.
PRINT("\r\n");
```
I have wrote this code in IAR embedded workbench software for ARM controller, but it's not giving me accurate answer, can anyone tell me why??
"when i am entering 3. it's giving me 0 answer".
|
You are just doing your calculation withintegerand assign afterwards to afloatvalue. This will remove the digits after the decimal point.
Try this:
```
jeo=(1.0/(1.0+decade));
```
|
I adopted the code fromthisanswer in order to draw an overlay window, which stays on top of all windows, always. But I find that this window keeps flickering whenever there is a keypress or a button click. I wanted to know if this can be stopped somehow. Increasing the time did not help me, as my terminal was frozen for few seconds when I increased time to5000000000
The code was tested onUbuntu 16.04 LTS.
|
I could not find a solution using theXCompositesuite of functions. However, you can easily achieve the same effect with (in my opinion) much more flexibility and pure X11 viaCWOverrideRedirect. You can see example usage for it here:https://stackoverflow.com/a/57780772/4204557
|
Given a binary integer, how can I invert (flip) last n bits using only bitwise operations in c/c++?For example:
```
// flip last 2 bits
0110 -> 0101
0011 -> 0000
1000 -> 1011
```
|
You can flip last n bits of your number with
```
#define flipBits(n,b) ((n)^((1u<<(b))-1))
```
for exampleflipBits(0x32, 4)will flip the last 4 bits and result will be0x3d
this works because if you think how XOR works
```
0 ^ 0 => 0
1 ^ 0 => 1
```
bitsaren'tflipped
```
0 ^ 1 => 1
1 ^ 1 => 0
```
bitsareflipped
```
(1<<b)-1
```
this part gets you the last n bits
for example, if b is 4 then1<<4is0b10000and if we remove 1 we get our mask which is0b1111then we can use this to xor with our number to get the desired output.
works for C and C++
|
these codes do the same work. I don't understand why
```
for ( ; *s1 = *s2; s1++, s2++ ) { ;}
for ( ; *s1 = *s2; s1++, s2++ ) {*s1=*s2;}
```
|
The second clause of the loop will evaluate to the value of the assignment and then use this value to determine whether to continue looping, so both loops will copys2tos1until*s1 == 0. Ifs1ands2are the same type of pointer, then this occurs when*s2 == 0. If they are not the same type, then this is tricky code that is quite possibly incorrect.
The second loop contains an entirely redundant body, since it just repeats what the second clause of the loop does already.
|
I want to set a 5th bit of a register called RCGCGPIO in RISC uC and I am using pointer dereference method along with bitwise OR operator to directly modify the address of the register that is at 0x40004000. But after executing the program in debugger, there is no change happening at this address. How should I use the pointer arithmetic with bitwise operator?
Refer the code snippet provided. When I use temporary variable to load, modify and store back the data to memory, it works fine. But when I directly use the bit wise operator, then I face this issue
```
#define RCGCGPIO (*((volatile unsigned short *)0x40004000))
#define N 5
int main(){
/*To set Nth bit*/
SYSCTL_RCGCGPIO_R = SYSCTL_RCGCGPIO_R | (1U >> N);
return 0;
}
```
|
1U >> Nshifts 1rightN bits, meaning it divides 1 by 2N. For any N greater than zero, this produces zero.
You likely want1U << Nto shiftleftN bits, which multiplies by 2N.
|
I am reading the fifth edition of a reference manual from 2002 and am very curious about the preprocessor declarations shown in a code sample. More specifically, why is it apparently necessary to add an 'x' after the call to 'free(x)'?
```
//1//#define free(x)x ? free(x) : NULL //OK
//2//#define free(x) ? free(x) :NULL // Error
int main() {
int *p;
*p = (int*)malloc(sizeof(int) * 5);
free(p); // 2 -(error) ->expected a decleration
//and also see this error in both
// ':' cannot convert from 'void *' to 'void'
```
|
The preprocessor does straight text replacement. Without the x, your processed code would look like:
```
*p = (int*)malloc(sizeof(int) * 5);
? free(p) :NUL;
```
Which is of course an error. The first example with the x would expand to
```
*p = (int*)malloc(sizeof(int) * 5);
p ? free(p) :NUL;
```
|
I have managed to transfer the 2d array int a 1d array to make it simpler. So given:
```
local table = {0,0,0,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,0,30,31,32,33, 0,34,35,36,37, 0 }
```
How can I extract a sub-array as below?
```
local sub = {2,3,4,7,8,9,12,13,14,17,18,19,22,23,24}
```
|
Here's one way...
```
> t = {}
> for i = 7, 30, 5 do
>> for j = i, i + 2 do
>> t[#t+1] = ble[j]
>> end
>> end
> for k,v in ipairs(t) do print(k,v) end
1 2
2 3
3 4
4 7
5 8
6 9
7 12
8 13
9 14
10 17
11 18
12 19
13 22
14 23
15 24
>
```
I renamed your table tobleso it doesn't shadow the table library.
|
This question already has answers here:Why unsigned int contained negative number(4 answers)C Unsigned int providing a negative value?(3 answers)Why unsigned int stills signed? [duplicate](3 answers)Unsigned values in C(3 answers)Closed4 years ago.
When i tried the below code snippet,its printing -1 as output.
But how unsigned int is storing -1?
code:
```
unsigned int a = -1;
printf("a = %d \n",a)
```
The output: -1
How is this possible?
note: I saw similar question in stackoverflow. This is different. My question is why it printed -1 as output even though "a" is unsigned.
|
The%dspecifier tellsprintf, "Interpret this value as asignedinteger". Even thoughahas a value of0xFFFFFFFF(4,294,967,296), when interpreted as a signed value, it will show up as -1.
|
"Production compilers also exist for several other machines, including the IBM System/370, the Honeywell 6000, and the Interdata 8/32."
|
Compilers which are production-ready. Ie. It conforms to all requirements to be used in a production environment. It generates stable, executable software for the platform it is designed to.
This is as opposed to an experimental compiler or an in-development compiler.
|
How to detect process name which access to designated registry like process monitor?
Older regmon do it using SSDT Hooking ,but in windows 10, we can't hook
registry using it.SSDT Hooking seem to be legacy technology.
Are there substituites for SSDT Hooking to hook ?
|
You should implement a properregistry filtering driver.
A registry filtering driver is any kernel-mode driver that filters registry calls, such as the driver component of an antivirus software package. The configuration manager, which implements the registry, allows registry filtering drivers to filter any thread's calls to registry functions.
|
Given a binary integer, how can I invert (flip) last n bits using only bitwise operations in c/c++?For example:
```
// flip last 2 bits
0110 -> 0101
0011 -> 0000
1000 -> 1011
```
|
You can flip last n bits of your number with
```
#define flipBits(n,b) ((n)^((1u<<(b))-1))
```
for exampleflipBits(0x32, 4)will flip the last 4 bits and result will be0x3d
this works because if you think how XOR works
```
0 ^ 0 => 0
1 ^ 0 => 1
```
bitsaren'tflipped
```
0 ^ 1 => 1
1 ^ 1 => 0
```
bitsareflipped
```
(1<<b)-1
```
this part gets you the last n bits
for example, if b is 4 then1<<4is0b10000and if we remove 1 we get our mask which is0b1111then we can use this to xor with our number to get the desired output.
works for C and C++
|
these codes do the same work. I don't understand why
```
for ( ; *s1 = *s2; s1++, s2++ ) { ;}
for ( ; *s1 = *s2; s1++, s2++ ) {*s1=*s2;}
```
|
The second clause of the loop will evaluate to the value of the assignment and then use this value to determine whether to continue looping, so both loops will copys2tos1until*s1 == 0. Ifs1ands2are the same type of pointer, then this occurs when*s2 == 0. If they are not the same type, then this is tricky code that is quite possibly incorrect.
The second loop contains an entirely redundant body, since it just repeats what the second clause of the loop does already.
|
I want to set a 5th bit of a register called RCGCGPIO in RISC uC and I am using pointer dereference method along with bitwise OR operator to directly modify the address of the register that is at 0x40004000. But after executing the program in debugger, there is no change happening at this address. How should I use the pointer arithmetic with bitwise operator?
Refer the code snippet provided. When I use temporary variable to load, modify and store back the data to memory, it works fine. But when I directly use the bit wise operator, then I face this issue
```
#define RCGCGPIO (*((volatile unsigned short *)0x40004000))
#define N 5
int main(){
/*To set Nth bit*/
SYSCTL_RCGCGPIO_R = SYSCTL_RCGCGPIO_R | (1U >> N);
return 0;
}
```
|
1U >> Nshifts 1rightN bits, meaning it divides 1 by 2N. For any N greater than zero, this produces zero.
You likely want1U << Nto shiftleftN bits, which multiplies by 2N.
|
I am reading the fifth edition of a reference manual from 2002 and am very curious about the preprocessor declarations shown in a code sample. More specifically, why is it apparently necessary to add an 'x' after the call to 'free(x)'?
```
//1//#define free(x)x ? free(x) : NULL //OK
//2//#define free(x) ? free(x) :NULL // Error
int main() {
int *p;
*p = (int*)malloc(sizeof(int) * 5);
free(p); // 2 -(error) ->expected a decleration
//and also see this error in both
// ':' cannot convert from 'void *' to 'void'
```
|
The preprocessor does straight text replacement. Without the x, your processed code would look like:
```
*p = (int*)malloc(sizeof(int) * 5);
? free(p) :NUL;
```
Which is of course an error. The first example with the x would expand to
```
*p = (int*)malloc(sizeof(int) * 5);
p ? free(p) :NUL;
```
|
I have managed to transfer the 2d array int a 1d array to make it simpler. So given:
```
local table = {0,0,0,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,0,30,31,32,33, 0,34,35,36,37, 0 }
```
How can I extract a sub-array as below?
```
local sub = {2,3,4,7,8,9,12,13,14,17,18,19,22,23,24}
```
|
Here's one way...
```
> t = {}
> for i = 7, 30, 5 do
>> for j = i, i + 2 do
>> t[#t+1] = ble[j]
>> end
>> end
> for k,v in ipairs(t) do print(k,v) end
1 2
2 3
3 4
4 7
5 8
6 9
7 12
8 13
9 14
10 17
11 18
12 19
13 22
14 23
15 24
>
```
I renamed your table tobleso it doesn't shadow the table library.
|
This question already has answers here:Why unsigned int contained negative number(4 answers)C Unsigned int providing a negative value?(3 answers)Why unsigned int stills signed? [duplicate](3 answers)Unsigned values in C(3 answers)Closed4 years ago.
When i tried the below code snippet,its printing -1 as output.
But how unsigned int is storing -1?
code:
```
unsigned int a = -1;
printf("a = %d \n",a)
```
The output: -1
How is this possible?
note: I saw similar question in stackoverflow. This is different. My question is why it printed -1 as output even though "a" is unsigned.
|
The%dspecifier tellsprintf, "Interpret this value as asignedinteger". Even thoughahas a value of0xFFFFFFFF(4,294,967,296), when interpreted as a signed value, it will show up as -1.
|
"Production compilers also exist for several other machines, including the IBM System/370, the Honeywell 6000, and the Interdata 8/32."
|
Compilers which are production-ready. Ie. It conforms to all requirements to be used in a production environment. It generates stable, executable software for the platform it is designed to.
This is as opposed to an experimental compiler or an in-development compiler.
|
How to detect process name which access to designated registry like process monitor?
Older regmon do it using SSDT Hooking ,but in windows 10, we can't hook
registry using it.SSDT Hooking seem to be legacy technology.
Are there substituites for SSDT Hooking to hook ?
|
You should implement a properregistry filtering driver.
A registry filtering driver is any kernel-mode driver that filters registry calls, such as the driver component of an antivirus software package. The configuration manager, which implements the registry, allows registry filtering drivers to filter any thread's calls to registry functions.
|
```
int main()
{
int var = 10;
int **ptr;
**ptr = var;
printf("%x\n",ptr);
printf("%d\n",**ptr);
return 0;
}
```
The above code prints: 0 and 10
Why is ptr 0 ?
How is the code showing **ptr = 10, if ptr is 0 ?
I tried printing *ptr.
This gave segmentation fault (since ptr is 0).
So, again why not throw segmentation fault at **ptr ?
Could this be related to compiler ?
PS: I am usinghttps://www.onlinegdb.com/online_c_compilerto run this code.
|
Pointerptris not initialized. Your code invokes undefined behaviour because you are dereferencing an uninitialized pointer.
|
I want to set a 5th bit of a register called RCGCGPIO in RISC uC and I am using pointer dereference method along with bitwise OR operator to directly modify the address of the register that is at 0x40004000. But after executing the program in debugger, there is no change happening at this address. How should I use the pointer arithmetic with bitwise operator?
Refer the code snippet provided. When I use temporary variable to load, modify and store back the data to memory, it works fine. But when I directly use the bit wise operator, then I face this issue
```
#define RCGCGPIO (*((volatile unsigned short *)0x40004000))
#define N 5
int main(){
/*To set Nth bit*/
SYSCTL_RCGCGPIO_R = SYSCTL_RCGCGPIO_R | (1U >> N);
return 0;
}
```
|
1U >> Nshifts 1rightN bits, meaning it divides 1 by 2N. For any N greater than zero, this produces zero.
You likely want1U << Nto shiftleftN bits, which multiplies by 2N.
|
I am reading the fifth edition of a reference manual from 2002 and am very curious about the preprocessor declarations shown in a code sample. More specifically, why is it apparently necessary to add an 'x' after the call to 'free(x)'?
```
//1//#define free(x)x ? free(x) : NULL //OK
//2//#define free(x) ? free(x) :NULL // Error
int main() {
int *p;
*p = (int*)malloc(sizeof(int) * 5);
free(p); // 2 -(error) ->expected a decleration
//and also see this error in both
// ':' cannot convert from 'void *' to 'void'
```
|
The preprocessor does straight text replacement. Without the x, your processed code would look like:
```
*p = (int*)malloc(sizeof(int) * 5);
? free(p) :NUL;
```
Which is of course an error. The first example with the x would expand to
```
*p = (int*)malloc(sizeof(int) * 5);
p ? free(p) :NUL;
```
|
I have managed to transfer the 2d array int a 1d array to make it simpler. So given:
```
local table = {0,0,0,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,0,30,31,32,33, 0,34,35,36,37, 0 }
```
How can I extract a sub-array as below?
```
local sub = {2,3,4,7,8,9,12,13,14,17,18,19,22,23,24}
```
|
Here's one way...
```
> t = {}
> for i = 7, 30, 5 do
>> for j = i, i + 2 do
>> t[#t+1] = ble[j]
>> end
>> end
> for k,v in ipairs(t) do print(k,v) end
1 2
2 3
3 4
4 7
5 8
6 9
7 12
8 13
9 14
10 17
11 18
12 19
13 22
14 23
15 24
>
```
I renamed your table tobleso it doesn't shadow the table library.
|
This question already has answers here:Why unsigned int contained negative number(4 answers)C Unsigned int providing a negative value?(3 answers)Why unsigned int stills signed? [duplicate](3 answers)Unsigned values in C(3 answers)Closed4 years ago.
When i tried the below code snippet,its printing -1 as output.
But how unsigned int is storing -1?
code:
```
unsigned int a = -1;
printf("a = %d \n",a)
```
The output: -1
How is this possible?
note: I saw similar question in stackoverflow. This is different. My question is why it printed -1 as output even though "a" is unsigned.
|
The%dspecifier tellsprintf, "Interpret this value as asignedinteger". Even thoughahas a value of0xFFFFFFFF(4,294,967,296), when interpreted as a signed value, it will show up as -1.
|
"Production compilers also exist for several other machines, including the IBM System/370, the Honeywell 6000, and the Interdata 8/32."
|
Compilers which are production-ready. Ie. It conforms to all requirements to be used in a production environment. It generates stable, executable software for the platform it is designed to.
This is as opposed to an experimental compiler or an in-development compiler.
|
How to detect process name which access to designated registry like process monitor?
Older regmon do it using SSDT Hooking ,but in windows 10, we can't hook
registry using it.SSDT Hooking seem to be legacy technology.
Are there substituites for SSDT Hooking to hook ?
|
You should implement a properregistry filtering driver.
A registry filtering driver is any kernel-mode driver that filters registry calls, such as the driver component of an antivirus software package. The configuration manager, which implements the registry, allows registry filtering drivers to filter any thread's calls to registry functions.
|
```
int main()
{
int var = 10;
int **ptr;
**ptr = var;
printf("%x\n",ptr);
printf("%d\n",**ptr);
return 0;
}
```
The above code prints: 0 and 10
Why is ptr 0 ?
How is the code showing **ptr = 10, if ptr is 0 ?
I tried printing *ptr.
This gave segmentation fault (since ptr is 0).
So, again why not throw segmentation fault at **ptr ?
Could this be related to compiler ?
PS: I am usinghttps://www.onlinegdb.com/online_c_compilerto run this code.
|
Pointerptris not initialized. Your code invokes undefined behaviour because you are dereferencing an uninitialized pointer.
|
I would like to ask if this short code:
```
int i = 0;
```
has 1 operand or 2? Theiis an operand, but is0too? According towikipedia, 0 shouldn't (or maybe I misunderstand). If 0 isn't operand, is it a constant or something?
If it is important, the code is in C99.
|
Inint i = 0;,=is not an operator. It's simply a part of the variable initializaton syntax. On the other hand, inint i; i = 0;it would be an operator.
Since=here is not an operator, there are no operands. Instead,0is theinitializer.
|
I get this error(Error expected expression before “)” token in C) when i try to dynamically create a 2-d array of structures
```
typedef struct
{
unsigned char r;
unsigned char g;
unsigned char b;
} pixeli;
int main()
{
pixeli **rgb=(pixeli**)malloc((sablon_w)*sizeof(pixel*));
for(int i=0;i<sablon_h;i++)
rgb[i]=(pixeli *)malloc(sablon_h*sizeof(pixel));
}
```
|
There is typo in bothsizeofparenthesis: should bepixeliinstead ofpixel.
|
I would like to ask if this short code:
```
int i = 0;
```
has 1 operand or 2? Theiis an operand, but is0too? According towikipedia, 0 shouldn't (or maybe I misunderstand). If 0 isn't operand, is it a constant or something?
If it is important, the code is in C99.
|
Inint i = 0;,=is not an operator. It's simply a part of the variable initializaton syntax. On the other hand, inint i; i = 0;it would be an operator.
Since=here is not an operator, there are no operands. Instead,0is theinitializer.
|
This is the implementation of the functionint fgetc(FILE* fp)according to this link.mirror.fsf.org
```
#include <stdio.h>
#include <unistd.h>
/** fgetc(fp) -- get char from stream */
int fgetc(FILE *fp)
{
char c;
if (fp->ungetcflag) {
fp->ungetcflag = 0;
return (fp->ungetchar);
}
if (read (fp->fd, &c, 1) == 0)
return (EOF);
return (c);
}
```
I tried looking at the definition ofFILEinstdio.hand google and I couldn't find the memberungetcflagorungetchar.
What is the meaning of this?
|
@Antti Haapalacomment good enough for an answer.
That isoneimplementation offgetc(), nottheimplementation offgetc)_.Specifically it isnot the implementation offgetc()that is your libc, hence the code does not match theFILEdefinition in your<stdio.h>.
|
PSEUDO-CODE:
```
Child:
...
wait until parent prints "blabla"
...
Parent:
...
print "blabla"
...
```
I can't usewait, because that would be the other way around and furthermore, I want to continue the parent process after theprint "blabla"parallel to the child process.I could imagine to share withmmapapthread_mutex_tvariable and solve the issue with mutual exclusion, but I am not sure about that and wanted to ask if there might exists a very easy solution.
|
You can use Signals for this,
After completing a certain task parent process should send a signal to child process by using Kill system call and by updating the signal handler of the signal child process can do further task.
Child:
signal_handler()
{
...
}
main()
{
signal(SIGINT, signal_handler);
while(1);//wait until parent prints "blabla"
}
```
Parent:
...
print "blabla"
kill(pid_of_child,signal)
...
```
|
Could you point me in right direction? Now I am looking system callg_io_getattr..
I do not want to call subprocess.
The return would be e.g. 'da0', 'da1' or 'ada0'...
|
You are most likely going to want to be working with FreeBSD'slibgeom- specifically geom_gettree().The source to freebsd's partedit- shows it being used and the resulting structure being iterated through in the read_geom_mesh and related functions in order to get a list of the disks. What appears to be thesource of the geom programalso demonstrates some usage of the geom_gettree function and iterating through its returned structure.
|
Could you point me in right direction? Now I am looking system callg_io_getattr..
I do not want to call subprocess.
The return would be e.g. 'da0', 'da1' or 'ada0'...
|
You are most likely going to want to be working with FreeBSD'slibgeom- specifically geom_gettree().The source to freebsd's partedit- shows it being used and the resulting structure being iterated through in the read_geom_mesh and related functions in order to get a list of the disks. What appears to be thesource of the geom programalso demonstrates some usage of the geom_gettree function and iterating through its returned structure.
|
I couldn't zero down where i have missed in the input statement. I have build it to acquire four values as input but it goes one more.
manipulating the array entries to check if the fifth value is stored. Basic things
```
#include <stdio.h>
int main()
{
int i,j,a[2][2];
for(i=1;i<=2;i++)
{
for(j=1;j<=2;j++)
scanf("%d\t",&a[i][j]);
}
printf("\n%d\t%d\n%d\t%d", a[1][1],a[1][2],a[2][1],a[2][2]);
}
```
|
You have declared this
```
int a[2][2];
```
which has four items,a[0][0],a[0][1],a[1][0]anda[1][1].
However, you are starting your indexing at1and going up to2, so are stepping out of bounds which is undefined behaviour.
Anything can then happen.
Change your loops i.e.:
```
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
// as you were
```
to index from 0.
You also need to consider yourprintfstatement, since that oversteps too.
|
```
int a = 2;
while (1 < a < 5) {
printf("%d\n", a);
a = a + 1;
}
```
In a C program, I have used the above code, but it is always counting infinitely. That means the test condition of the while loop is always true. But I could not understand why this is happening.
|
1 < a < 5is grouped as(1 < a) < 5.
For your value ofa,1 < areturns1(true), so now your expression becomes1 < 5, which always evaluates to1, that's why you end up with an infinite loop.
The behavior you want can be obtained by writingwhile((1 < a) && (a < 5))instead.
|
Suppose I have following C project structure:
```
├── CMakeLists.txt
├── include
│ ├── header.h
├── README.md
├── src
│ └── src.c
└── test
├── CMakeLists.txt
└── test.c
```
TheCMakeLists.txtin the root directory contains a project calledcproj
```
PROJECT(cproj C)
```
Also intest/CMakeLists.txt, I have another project
```
PROJECT(test C)
```
The question is how can I assess the project namecprojin theCMakeLists.txtintestdirectory?
|
If I gather your use case correctly, you should probably do as follows:
testis quite likely not a standalone sub-project. It should not have aprojectdirective. If you remove it, it will now be under thecprojproject.Now you looking for the project name you've set in the root, it should be available via theCMAKE_PROJECT_NAMEvariable.
|
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.Closed4 years ago.Improve this question
In the following statement:
```
char *myarray[] = {"Amir"};
```
For pointer myarray[], how many bytes of memory has been allocated?
|
It depends on the OS Architecture. Because it is an array ofchar *, It will take size equivalent to one pointer in this case.
For 32-bit addressing, it will take 4 bytes.
For 64-bit addressing, it will take 8 bytes.
|
This question already has answers here:What does getting the address of an array variable mean?(7 answers)Closed4 years ago.
I am trying to understand array behavior. Please see the code below. Size of int is 4.
```
int arr[]={10,9,8,7,6,5};
printf("\nSingle array print=> \n%u || %u || %u || %u",
singlearr, &singlearr, &singlearr + 1);
```
I am getting the output:
```
2293248 || 2293248 || 2293272
```
I understand the expressions "singlarr" and "&singlearr" but when I am doing "&singlearr + 1", why it is giving output as 2293272 which is 24 bytes after the address 2293248 (2293248+24) ?
|
&arr is a pointer to an entire array. So, if we move &arr by 1 position it will point the next block ofnelements.
If the array base address isb, &arr+1 will beb + (n * 4)
here, n=6 and b = 2293248
so,&arr+1 = b+(n*4) = 2293248 + (6*4) = 2293272
|
How to used sd2 primitivies and sdl2_gfx in c4droid
In sdl copiler options i have
-lSDL2_image -lSDL2_net -ltiff -ljpeg -lpng -lz -lSDL2_ttf -lfreetype -lSDL2_mixer -lSDL2_test -lsmpeg2 -lvorbisfile -lvorbis -logg -lstdc++ -lSDL2 -lEGL -lGLESv1_CM -lGLESv2 -landroid -I(c4droid:GCCROOT)(c4droid:PREFIX)/include/SDL2 -Wl,--no-undefined -shared
When i add *.h file and lib c4droid do not have it
|
I was stiupid it is very simple download SDL2_gfx source extension for example fromhttp://www.ferzkopp.net/wordpress/2016/01/02/sdl_gfx-sdl2_gfx/add SDL2_gfxPrimitives.c and SDL2_rotozoom.c to compile and to directory and add to directory SDL2_gfxPrimitives.h, SDL2_rotozoom.h, SDL2_gfxPrimitives_font.h. To multifile compilation hold compile button and set compile multiple source code files
|
I understand from C manpage that usingfgets(), reading stops after anEOFor a newline. i have a program that reads from file(with multiple lines) and reading stop at the end of new line.
Is there a way to forcefgets()to ignore newlines and read tillEOF?
```
while(fgets(str,1000, file))
{
// i do stuffs with str here
}
```
|
Is there a way to forcefgets()to ignore newlines and read tillEOF?
No, you can't becausefgets()is implemented in such a way that the parsing will stops ifend-of-fileoccurs or anewline characteris found. May you can consider using other file i/o function likefread().
|
I am having aFILE* targethere which should open the windows hosts file and write to it:
```
FILE* target;
target = fopen("C:\\windows\\sysnative\\drivers\\etc\\hosts", "r+");
if (target != NULL) {
printf("true\n");
} else {
printf("false\n");
}
```
However, upon opening the windows hosts file, it fails to open it. Specifically,fopen()returnsNULLandfalseis printed to the screen. I checked the directory. It is good. Removing the extra\s, I was able to open it with Notepad. Howeverfopen()cannot open that file. It is able to open any file in the current working directory, or in a nested directory inside it, but it can't open the hosts file. Perhaps I have an issue with my path? Am I missing something?
|
you need admin priv to open hosts file on windows, try running your script as admin.
|
what does asterisk(*++argv) mean?
```
void main (int argc, char *argv[])
{
while (--argc)
{
printf ("%s\n", *++argv);
}
}
```
|
hereargvis a pointer to a pointer ofchartype
*argvpoints to the first argument string in the argv array, which is same asargv[0], similarly*(argv + 1)andargv[1]point to second argument string and so on..
Pointers in C: when to use the ampersand and the asterisk?
|
Assuming can_change_color() returns true, can init_color() add more colors outside the 8 initialized basic colors? Or only modify their RGB values?
Reading through the manpage I was under the impression it could only modify one of the 8 basic colors. But recently I came across some commented code which implied it could add colors beyond the 8 initial.
I haven't found any definitive documentation on this, does anybody know?
|
I love That Katie Loves Classi, actually this question wasanswered a bit ago on Stack Exchange. Feel free to read that and enjoy!
|
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed4 years ago.Improve this question
```
type Foobar C.struct_foobar
```
vs.
```
type Foobar struct {
foobar C.struct_foobar
}
```
Which one has which (dis)advantages for writing Golang bindings for a C lib?
|
The second example clearly shows a data structure not accessible from other packages.
With the first one this would be impossible.
|
I want to input a string, the subsequently a char for further use in my program, but whenever I try to input a string longer than 10 characters, all that's leftover, goes into my next input request. I tried using scanf("%*c"), but it couldn't flush all my input.
```
char tab[11];
char c;
printf("Give me a string: ");
scanf("%10[^\n]%*c", tab);
printf("%s\n", tab);
printf("Give ma a char: ");
scanf("%c", &c);
```
How should I properly deal with this issue?
|
Rungetcharin a loop until you read a newline:
```
printf("Give me a string: ");
scanf("%10[^\n]", tab);
while (getchar() != '\n');
printf("%s\n", tab);
printf("Give me a char: ");
scanf("%c", &c);
```
|
This question already has answers here:Does C have references?(2 answers)Closed4 years ago.
I'm learning referencing in C and here is my code:
```
#include <stdio.h>
int main(void)
{
int x = 5;
int &ref = x;
printf("%d\n", x);
printf("%p\n", &x);
printf("%p\n", &ref);
return 0;
}
```
When i compile, it shows these errors:
reference.c:7:6: error: expected identifier or '('int &ref = x;reference.c:11:18: error: use of undeclared identifier 'ref'printf("%p\n", &ref);2 errors generated.
What should i do to fix this and thanks in advance.
|
c does not have a reference type, you can only use point instead of ref.
```
#include <stdio.h>
int main(void) {
int x = 5;
int *ref = &x;
printf("%d\n", x);
printf("%p\n", &x);
printf("%p\n", &ref);
return 0;
}
```
|
Normally the data segment inC coderesides in theRAMvolatile memory and consists of Initialized data segment,Uninitialized data segment(.BSS),Stack memoryand the heap.
Stack memory is only coming to picture while on run time call routines and inpushandpullof values.Heap is used on dynamic memory allocation callsmalloc,callocandrealloc..BSS segmentis only having value by memset or inside functions as it doesnot have any genuine initial values .But theInitialized data segmenteven though it is static or global must be having some values and these values needs to be stored in a non volatile memory location as it should exist before the running of the code.
Question:In which section of non volatile memory location this initialized values are stored and whether any means we can use to reduce the memory consumption of this?
|
The following two diagrams helps to understand the memory layout of c binary
Refer :C compiler. Memory map. Program
|
What is_ALPHA_macro?
I found this macroin this code.
What do you use this macro for?
Please tell me this macro or its references.
|
I believe it is a macro that is#defined if the file is being compiled forDEC Alpha architecture. With Windows, of course, one must note that Alpha support was there for
Windows NT (discontinued after NT 4.0; and pre-release Windows 2000 RC1)
it means that in practice it is never#defined.
|
I want to input a string, the subsequently a char for further use in my program, but whenever I try to input a string longer than 10 characters, all that's leftover, goes into my next input request. I tried using scanf("%*c"), but it couldn't flush all my input.
```
char tab[11];
char c;
printf("Give me a string: ");
scanf("%10[^\n]%*c", tab);
printf("%s\n", tab);
printf("Give ma a char: ");
scanf("%c", &c);
```
How should I properly deal with this issue?
|
Rungetcharin a loop until you read a newline:
```
printf("Give me a string: ");
scanf("%10[^\n]", tab);
while (getchar() != '\n');
printf("%s\n", tab);
printf("Give me a char: ");
scanf("%c", &c);
```
|
This question already has answers here:Does C have references?(2 answers)Closed4 years ago.
I'm learning referencing in C and here is my code:
```
#include <stdio.h>
int main(void)
{
int x = 5;
int &ref = x;
printf("%d\n", x);
printf("%p\n", &x);
printf("%p\n", &ref);
return 0;
}
```
When i compile, it shows these errors:
reference.c:7:6: error: expected identifier or '('int &ref = x;reference.c:11:18: error: use of undeclared identifier 'ref'printf("%p\n", &ref);2 errors generated.
What should i do to fix this and thanks in advance.
|
c does not have a reference type, you can only use point instead of ref.
```
#include <stdio.h>
int main(void) {
int x = 5;
int *ref = &x;
printf("%d\n", x);
printf("%p\n", &x);
printf("%p\n", &ref);
return 0;
}
```
|
Normally the data segment inC coderesides in theRAMvolatile memory and consists of Initialized data segment,Uninitialized data segment(.BSS),Stack memoryand the heap.
Stack memory is only coming to picture while on run time call routines and inpushandpullof values.Heap is used on dynamic memory allocation callsmalloc,callocandrealloc..BSS segmentis only having value by memset or inside functions as it doesnot have any genuine initial values .But theInitialized data segmenteven though it is static or global must be having some values and these values needs to be stored in a non volatile memory location as it should exist before the running of the code.
Question:In which section of non volatile memory location this initialized values are stored and whether any means we can use to reduce the memory consumption of this?
|
The following two diagrams helps to understand the memory layout of c binary
Refer :C compiler. Memory map. Program
|
What is_ALPHA_macro?
I found this macroin this code.
What do you use this macro for?
Please tell me this macro or its references.
|
I believe it is a macro that is#defined if the file is being compiled forDEC Alpha architecture. With Windows, of course, one must note that Alpha support was there for
Windows NT (discontinued after NT 4.0; and pre-release Windows 2000 RC1)
it means that in practice it is never#defined.
|
In which situation should we prefer a void pointer over a char pointer or vice-versa?
As a matter of fact both can be type cast to any of the data types.
|
Avoidpointer is a pointer to "any type", and it needs to be converted to a pointer to an actual type before it may be dereferenced.
A pointer tocharis a pointer tochar, that happens to have the property that you could also access (parts of) other types through it.
You should usevoid *when the meaning is intended to be "any type" (or one of several types, etc). You should usechar *when you access either achar(obviously), or the individual bytes of another typeas raw bytes.
|
I have function, say:
```
int foo(char* a)
{
printf("%d\n", (int)a);
char cmd[] = "echo hello";
system(cmd);
printf("%d\n", (int)a);
}
```
in C code, and then I run it on linux; after doing so, I see that printf outputs are:
```
274351760
1853775725
```
I just confused so much! Any idea?! :|
|
Works here:
```
#include <stdio.h>
#include <stdlib.h>
int foo(char* a)
{
printf("%p\n", a);
char cmd[] = "echo hello";
system(cmd);
printf("%p\n", a);
return 0;
}
int main(void)
{
foo("OMG");
return 0;
}
```
Output:
```
$ ./a.out
0x400718
hello
0x400718
```
|
This is my makefile but the header files are not included:
```
CC =gcc
#CFLAGS =-g
INC=-I/inc/stackheaders.h
OBJFILES= main.o fileOperations.o stackOperations.o
HEADERS = inc/stackheaders.h
TARGET = stacktest
all: $(TARGET)
$(TARGET): $(OBJFILES)
$(CC) $(INC)-o $(TARGET) $(OBJFILES)
clean:
rm -f $(OBJFILES) $(TARGET)
```
The error I get is:
```
gcc -c -o main.o main.c
main.c:1:26: fatal error: stackheaders.h: No such file or directory
compilation terminated.
<builtin>: recipe for target 'main.o' failed
make: *** [main.o] Error 1
```
|
In the makefile change:
```
INC=-I/inc/stackheaders.h
```
...to:
```
INC=-I/inc
```
...given that the filestackheaders.his in/inc.
|
I am trying to replace stdin with another pipe, then place the original stdin back to fd #0.
e.g.
```
dup2(p, 0); // p is a pre-existing fd of a pipe
exec(/* some commands */);
//what will be here in order to have the original stdin back?
scanf(...) //continue processing with original stdin.
```
|
You can't recover the original once it has been overwritten (closed). What you can do is save a copy of it before you overwrite it (which requires planning ahead, of course):
```
int old_stdin = dup(STDIN_FILENO);
dup2(p, STDIN_FILENO);
close(p); // Usually correct when you dup to a standard I/O file descriptor.
…code using stdin…
dup2(old_stdin, STDIN_FILENO);
close(old_stdin); // Probably correct
scanf(…);
```
However, your code mentionsexec(…some commands…);— if that is one of the POSIXexecve()family of functions, then you won't reach thescanf()(or the seconddup2()) call unless theexec*()call fails.
|
Can anybody explain exactly what this type meansint * (*) (int *)in C language?
Thanks,
|
Unlessintis defined as a macro,int * (*) (int *)contains neither any constants nor any identifiers, therefore it cannot be an expression. Rather, it is atype. Specifically, it is the type of a pointer to a function that accepts one parameter, of typeint *, and returns a value of typeint *. For example, it is compatible with a pointer to this function:
```
int *foo(int *x) {
return x + 1;
}
```
You might use it in a typecast expression, such as in this contrived example:
```
int *(*p)() = foo;
int *(*p2)(int *) = (int * (*)(int *)) p;
// here ------------^^^^^^^^^^^^^^^^^^
```
|
I'm trying to set a keylogger kernel module. all is fine except the final log file. I'm trying to, at the exit of the module, write a log in a /tmp/ file.
I'm using last kernel version 4.20. I'm trying to use vfs_write, but when compiling, it tells me
"WARNING : vfs_write [...] undefined !"
and when im trying to insert the module it says me
"Unknown symbol vfs_write (err -2)"
i am using this method to do the job:Read/write files within a Linux kernel module
Tell me What i did wrong or how to correctly open /to write a file x).
Thanks for all.
|
Since version 4.14 of Linux kernel,vfs_writefunction isno longer exportedfor use in modules. Usekernel_writeinstead. It has the the same signature:
```
ssize_t kernel_write(struct file *file, const void *buf, size_t count,
loff_t *pos)
```
|
How can I make a function that either returns zero or an array of numbers. My function should test if the input string with a string two hexadecimal numbers separated by a space, such as this string:"a48 2b4". If it does qualify, return an int array of the two numbers, if not, like if it has non hex characters or too many spaces, return 0. How can I do this in c?
|
I could also use aUnion. A union can store two or more types of values.
```
union OptionalInt {
int Value;
bool IsNull;
};
union OptionalInt ParseHex(char *Str) {
//...
if(/*Success*/) {
return (union OptionalInt){/*Value*/, 0};
}else{
return (union OptionalInt){0, 1};
}
}
```
|
I must add-lmin gcc command when usingpow. One day when I was learning linux thread I saw I must add-lpthreadin gcc command.
I know it might be impossible to find library name via function name. Butis there a way to find what library name should I add? Maybe via the header's name? Now the only way I know is searching other's experience.
|
Look into the documentation; forman powyou will read
Link with -lm.
forman pthread_yieldyou will read
Compile and link with -pthread.
Such a documentation does not exist everytime; you might have to look at other places too (e.g. pdf, info pages, web sites).
|
need string lenght for my scanf , how do i determine what number to put betwen [], can use A[strlen].
```
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main()
{
char A[];
printf("enter a string");
scanf("%s", A);
printf("%s", A);
getch();
}
```
|
Only you can know what length is sufficient for your needs.
If there is a limited set or range of valid inputs, you can use the length of the maximum valid input + 1.
If there isn't a limit to the maximum valid input, either you need to decide that your program doesn't support input longer than X and set that as the limit, or implement reading in a loop into a dynamically growing buffer (e.g., usingreallocas needed).
And always remember to limit the maximum allowed input length when reading, so that it's not possible to overflow your buffer with excessive input. (Usingfgetsis often the simplest to get right.)
|
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.Closed4 years ago.Improve this question
IDA can do this:some function with no symbol will named with 'sub_address'.
How can I do this at runtime.
enter image description here
|
In short, you disassemble all exported functions and look forcallinstructions. For eachcallinstruction you take the address operand and mark it as another function, and disassemble it too. Ditto recursively.
Such functions, found fromcalloperands, are what IDA callssub_XXXX.
|
I wrote the following c - codesnippet:
```
#include <stdio.h>
void function(int size){
int array[size];
for(int i = 0; i < size; i++){
printf("%d ", array[i]);
}
}
int main(){
int array_size;
scanf("%d",&array_size);
function(array_size);
return 0;
}
```
Why it is possible to generate an array of dynamic size this way. Normally I would use malloc, but this works as well. Why it is allowed to use the non constant variable size for the size of an array?
|
This is what is known as a"Variable-length array".
Variable-length automatic arrays have been supported since C99
They are declared like a normal array, but length is not constant and storage is allocated at the point of declaration.
More on this can be found @gcc.gnu.org
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed4 years ago.Improve this question
In my program I need to handle mathematical expressions like:
```
sin(x) + x^2 + x
```
so I have to create a C function like:
```
double my_function(double x) {
return sin(x) + x*x + x;
}
```
The problem is that the program has to manage any kind of function whose form factor is not known a priori.
The function has to be read from a .txt file, is there any method to parse them?
|
There are many available projects doing it.
For example:https://github.com/codeplea/tinyexpr
Clone, test & see how it is done
|
I've read a file called names.txt which contains firstname and secondname. I printed the names out, just to see, if it's working
```
for (int counter = 0; counter < 10; counter ++) {
fscanf(names, "%s %s\n", firstname, secondname);
printf("%s%s\n", firstname, secondname);
}
```
I tried to access a specific string with firstname[x] but this gets me the single char in the firstname
is it possible now, to only print let's say the 7th firstname and secondname of the red file names.txt?
|
```
for (int counter = 0; counter < 10; counter ++)
{
fscanf(names, "%s %s\n", firstname, secondname);
if(counter==6)
printf("%s%s\n", firstname, secondname);
}
```
This code will now print only 7th firstname and secondname,
|
I wrote the following c - codesnippet:
```
#include <stdio.h>
void function(int size){
int array[size];
for(int i = 0; i < size; i++){
printf("%d ", array[i]);
}
}
int main(){
int array_size;
scanf("%d",&array_size);
function(array_size);
return 0;
}
```
Why it is possible to generate an array of dynamic size this way. Normally I would use malloc, but this works as well. Why it is allowed to use the non constant variable size for the size of an array?
|
This is what is known as a"Variable-length array".
Variable-length automatic arrays have been supported since C99
They are declared like a normal array, but length is not constant and storage is allocated at the point of declaration.
More on this can be found @gcc.gnu.org
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed4 years ago.Improve this question
In my program I need to handle mathematical expressions like:
```
sin(x) + x^2 + x
```
so I have to create a C function like:
```
double my_function(double x) {
return sin(x) + x*x + x;
}
```
The problem is that the program has to manage any kind of function whose form factor is not known a priori.
The function has to be read from a .txt file, is there any method to parse them?
|
There are many available projects doing it.
For example:https://github.com/codeplea/tinyexpr
Clone, test & see how it is done
|
When I run coreFlightSystem with my custom application, I get the following log message:
```
ES Startup: Loading file: /cf/apps/lls_app.so, APP: LLS_APP
ES Startup: loading directly:/cf/apps/lls_app.so (LLS_APP) -70028.
ES Startup: Could not load cFE application file:/cf/apps/lls_app.so. EC = 0xFFFFFFFF
```
I have checked, andlls_app.sois built and placed in the correct location (build/cpu1/exe/cf/apps/lls_app.so).
|
Failing to load an application may be caused by a number of issues. A few things to check:
Check that the application is be generated (the.so) and is in the correct directoryReview the startup script to make sure that the application name and entry location are correctCheck for warnings such as undefined references when building.
This specific case was caused by a typo in a function name called by the application's*_AppInitfunction. This resulted in an undefined reference warning when building.
|
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.Closed4 years ago.Improve this question
The following function is not compiling:
```
double GetCurTime()
{
LARGE_INTEGER CounterFreq;
QueryPerformanceFrequency(&CounterFreq);
LARGE_INTEGER Counter;
QueryPerformanceCounter(&Counter);
return (double)Counter.QuadPart / (double)CounterFreq.QuadPart;
}
```
The C the compiler I am using does not recognizeLARGE_INTEGERandQueryPerformanceFrequency.
If anyone recognizes these items, can you please suggest where I might find them?Perhaps they are in a header file, or a library that I do not currently have.
|
Include the<time.h>library and use thetime_t time(time_t *timer);function.
Also, if you want to use QueryPerformanceCounter, then you need to include Winbase.h (and Windows.h).
|
Somewhere I read that unary operators are atomic by nature and so they can be used as it is in multi threaded environment. To confirm the same, I wrote two separate programs where in
I used a variable x and incremented using unary operator ++xI used a variable x and incremented using x=x+1
I compared the disassembly of both programs and found no difference. Please provide your inputs on this.
|
Somewhere I read that unary operators are atomic by nature and so they can be used as it is in multi threaded environment.
That source is completely wrong. You need to usestd::atomic(or the C equivalent) to achieve atomicity – unary operations are not special.
I compared the disassembly of both programs and found no difference
That doesn't mean that the generated operations are atomic. There is no difference as any decent compiler will optimizex=x+1and++xinto the same assembly (assuming built-in types).
|
ERROR: type should be string, got "\nhttps://www.bytereef.org/mpdecimal/doc/libmpdec/assign-convert.html\n\n```\nmpd_t *mpd_qncopy(const mpd_t *a);\n```\n\nReturns a pointer to a fresh copy of a, NULL on failure.\n\nWhat does\"a fresh copy\"mean? \nWhere does itallocatethenew pointerwithout anympd_context_tgiven?\n" |
"Fresh copy" means allocate memory and copy the decimal object over. Thefull implementationis:
```
mpd_t *
mpd_qncopy(const mpd_t *a)
{
mpd_t *result;
if ((result = mpd_qnew_size(a->len)) == NULL) {
return NULL;
}
memcpy(result->data, a->data, a->len * (sizeof *result->data));
mpd_copy_flags(result, a);
result->exp = a->exp;
result->digits = a->digits;
result->len = a->len;
return result;
}
```
It is unclear why you think anmpd_context_tobject would need to be provided, as no operation is performed on the decimal.
|
This program tells whether a given input is prime or not but I don't understand what exactly the for loop does here? It has no brackets and no statements in it.
```
int main(void)
{
int n;
printf("Enter an integer number (> 1): ");
if (scanf("%d", &n) != 1 || n <= 1) {
printf("Invalid input. Quit!\n");
return -1;
}
int d;
for (d = 2; n % d != 0; d++)
;
if (d == n)
printf("%d is prime\n", n);
else
printf("%d divides into %d\n", d, n);
return 0;
}
```
|
It doesn't need a body, the purpose is just to incrementduntil the conditionn % d != 0is false (i.e. whenn % d == 0is true). It's not doing anything withdduring this process.
At the end of the loop,dwill be the lowest factor ofn. Ifd == nit means thatndoesn't have any factors other than itself and 1 (which isn't checked, since the loop starts atd = 2), i.e. it's prime.
|
Is there function in a C library that iterates through an array and checks if two characters are next to each other?
For example :array[30] = "[email protected]"Is it possible to go through the array and check if '@' and '.' are next to each other?
|
Usestrstr:
```
if (strstr(array, "@.") || strstr(array, ".@"))
/* the characters are touching */
```
|
I have made a program using the below initialization
```
int j=35,l;
l=~j;
```
iflis printed as%dthen the output is -36
|
The bitwise compliment operator~invertsallbits of its operand. So assuming anintis 32 bits, the binary value:
```
00000000 00000000 00000000 00100011
```
Becomes this after applying~:
```
11111111 11111111 11111111 11011100
```
Assuming negative numbers are represented in two's complement representation, this value is -36.
The value 222 you were expecting looks like this in binary as anint:
```
00000000 00000000 00000000 11011110
```
So it seems you were expecting that only the least significant byte gets inverted, but instead the bits in all bytes get inverted.
|
Somewhere I read that unary operators are atomic by nature and so they can be used as it is in multi threaded environment. To confirm the same, I wrote two separate programs where in
I used a variable x and incremented using unary operator ++xI used a variable x and incremented using x=x+1
I compared the disassembly of both programs and found no difference. Please provide your inputs on this.
|
Somewhere I read that unary operators are atomic by nature and so they can be used as it is in multi threaded environment.
That source is completely wrong. You need to usestd::atomic(or the C equivalent) to achieve atomicity – unary operations are not special.
I compared the disassembly of both programs and found no difference
That doesn't mean that the generated operations are atomic. There is no difference as any decent compiler will optimizex=x+1and++xinto the same assembly (assuming built-in types).
|
ERROR: type should be string, got "\nhttps://www.bytereef.org/mpdecimal/doc/libmpdec/assign-convert.html\n\n```\nmpd_t *mpd_qncopy(const mpd_t *a);\n```\n\nReturns a pointer to a fresh copy of a, NULL on failure.\n\nWhat does\"a fresh copy\"mean? \nWhere does itallocatethenew pointerwithout anympd_context_tgiven?\n" |
"Fresh copy" means allocate memory and copy the decimal object over. Thefull implementationis:
```
mpd_t *
mpd_qncopy(const mpd_t *a)
{
mpd_t *result;
if ((result = mpd_qnew_size(a->len)) == NULL) {
return NULL;
}
memcpy(result->data, a->data, a->len * (sizeof *result->data));
mpd_copy_flags(result, a);
result->exp = a->exp;
result->digits = a->digits;
result->len = a->len;
return result;
}
```
It is unclear why you think anmpd_context_tobject would need to be provided, as no operation is performed on the decimal.
|
This program tells whether a given input is prime or not but I don't understand what exactly the for loop does here? It has no brackets and no statements in it.
```
int main(void)
{
int n;
printf("Enter an integer number (> 1): ");
if (scanf("%d", &n) != 1 || n <= 1) {
printf("Invalid input. Quit!\n");
return -1;
}
int d;
for (d = 2; n % d != 0; d++)
;
if (d == n)
printf("%d is prime\n", n);
else
printf("%d divides into %d\n", d, n);
return 0;
}
```
|
It doesn't need a body, the purpose is just to incrementduntil the conditionn % d != 0is false (i.e. whenn % d == 0is true). It's not doing anything withdduring this process.
At the end of the loop,dwill be the lowest factor ofn. Ifd == nit means thatndoesn't have any factors other than itself and 1 (which isn't checked, since the loop starts atd = 2), i.e. it's prime.
|
Is there function in a C library that iterates through an array and checks if two characters are next to each other?
For example :array[30] = "[email protected]"Is it possible to go through the array and check if '@' and '.' are next to each other?
|
Usestrstr:
```
if (strstr(array, "@.") || strstr(array, ".@"))
/* the characters are touching */
```
|
I want to change auint8_tarray type to aintorstringtype, so i can write it in a text file.
for example array:
uint8_t outstr[4]; \\ outstr is 0x00 0x04 0x49 0xba
i tried using this code:
fprintf(ptr_myfile, "%d \n", *outstr);
this code give me only the first number '0' ,but I need the all array.
the expected result of the hex number0x000449bashould be281018.
|
If your array size is always 4 you could create auint32_tvariable:
```
uint32_t num = 0;
for(int i=0; i<4; i++)
{
num <<= 8;
num |= outstr[i];
}
fprintf(ptr_myfile, "%" PRIu32 "\n", num);
```
|
Whenever I try to use a float value in thisIF ELSE statementit gives me0or an incorrect answer. I have usedINTfor the rest of the code and the rest works fine. This is the first time I have used float in the code and now it's not giving me the answer I want.
Can you please tell me what am I doing wrong?
```
float interestrate;
if (month < 49)
{
interestrate = (0.063);
}
else if (salary <= 25000)
{
interestrate = (0.033);
}
else if (salary > 45000)
{
interestrate = (0.063);
}
else
{
interestrate = (0.033+(salaryabovethreshold*0.0000015));
}
printf("Interest Rate: %d \n", interestrate);
```
|
The%dformat specifier is forints, notfloats. Try%f,%eor%gor%afor floating-point types.
|
I used to work on java i'm new to C. I'm facing some issues.
Here i'm continuosly receiving data from a source. After reaching the count 3 i need to passthe whole data from count 1 to 3 to another function.
```
void check_msg_id( uint8_t *recvdata) {
uint8_t buffer1[3];
cnt=0;
buffer1[cnt]=recvdata;
cnt++;
if (cnt==3) {
cnt=0;
}
}
```
How can i pass the data from all counts to a buffer?
Any help will be appreciated.
Thanks in advance
|
You can pass the data to another function by.
```
void check_msg_id( uint8_t *recvdata) {
uint8_t buffer1[3];
cnt=0;
buffer1[cnt]=recvdata;
cnt++;
if (cnt==3) {
cnt=0;
pass_data(buffer1); //create a function
}
```
}
You can pass this where ever you want.
|
Why this recursive function is falling in infinite loop ? It showing value of Val is not decreasing. What's the logic behind.
```
int Bar(int Val) // value passed is 3
{
int x=0;
while (Val>0)
{
x=x+Bar(val-1);
}
return Val
}
```
|
It is not the recursion, but the while cycle which never ends.
```
while (val>0) {
x=x+bar(val-1);
}
```
In this loop, you never change the value ofval. So the loop never terminates.
|
In code i'm getting this warning while compiling.
I tried to fix this my i'm unable to solve this issue.
```
static uint8_t tx_data;
int *recvdata2,*recvdata;
recvdata= str2int(tx_data); //warning assignment from incompatible pointer type
recvdata2=(uint8_t*)&recvdata
```
str2int is a function to convert the string to integer.
```
int str2int(char *str)
{
int res=0;
int i;
for ( i = 0; str[i] != '\0'; ++i)
res=(res)*10+str[i]-'0';
return res;
}
```
I'm a noobie to this. Please help me to fix this issue.
Any help will be appreciated.
|
Currently you are trying to assigninttoint *You seerecvdatais pointer toint.
Modify as below.
```
int *recvdata2, recvdata;
recvdata = str2int(tx_data);
recvdata2 = &recvdata
```
|
I was wondering if it is possible to build a string with the following code
```
char query[512];
char *insert = "insert into tableName values("%s, "%s");"
strcpy(query, insert);
method("max", "1234"); //function which adds values inro %s
```
My questions, how can I add another char array into in place of %s if it is possible?
Thanks beforehand.
|
use sprintf() so that you can replace the %s with char arrayhttps://linux.die.net/man/3/sprintf
```
char query[512];
char *insert = "insert into tableName values(\'%s\',\'%s\');";
sprintf(query, insert, "max","234");
printf("%s",query);
```
This is actually a bad approach. This will introduce SQL Injection vulnerabilities.
|
I have to use prototype poly float to computef(x)=5x^2+12.55x+0.75. I have error every time I run this code because poly is not used. Any help will be good and any tips for prototypes too.
```
#include<stdio.h>
float poly(float x)
{
return 1;
}
int main()
{
float b, c, a;
printf("Podaj x=");
a = scanf("%f", &b);
c = 5 * b * b + 12.55 * b + 0.75;
if(a<1)
{
printf("Incorrect input");
return 1;
}else
{
printf("Wynik: %.2f", c);
return 0;
}
}
```
|
Changepolyto:
```
float poly(float x)
{
return 5*x*x + 12.55*x + .75;
}
```
In main, you can use the function:
```
print("poly(%g) = %g.\n", b, poly(b));
```
|
I am new to the programming world and I'm trying to make a string split by using a loop that should split all characters separately but it's being ignored and basically ends with showing the input of the user instead of using the loop to separate the individual letters/characters. Have I missed declaring something important in the loop?
|
for (i = 0; str[i] != '\0'; i++);<- there's a semicolon here, so your loop literally does nothing
also note thatstr[i] != '\0'is a very dangerous way of iterating your string. If your string doesn't contain a zero-terminal character, C will happily continue reading memory beyond the end.
|
I've wrote this very basic code-lines with colored output:
```
printf("\033[1;32m"); // boldgreen code: \033[1;32m according to:
http://web.theurbanpenguin.com/adding-color-to-your-output-from-c/
puts("Enter username:");
gets(user);
```
In my computer evreything works fine and I get colored output as expected:
but in other computers I get this Output:
```
\033[1;32mEnter username:
```
I have to say that all my #includes are fine, Im just doing copy-paste to another computer & if thats important Im using Visual Studio in both Computers.
seems like basic thing but I don't understand why thats happend.
Thanks for helpers.
|
Most terminals support colors. The problem is sending the right escape code. For the Windows command line, you have do a different escape sequence.There is a wikipedia entry that describes how to do an escape in different environments.
|
Why is this erroneous?
```
char *p;
*p='a';
```
The book only says -use of uninitialized pointer.
Please can any one explain how that is?
|
Yes, it may cause a run-time error since it isundefined behavior. The pointer variable is defined (but not properly initialized to a valid memory location), but it needs memory allocation to set value.
```
char *p;
p = malloc(sizeof(char));
*p = 'a';
```
It will work whenmallocsucceeds. Please try it.
|
This question already has answers here:What is the size of an enum in C?(7 answers)Closed4 years ago.
if I create anenumlike so
```
enum test {
a=0,
b
};
```
Is a variable of typeenum teststored as 1 bit in memory, as that's the minimum needed to represent it?
|
According to the language specification, the size of an enum is guaranteed to be at most the size of an integer. Keeping that in mind, the compiler is free to choose the actual size upon analyzing the source code.
Having said that, you can usehttps://godbolt.org/to explore the asm output of various C compilers running on loads of different CPU architectures. From there, you can figure out the actual size on your specific configuration.
|
Doescalloc()of a double field always evaluate to0.0?
Furthermore:
Doescalloc()of afloatfield always evaluate to0.0f?Doescalloc()of anintorunsigned intfield always evaluate to0?
That is, will theassert()below always succeed on all platforms?
```
double* d = calloc(1, sizeof(double));
assert(*d == 0.0);
free(d);
```
|
C11 documentation has this explicit notice forcalloc
FootnotesNote that this need not be the same as the representation of
floating-point zero or a null pointer constant.
In practice, all zero bits is a (or the) representation for 0.0 on all major platforms as they use IEEE 754 representation. Yes, this will hold on Intel, ARM, Linux, Windows, Mac, Raspberry PI, the smartphones.
|
Doescalloc()of a double field always evaluate to0.0?
Furthermore:
Doescalloc()of afloatfield always evaluate to0.0f?Doescalloc()of anintorunsigned intfield always evaluate to0?
That is, will theassert()below always succeed on all platforms?
```
double* d = calloc(1, sizeof(double));
assert(*d == 0.0);
free(d);
```
|
C11 documentation has this explicit notice forcalloc
FootnotesNote that this need not be the same as the representation of
floating-point zero or a null pointer constant.
In practice, all zero bits is a (or the) representation for 0.0 on all major platforms as they use IEEE 754 representation. Yes, this will hold on Intel, ARM, Linux, Windows, Mac, Raspberry PI, the smartphones.
|
```
#include<stdio.h>
int main()
{
int a = 0, b = 1, c = 2;
*((a+1 == 1) ? &b : &a) = a ? b : c;
printf("%d, %d, %d\n", a, b, c);
return 0;
}
```
The output of the program is 0, 2, 2. How does the conditional statement change the value of variable b in C?
|
Let's look at this row:
```
*((a+1 == 1) ? &b : &a) = a ? b : c;
```
(a+1 == 1)is1so this becomes
```
*(1 ? &b : &a) = a ? b : c;
```
Which is
```
*(&b) = a ? b : c;
```
Sinceais still0, that is
```
*(&b) = c;
```
This means that the address ofbis taken, and the value that it points to (b) is set toc, which is2. So in the end, what it does is changingbto2.
If the ternary operator (?) confuses you, you can read up on ithere.
|
The question concerns implicit multiplication by the-operator.
For example
```
float a = 10;
float b;
```
b = -a;Is this valid? doesb = -10?
|
This isn't implicit multiplication, but use of the unary-operator.
The code is valid, since the operator works on all arithmetic types, including floating point.
|
```
int i=3,j=5;
int *p, *q;
p = &i;
q = &j;
printf("%d\n", 3* -*p/(*q)+7);
```
The compiler says the result is 6, but i can't understand how, for me it was suposed to be (-9/12) = -0,74 or 0 beacause is a int, can anyone help?
|
Taking into account the precedence rules that are implicitly encoded inthe grammar of the C language,3* -*p/(*q)+7is((3 * (-*p)) / (*q)) + 7.
The result of-9 / 5is-1because/represents integer division here.
The result of-1 + 7is 6.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.