question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I tried to read 2 variables from the keyboard and to write them on the screen and I have a problem, the program display me only one..
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
short int n,x;
scanf("%d",&n);
scanf("%d",&x);
printf("%d %d",n,x);
return 0;
}
```
I introduced 14 and 15... |
Use %hd format specifier for short int
Use %hu format specifier for unsigned int
Use %d format specifier for int
Use %ld format specifier for long int
```
#include <stdio.h>
#include <stdlib.h>
int main() {
short int n, x;
scanf("%hd", &n); // Notice %hd instead of %d for short int
scanf("%hd", &x); // Notice ... |
I am having a question for myself while taking operating system course.
If I type in any C code to my text editor or though IDE and execute it with the compiler
it translates the code into machine code.
Then I would guess if I run the program, the OS will allocate a memory address to the code which is done by kernel... |
In the ordinary course of events, any code you write is 'user mode code'. Kernel mode code is executed only when you execute a system call and the control jumps from your user code to the operating system.
Obviously, if you're writing kernel code, or loadable kernel modules, then things are different — that code wil... |
In C, I can bind a client socket to a specific local address and a system-selected port. What would happen if any of the following happened?
The local address of the machine is changedThe program is moved to a host with a different local address
And what would happen if I attempt to bind after calling connect()?
|
Well, in general, a TCP socket connection is really identified by the source IP, source port, destination ip, destination port tuple. If say the source IP is not valid any more then neither end can recover from it and the destination host will not probably notice until after a timeout.
If on the other hand you're try... |
I tried to read 2 variables from the keyboard and to write them on the screen and I have a problem, the program display me only one..
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
short int n,x;
scanf("%d",&n);
scanf("%d",&x);
printf("%d %d",n,x);
return 0;
}
```
I introduced 14 and 15... |
Use %hd format specifier for short int
Use %hu format specifier for unsigned int
Use %d format specifier for int
Use %ld format specifier for long int
```
#include <stdio.h>
#include <stdlib.h>
int main() {
short int n, x;
scanf("%hd", &n); // Notice %hd instead of %d for short int
scanf("%hd", &x); // Notice ... |
I am having a question for myself while taking operating system course.
If I type in any C code to my text editor or though IDE and execute it with the compiler
it translates the code into machine code.
Then I would guess if I run the program, the OS will allocate a memory address to the code which is done by kernel... |
In the ordinary course of events, any code you write is 'user mode code'. Kernel mode code is executed only when you execute a system call and the control jumps from your user code to the operating system.
Obviously, if you're writing kernel code, or loadable kernel modules, then things are different — that code wil... |
In C, I can bind a client socket to a specific local address and a system-selected port. What would happen if any of the following happened?
The local address of the machine is changedThe program is moved to a host with a different local address
And what would happen if I attempt to bind after calling connect()?
|
Well, in general, a TCP socket connection is really identified by the source IP, source port, destination ip, destination port tuple. If say the source IP is not valid any more then neither end can recover from it and the destination host will not probably notice until after a timeout.
If on the other hand you're try... |
Using c language, If I have I declared four random integers how do I go about storing them inside the series variable and then accessing them?
```
int a =3;
int b=4;
int c=5;
int d=6;
typedef struct struct1
{
int *series;
int num1;
double num2;
double num3;
}
Struct1;
```
I declared the struct as
```
Struct1 my... |
First of all you allocate the memory you need to store them usingmalloc. You'll need to include<stdlib.h>to access that function. You need enough space for 4intso:
```
mystruct.series = malloc(4 * sizeof(int));
```
Then you just store and access the data like you'd do for any other array:
```
mystruct.series[0] = a... |
In<math.h>the constantM_2_SQRTPIis defined with the value2/sqrt(pi).
I have never seen this expression used in a formula, so I searched for uses ofM_2_SQRTPIbut I could only found documentation about the constant and no actual uses of it.
Where is the constant used and what is the reason it is defined in<math.h>as a... |
The constant is related to theerror function.
I don't know why it's provided as a constant inthe standard libraryPOSIX, though. With GCC on a x86-64 system, and by extension on every system conforming to IEEE 754, computing2.0 / sqrt(M_PI)yieldsexactlythe same double-precision value asM_2_SQRTPI.
Try it online!
Eve... |
mkdir() is in<sys/stat.h>whereas rmdir() is in<unistd.h>. Wouldn't it make more sense to have them in the same header file?
|
The reason is, that withmkdir(2)you specify thepermissionsin the second argument:
```
int mkdir(const char *pathname, mode_t mode);
```
These mode-flags and the typemode_tare defined insys/stat.h(at least indirectly by includingbits/stat.handbits/types.hon my system), so it seems appropriate to define mkdir() there,... |
The code is given below.
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main ( int argc, char *argv[] )
{
//FILE *fps;
char secret[512] =" ";
FILE *fps = fopen("/etc/comp2700/share/secret", "r");
if(fps == NULL)
{
printf("Secret file not found\n");
return 1;
}
... |
You need to compile your source file with gcc as follows
gcc -o attack attack1.c
then run it with
./attack
You should read up on the difference betweencompiledversusinterpretedlanguages.
There is a short videohereexplaining the difference.
|
I am following instructions to write a program of characters counting:
```
#include <stdio.h>
main()
{
double nc;
for (nc=0; getchar() != EOF; ++nc);
printf("%.0f\n", nc);
}
```
After it was compiled and run,
```
$ ./a.out
ff
fdg
fd
fdr
```
It did not print the counting.What's the problem with my co... |
I'm pretty sure you never enterEOF.
UseControl+Zon Windows orControl+Don UNIX/Linux/OSX to getEOF.
|
If I have, e.g.:
```
#include <stdlib.h>
int f(void) { return 42; }
int g(void) { return 43; }
int main()
{
if(f()!=g())
abort();
}
```
Is it possible to obtain the return values off()andg()from the core dump without having the original code assign them to variables? (int lhs, rhs; if((lhs=f())!=(rhs=g()... |
No—even without inlining, the comparison is likely to be compiled as a subtraction followed by a test against zero, such that at least one return value was no longer present (in registers or in memory) at the time of the dump.
With optimization, even storing the values in variables is of no help: it will surely elimi... |
I'm using the software timer API from FreeRTOS to create a timer
```
xTimer = xTimerCreate("Timer", 100, 0, (void *) 0, vTimerCallback0);
```
Is there a way to change to callback of the timer to another function?
|
Another way to do it could be that the callback that you register when the timer gets created (vTimerCallback0) calls one from a set of other functions after some decision making in your code. It depends on what exactly you are trying to do.
|
the status of the echo bit in the driver for file descriptor 0. Use redirection operator < to attach standard input to other files of devices. Try these experiments:
```
$ ./echostate < /dev/pts/0
$ ./echostate < /etc/passwd
```
Output
plz explain to me the output produced by each of these commands.
i don't know... |
tcgetattrdoesn't make sense on a file (/etc/passed), but only on certain types of devices.
That's what the error message is telling you.
|
```
typedef struct {
int pid;
struct f_queue_node *next;
}f_queue_node;
typedef struct {
f_queue_node *front, *rear;
}f_queue;
f_queue *queue;
f_queue_node *node
queue->rear->next = node;
```
I get a warning whenever I use a pointer of f_queue_node with front and rear.
queue_f.c:39:21: wa... |
Use this:
```
typedef struct f_queue_node {
int pid;
struct f_queue_node *next;
} f_queue_node;
```
instead of:
```
typedef struct {
int pid;
struct f_queue_node *next;
} f_queue_node;
```
That's happens because of youtypedefananonymous struct.
Also, you misssemicolonheref_queue_no... |
I have a problem. I need to insert a specific char (number sign) into my output value. I am not allowed to use if statement and "? :" statement. My output needs to look like this:
```
9999.999(+/-)i9999.999
```
Where character "i" needs to go right after the 2nd number sign. Here is my code so far:
```
void show(st... |
without if or ternary
```
void show(struct z z) {
printf("%.3f%ci%.3f", z.re, "+-"[z.im<0], fabs(z.im));
}
```
|
Take for example the following code:
```
int main(){
char string[] = { 'h' , 'e', 'l', 'l', 'o' };
printf(string);
printf("\n%d", strlen(string));
}
```
The output will be:
```
hello
6
```
So right off the start I can see that thestrlenvalue is off by 1, but it doesn't seem like such a hurdle if we acc... |
What are the repercussions of not using null termination in strings?
Technically none, because C strings are -by definition- terminated by a null character:
A string is a contiguous sequence of characters terminated by and including the first null character.
So if it's not properly terminated, it's not a string.
I... |
When I compile the following C source withgccversion 8.1.1, I get awarning: ‘stdcall’ attribute ignored [-Wattributes].
Why does gcc choose to ignore this attribute and what can I do to make it accept it?
```
__attribute__((stdcall)) int S(int a) {
return a * (a+1);
}
int main() {
return S(6);
}
```
|
Thegcc documentationsays:
stdcallOn x86-32 targets, thestdcallattribute causes the compiler to assume that the called function pops off the stack space used to pass arguments, unless it takes a variable number of arguments.
(Emphasis mine.)
So if you're not compiling for a 32-bit machine,stdcallcan't be used.
|
```
#include <stdio.h>
#include <string.h>
int main()
{
char x[5];
char y[10];
scanf("%s",x);
scanf("%s",y);
printf("%s %s",x,y);
}
```
I typed "hello world" in the terminal, but the printf result is "helloworld world".
Is there something wrong I'm doing?
|
Never, never, really never use the"%s"format specifier without a WIDTH to tellscanf()how many characters it may put into the memory pointed to by the argument.
```
char str[5];
scanf("%4s", str);
```
|
I have this C program:
```
#include <stdio.h>
#include <math.h>
main() {
int I;
double A[3]={0.0, 1.0, 2.0};
double B[3]={0.0, 1.0, 2.0};
double C[3]={0.0, 1.0, 2.0};
double X[3];
for (I=0; I<3; I++) {
X[I] = A[I] * ( B[I] - C[I] )**2;
}
}
```
compiling produces an error:
invalid type argument ... |
Here you are presumably trying to square an expression.
```
X[I] = A[I] * ( B[I] - C[I] )**2;
```
Do it like this instead:
```
X[I] = A[I] * pow(B[I] - C[I], 2.0);
```
I don't think there's an integerpowinmath.h, butthis answerprovides a nice implementation.
|
```
#include <stdio.h>
#include <string.h>
int main()
{
char x[5];
char y[10];
scanf("%s",x);
scanf("%s",y);
printf("%s %s",x,y);
}
```
I typed "hello world" in the terminal, but the printf result is "helloworld world".
Is there something wrong I'm doing?
|
Never, never, really never use the"%s"format specifier without a WIDTH to tellscanf()how many characters it may put into the memory pointed to by the argument.
```
char str[5];
scanf("%4s", str);
```
|
I have this C program:
```
#include <stdio.h>
#include <math.h>
main() {
int I;
double A[3]={0.0, 1.0, 2.0};
double B[3]={0.0, 1.0, 2.0};
double C[3]={0.0, 1.0, 2.0};
double X[3];
for (I=0; I<3; I++) {
X[I] = A[I] * ( B[I] - C[I] )**2;
}
}
```
compiling produces an error:
invalid type argument ... |
Here you are presumably trying to square an expression.
```
X[I] = A[I] * ( B[I] - C[I] )**2;
```
Do it like this instead:
```
X[I] = A[I] * pow(B[I] - C[I], 2.0);
```
I don't think there's an integerpowinmath.h, butthis answerprovides a nice implementation.
|
For example:
```
int x = 7 // x is variable name
int* p_x = &x // p_x is a pointer to x
int** pp_x = &p_x // pp_x is a double pointer to x.
```
Is there a quick way to go fromxtopp_xwithout using a intermediate variablep_x?
EDIT:
Thanks to the comments below I realized that such a thing isn't really ... |
If you are targeting anything above C99 you could use compound literals - like following:
```
int **pp_x = (int *[1]){(int[1]){7}};
```
|
I start to work on a huge project with tones of C and C++ files, already wrote by someone else.
Is there any faster/simpler ways to find in what file any macro or function is define other than agrep -r? It is kind of long.
In some IDE there is thismagicalthing like right click and "go to definition". But I'm current... |
CTags. You can try using Ctags with emacs and it will help you to navigate to the function declaration directly. For its usage, please refer tohttps://www.emacswiki.org/emacs/EmacsTags
You can also explore Cscope, It has a better feature set than ctags which works directly on pattern recognition. But sometimes, you j... |
I'm trying to read a series of integers from a text file that is formatted as follows:
```
int1
int2
int3
int4
int99
```
ie. every integer has the same string in front of it, in this case 'int'.
I've tried the following code, but the program only prints the first integer and then ends.
```
FILE *fp = fopen("data.t... |
adding a space after %d will do the job.
```
(fscanf(fp1,"int%d ", &num)==1)
```
|
I have the following code:
```
int main()
{
char i = 0;
for (; i++; printf("%d", i));
printf("%d", i);
return 0;
}
```
It successfully compiles and prints1. I am new to C and I don't understand this. I thought i++ will always be true and so it will be an infinite loop.
Can someone please explain ... |
i++ispost-increment. So at the time of checking the statement, the value ofiis0, which isfalse. Hence, the loop breaks.
|
when I try to write this code:
```
int main(){
/*1.*/char A[16];
/*2.*/char B[16];
/*3.*/char C[16];
/*4.*/scanf(" %15[^\n]",A);
/*5.*/scanf(" %15[^\n]",B);
/*6.*/scanf(" %15[^\n]",C);
```
and for example after line 4 the input I getting from the user is: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"(30*a... |
You can eat up the characters until\n.
To do that you can use%*[\n]specification.
Where%*[\n]specification reads and ignores the characters until it reaches\n.
Example:
```
scanf(" %15s%*[^\n]",A);
scanf(" %15s%*[^\n]",B);
scanf(" %15s%*[^\n]",C);
```
|
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed4 years ago.Improve this question
Could someone explai... |
Becauseais an array and having storage address, buta + 1is an operation without saving to a variable, and&(a + 1)means the address of that operation and it does not mean anything inC. Hence, this&is found as a bitwise operator by the compiler, so you are getting this error.
|
What does the following mean in C programming language?
I understand, that in my first line I have a hex-literal
I don't really understand what my 2nd line is doing. Without actually running the code, how can I find out what this code is doing? I'm studying for an exam where I will have to do this on paper.
```
int a... |
In the second line:
">>" indicates a bit shift to the right, "<<" is a bit shift to the left.
So it's going to print a string to the console with the value of aaa shifted 12 right then shifted 16 left.
To expand: convert the hex value to binary, shift every bit right 12, convert to an int with 8 places.
Then shift al... |
I have a header file in which I create a map array
#define MAP { {WALL,WALL,WALL,WALL,WALL,WALL,WALL,WALL,WALL,WALL,WALL,WALL}, {WALL,START,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,WALL,END,EMPTY,EMPTY,WALL} }
however I'm getting the error:expected expression before"{" token
May somebody help me understand why and how to corr... |
When using multi-lines with#defineyou need to add the escape character\. So:
```
#define MAP { {WALL,WALL,WALL,WALL,WALL,WALL,WALL,WALL,WALL,WALL,WALL,WALL}, \
{WALL,START,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,WALL,END,EMPTY,EMPTY,WALL} }
```
Otherwise the compiler thinks the next line doesn't belong to the macro.
|
I used code blocks to make a project with main.c:
```
#include <stdio.h>
#include "t.h"
int main()
{
printf("%c\n", return_f('f'));
printf("%c\n", return_f(return_char(71)));
printf("%d\n", STATIC_INT);
return 0;
}
```
And t.h:
```
static int STATIC_INT = 14;
static unsigned char return_char(char... |
t.his included textually before the actual compilation process takes place. Thereforestatic int STATIC_INT = 14;is part of yourmain.cfile.
The real problem is that you are declaring variables in a header file which is almost always wrong.
|
All the solutions I have seen online has calloc() function used twice, is it possible to do with only using it once?
The below code is not printing the correct array elements
```
int **ptr;
//To allocate the memory
ptr=(int **)calloc(n,sizeof(int)*m);
printf("\nEnter the elments: ");
//To access the memory
for(i=... |
Since C99 you can use pointers to VLAs (Variable Length Arrays):
```
int n, m;
scanf("%d %d", &n, &m);
int (*ptr)[m] = malloc(sizeof(int [n][m]));
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
scanf("%d", &ptr[i][j]); // Notice the address of operator (&) for scanf
}
}
free(ptr); // C... |
In following code:
```
int main(void)
{
char* a = malloc(sizeof(char));
a[0] = 'a';
a[1] = 'b';
a[2] = 'c';
printf("%s", a);
}
```
Acc. to me a[0] is being allocated memory from heap while a[1] and a[2] are on the stack. I get the output of following code asabc. How is that happening, if stack an... |
You're only allocating room on the heap for onecharina, but you're writing three. The other two don't magically go to the stack; they just overwrite some other probably-important value that happens to be after the one you did allocate. Your program is simple enough that it didn't blow up in your face, but it's still U... |
I have a header file in which I create a map array
#define MAP { {WALL,WALL,WALL,WALL,WALL,WALL,WALL,WALL,WALL,WALL,WALL,WALL}, {WALL,START,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,WALL,END,EMPTY,EMPTY,WALL} }
however I'm getting the error:expected expression before"{" token
May somebody help me understand why and how to corr... |
When using multi-lines with#defineyou need to add the escape character\. So:
```
#define MAP { {WALL,WALL,WALL,WALL,WALL,WALL,WALL,WALL,WALL,WALL,WALL,WALL}, \
{WALL,START,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,WALL,END,EMPTY,EMPTY,WALL} }
```
Otherwise the compiler thinks the next line doesn't belong to the macro.
|
I used code blocks to make a project with main.c:
```
#include <stdio.h>
#include "t.h"
int main()
{
printf("%c\n", return_f('f'));
printf("%c\n", return_f(return_char(71)));
printf("%d\n", STATIC_INT);
return 0;
}
```
And t.h:
```
static int STATIC_INT = 14;
static unsigned char return_char(char... |
t.his included textually before the actual compilation process takes place. Thereforestatic int STATIC_INT = 14;is part of yourmain.cfile.
The real problem is that you are declaring variables in a header file which is almost always wrong.
|
All the solutions I have seen online has calloc() function used twice, is it possible to do with only using it once?
The below code is not printing the correct array elements
```
int **ptr;
//To allocate the memory
ptr=(int **)calloc(n,sizeof(int)*m);
printf("\nEnter the elments: ");
//To access the memory
for(i=... |
Since C99 you can use pointers to VLAs (Variable Length Arrays):
```
int n, m;
scanf("%d %d", &n, &m);
int (*ptr)[m] = malloc(sizeof(int [n][m]));
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
scanf("%d", &ptr[i][j]); // Notice the address of operator (&) for scanf
}
}
free(ptr); // C... |
This question already has answers here:strcmp on a line read with fgets(6 answers)Closed4 years ago.
In this mini version of my program I am asking for user input. When the input is 'quit' or 'exit' I want the program to exit the while loop. The strcmp function doesn't seem to be working as I expect. I've spent some ... |
fgetsreads the trailing\nand stores it in the buffer, so you're always comparingquittoquit\n.
Also at the first time thewhileloop examines its condition, very bad things could happen because yourrequestarray is not initialized.
|
I am trying to run this program in C with Dev C++ in Windows 10:
```
#include <stdio.h>
#include <sys/types.h>
int main()
{
printf("gid_t: %zu\n", sizeof(gid_t));
}
```
And this error shows:
[Error] 'gid_t' was not declared in this scope.
I checked that gid_t is suppose to be with in the sys/types.h file but w... |
You useWindows, but do:
```
#include <sys/types.h>
```
That is not going to work, since that header is part of UNIX (not Windows).
gid_tis not part of Standard C. As a result, it can be found only in platform specific implementations (i.e. UNIX in that case).
An ugly workaround, is to typedef-it yourself, like t... |
I am struggling to find a reason for this, since the books I'm reviewing tell me to initialize a size for my array, yet, this compiles.
```
int main (void){
char word_0[] = "Hola que tal\n";
printf("%s", word_0);
char word_1[20] = "Hola que tal\n";
printf("%s", word_1);
return 0;
}
```
I kn... |
When an array is declared without any size specified but with an initializer, C chooses a size just large enough to accommodate all the elements specified by the initializer. In the case of your
char word_0[] = "Hola que tal\n";
, that is 14 chars (which includes one for the string terminator).
|
I found the following code which calculateslog2offloat x:
```
union { float f; unsigned int i; } vx = { x };
float y = vx.i;
y *= 1.0 / (1 << 23);
y = y - 126.94269504f;
return y;
```
Thefparameter of union is initialized to inputxand then it usesi? I can not understand how it uses something that is not initialized.... |
I can not understand how it uses something that is not initialized.
Actuallyvx.iis initialized. A union will occupy the same memory location. Thereforevx.iis initialized at the same time thatvx.fis initialized.
And what vx.i value is actually?
To get the actual value ofvx.iyou need to understand how a float is stor... |
I want to extract some number from HTTP Get requests in C.
for example if my HTTP request is like:
```
GET /getUIKVal?mdn=9860436150 HTTP/1.1
Host: api.end.point
```
I want number 9860436150 to be printed as output.
I have already tried with sscanf() and atoi()
|
You can simply usesscanflike below.
```
char* line = "GET /getUIKVal?mdn=9860436150 HTTP/1.1";
long long val ;
int ret = sscanf(line, "%*[^=]=%lld",&val);
printf("%lld\n", val) ;
```
Where%*[^=]=will read and discard the string until it reaches=and%ldwill read actual number inval.
|
While reading from a file in C, I was told that I can add an * after the % to disregard that input. For example:
```
fscanf(inputfile, "%lf %lf %*lf", &num1, &num2);
```
In this example the pointer reads three double values, but only two of them need to be stored (the ones without the * sign after the % sign).
Coul... |
The use of*is just a string constant chosen arbitrarily. It has no relation to pointer dereferencing. How it "works" is that the parser in scanf simply parses the type as it would normally then throws away the value rather than looking for a parameter to put it in.
|
I've wrote a program in which I create a thread in main that has a son who calls maFunction to show a text message . The problem is that when I execute this it doesn't work and I don't understand why . Any idea is welcomed . Thank you very much .
```
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#includ... |
Your program end execution before your thread start.
addpthread_join(leThread, NULL);at the end ofmain()
or addsleep(1);and don't forget to include<unistd.h>forsleep()
|
There are several initialization methods in OpenSSL
```
OpenSSL_add_all_algorithms(); /* Load cryptos, et.al. */
SSL_load_error_strings(); /* Bring in and register error messages */
SSL_library_init();
```
Is there a specific order in which they have to be called, if I am using TLS?
|
This question is a little vague, yet:
The order ofSSL_load_error_strings()andOpenSSL_add_all_algorithms()doesn't technically matter.
If you are using OpenSSL 1.1.0 or newer, you do not need to callOpenSSL_add_all_algorithms()at all.The function has been deprecated and superseded byOPENSSL_init_crypto().
Thissuggest... |
What will be the output of the program?
```
#include<stdio.h>
void main()
{
int i = 0;
while(i < 10)
{
i++;
printf("%d\n",i);
}
}
```
Will the output start from 0 or from 1 as I my professor taught me that the value of the variable is incremented only at the end of the loop while using i++ ... |
The side effect of incrementing using either the prefix++or the postfix++occurs before the statementi++;completes. The fact that the statement is in a loop doesn't change that.
Your professor is correct. The first timeprintfis called in the loop,iwill have the value 1 because the previous statement incremented the ... |
I am struggling to understand if there is any overflow with the following equation using 8 bit signed integers.0b00000000 - 0b10000000
|
This question is taggedc, and in C, all arithmetic in types lower-rank thanintgets promoted toint, andinthas at least 16-bit range, so(signed char)0-((signed char)-128)is just 128.
|
This question already has answers here:How do I properly compare strings in C?(11 answers)Closed4 years ago.
When I type hk on the Output, it did not say HONG KONG, It just say INPUT ERROR everytime.
```
char dc,ds[15];
int main(int argc, char *argv[]) {
p("Destination Code: ");
s("%s", &dc);
if(dc=="hk"){
strc... |
Two problems here.
You have declareddcaschartype and trying to read in thestringtype.You cannot use==to compare twostrings, you should usestrcmpinstead.
Example:
```
char dc[3];
scanf("%2s", dc);
if(strcmp(dc,"hk") == 0){
strcpy(ds, "HONG KONG");
}
else{
strcpy(ds, "INPUT ERROR");
}
```
|
When I usereallocto re-size the memory which I usedcallocearlier to initialize (an array), is it still remains 0 in a whole buffer? or the new part is not initialized?
|
Considering you're increasing the size of the allocated memory, theextendedmemory region will have indeterminate values.
QuotingC11, chapter §7.22.3.5, (emphasis mine)
[...] The contents of the new
object shall be the same as that of the old object prior to deallocation, up to the lesser of
the new and old sizes... |
how the "if" block in c will evaluate this . will code inside the "if" block will be executed?
Eg
```
int main(){
int i;
if(i=0){
//some code
}
return 0;
}
```
|
if (i = 0)would assign the value0toiand then it check whether the value of the expression (which is the value assigned, i.e. 0) is non-zero. In other words, it won't execute the body of theif. it'll just set i to 0. It'll also raise a warning on any decent compiler.
also ,if (i = 1)would assign the value 1 to i and a... |
This has to be done in C.
I'm Looking for a way to take an array with elements such as:
```
a = {1,2,3}
```
and given a variable such as i, if i = 3, each element copied into a new array i times like so:
```
b = {1,1,1,2,2,2,3,3,3,}
```
this is what I have so far:
```
for(i = 0; i < size_S-inter_seq; i++) //size ... |
This code should do the trick:
```
int a[] = {1,2,3};
int i = 3;
int len = (sizeof a)/(sizeof a[0]);
int b[i*len];
for(int k=0; k<len; k++)
for(int j=0; j<i; j++)
b[k*i + j] = a[k];
```
|
I am getting a segmentation fault on the following code:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void init_test(char ***test) {
*test = malloc(2 * sizeof(char *));
*test[0] = malloc(3);
*test[1] = malloc(3);
strcpy(*test[0], "12");
strcpy(*test[1], "13");
}
int main()... |
It's a matter ofoperator precedence. The expression*test[0]is equal to*(test[0]), not(*test)[0]as you seem to expect.
|
I used IDA to decompile a function a program and i don`t know what exactly this code work.
```
flag[i] ^= *((_BYTE *)&v2 + (signed int)i % 4);
```
How does this work?
|
This could be used for xor-"decrypting" (or encrypting, the operation is symmetric) a buffer with a 4-byte key. See the following code, which might be a bit better readable, than the decompiler output
```
char flag[SIZE];
char key[4];
for (int i = 0; i < SIZE; i++) {
flag[i] = flag[i] ^ key[i%4];
}
```
So if yo... |
I want to create a function that can return the number distinct values present in a given array. If for eg the array is
array[5] = { 1 3 4 1 3}, the return value should be 3(3 unique numbers in array).
I've so far only got this:
```
int NewFucntion(int values[], int numValues){
for (i=0; i<numValues; i++){
```
Im ... |
Add elements from thearrayto thestd::set<T>and since thesetis not allowing duplicate elements, you can then only get the number of elements from the set which gives you the number of distinct elements.
For example:
```
#include<set>
int NewFucntion(int values[], int numValues){
std::set<int> set;
for(int ... |
I am trying to check if a bit is clear in IA32_VMX_EPT_VPID_CAP (48CH) but in some cases I am working with hardware that dose not have that msr(q9300) itself and I get segfault. I was wondering if there was an instruction or a "nice" way to check if the msr exist in the first place. I know I could probably handle the ... |
From section A.10 of the Intel SDM:
The IA32_VMX_EPT_VPID_CAP MSR exists on processors that support EPT or VPID.
So you should check the following:
bit 63 of the IA32_VMX_PROCBASED_CTLS MSR is 1 (support for secondary controls)and either bit 33 or bit 37 of the IA32_VMX_PROCBASED_CTLS2 MSR is 1 (support for EPT or ... |
I'm confusing when creating a static library in C/C++ with same funtion names and param lists but implemented in different source files.
Say, I haveplay()funtion declared intest.h, andplay()implemented in bothtest.candtest_old.c. When creating a library that include bothtest.candtest_old.cin usually manner, there wil... |
Duplicating function names in your static library isverybad practice. Don't do this.
That said you can check for duplicate definitions by examining the output of thenmapplication.
```
$ nm libstest.a
test1.c.o:
0000000000000000 T bla
test2.c.o:
0000000000000000 T bla
```
The following command lists duplicate func... |
opendiris pretty much bound to be a memory-allocating function but thePOSIX spec for opendirdoes not mentionENOMEMin the list of possible errors.
What gives would-be-POSIX-compliant implementations the right to seterrno=ENOMEMin a callopendir?
|
SeeError NumbersinSystem Interfaces: General Information:
Implementations may support additional errors not included in this list, may generate errors included in this list under circumstances other than those described here, or may contain extensions or limitations that prevent some errors from occurring.
|
opendiris pretty much bound to be a memory-allocating function but thePOSIX spec for opendirdoes not mentionENOMEMin the list of possible errors.
What gives would-be-POSIX-compliant implementations the right to seterrno=ENOMEMin a callopendir?
|
SeeError NumbersinSystem Interfaces: General Information:
Implementations may support additional errors not included in this list, may generate errors included in this list under circumstances other than those described here, or may contain extensions or limitations that prevent some errors from occurring.
|
I am looking at aprojectwhich aims expose Cocoa API's to OCaml. The code comprises of a function which has two values where return type is mentioned.
```
CAMLprim value ml_NSWindow_center(value win_v)
{
CAMLparam1(win_v);
NSWindow *win = NSWindow_val(win_v);
[win center];
CAMLreturn(Val_unit);
}
```
Is that ... |
CAMLprimseems not to be a type at all, but a linkage/storage class for the function - it seems to be#defined to empty strings in some headers that I found. The real return type isvalue, which is atypedeffor an integer type.
|
This question already has answers here:C/C++: Pointer Arithmetic(7 answers)Closed4 years ago.
Here are we use typecasting from pointer to integer, but output of arithmetic operation are different from expected answer, Why?
Source Code :
```
int main(){
int *p,*q;
p = 1000;
q = 2000;
printf("%d",q-p)... |
The same reason due to which p++ will give you 1004. Sincesizeof(int)on your machine is 4, hence each operation is shown wrtsizeof(int), even the difference i.e. 1000/4.
|
I know we can print the path of the current working directory using something likegetcwd()but if the program was compiled in one place and the executable was copied to some other place, it will give the result as the new directory.
How do we store the value ofgetcwd()or something during compilation itself?
|
You could pass it as a compile-time define :
```
#include <stdio.h>
int main(void) {
printf("COMPILE_DIR=%s\n", COMPILE_DIR);
return 0;
}
```
And then :
```
/dir1$ gcc -DCOMPILE_DIR=\"$(pwd)\" current.c -o current
```
Resulting in :
```
/dir1$ ./current
COMPILE_DIR=/dir1
/dir1$ cd /dir2
/dir2$ cp /dir1/... |
I am looking at aprojectwhich aims expose Cocoa API's to OCaml. The code comprises of a function which has two values where return type is mentioned.
```
CAMLprim value ml_NSWindow_center(value win_v)
{
CAMLparam1(win_v);
NSWindow *win = NSWindow_val(win_v);
[win center];
CAMLreturn(Val_unit);
}
```
Is that ... |
CAMLprimseems not to be a type at all, but a linkage/storage class for the function - it seems to be#defined to empty strings in some headers that I found. The real return type isvalue, which is atypedeffor an integer type.
|
This question already has answers here:C/C++: Pointer Arithmetic(7 answers)Closed4 years ago.
Here are we use typecasting from pointer to integer, but output of arithmetic operation are different from expected answer, Why?
Source Code :
```
int main(){
int *p,*q;
p = 1000;
q = 2000;
printf("%d",q-p)... |
The same reason due to which p++ will give you 1004. Sincesizeof(int)on your machine is 4, hence each operation is shown wrtsizeof(int), even the difference i.e. 1000/4.
|
I know we can print the path of the current working directory using something likegetcwd()but if the program was compiled in one place and the executable was copied to some other place, it will give the result as the new directory.
How do we store the value ofgetcwd()or something during compilation itself?
|
You could pass it as a compile-time define :
```
#include <stdio.h>
int main(void) {
printf("COMPILE_DIR=%s\n", COMPILE_DIR);
return 0;
}
```
And then :
```
/dir1$ gcc -DCOMPILE_DIR=\"$(pwd)\" current.c -o current
```
Resulting in :
```
/dir1$ ./current
COMPILE_DIR=/dir1
/dir1$ cd /dir2
/dir2$ cp /dir1/... |
There are two programs and they get different results, but I don't understand why.
Here is the first:
```
int main()
{
printf("12345");
fflush(stdout);
printf("\b\b");
fflush(stdout);
return 0;
}
```
The result is:123.
Then the second:
```
int main()
{
printf("12345");
fflush(stdout);
... |
Depending on the Terminal,'\b'might "erase" a character or only move the cursor to the left. To have a foolproof solution, use:
```
#include <unistd.h>
#include <stdio.h>
int main(void)
{
printf("12345");
fflush(stdout);
sleep(1);
printf("\b\b \b\b");
fflush(stdout);
}
```
|
Its a part of code that i working on. When i try to assignDiagcb.endtoptr2it returned an error.
I tried to write it as:
```
ptr2 = &Diagcb.end;
ptr2 = &diagcb->end;
```
but the same error is returned.
```
typedef struct reportType {
int a;
int b;
int c;
int* ptr;
} reportType;
typedef struct cb {
... |
You should write it asptr2 = Diagcb.end. BecauseDiagcd.endis already a pointer, you don't need to use&to get the address.
|
__attribute__((unused))and__attribute((unused))can mark variables as unused to avoid unused warning.
What is the difference between them?
|
In the GCC repository, in the filec-common.c, the arrayc_common_reswordsof the typestruct c_common_reswordis defined.
In the array, you will find the following elements:
```
{ "__attribute", RID_ATTRIBUTE, 0 },
{ "__attribute__", RID_ATTRIBUTE, 0 },
```
AndRID_ATTRIBUTEis defined inc-common.hin theenum ridin t... |
I correctly got the alignment warning
cast increases required alignment of target type [-Wcast-align]
from the GCC compiler due to the following code:
```
uint8_t array[100];
uint32_t foo;
foo = * ( (uint32_t *) &array[10]);
```
Then I used thealignedattribute to figure out the issue:
```
uint8_t array[100] __at... |
__attribute__ ((aligned(4)))aligns only thebeginningof the array, not every single element of it.
If the beginning is aligned and the offset is10which is nor dividable by 4 the resulting address will not be aligned.
|
I was trying to make a function that removes the string terminator and adds a newline character instead to a string. The way i do it leads to a segfault. And i am unable to wrap my head around why my string is immutable and how to make it work with my implementation. Thanks a lot for any help.
```
int main () {
c... |
C strings are immutable, effectivelychar const[]that only look likechar []for strange historical reasons.
If you want a mutable string, initialize a char array from a string literal:
```
char value[] = "message"; //autosized
```
|
I have come across this code and I am not sure what#regis doing:
```
#define FPGA_WRITE(reg,val) do { printf("%-20s %08X <<- %08lX\n", #reg, (reg), (unsigned long)(val));} while (0)
int main()
{
FPGA_WRITE(10,15);
return 0;
}
```
This prints this following:
```
10 0000000A <<- 0000000F
```
... |
It isStringizing Operator (#)used inside#definepre-processor macros,which turns the argument it precedes into a quoted string
|
I'm new to C programming. I was trying to write a program that accepts an integer from user and displays its multiplication table up to 10 multiples.
This is my program:
```
#include <stdio.h>
int main ()
{
int number;
int count = 1;
int sum;
printf("Enter a number to display its ta... |
This is due to the spaces used in your scanf command.
If you replace that with
```
scanf("%i", &number);
```
you get an instant response.
|
I can release this using arrays, but i want to make it working with pointers.
```
char *ft_strcpy(char *dest, char *src)
{
while (*src)
{
*dest = *src;
dest++;
src++;
// return dest; i want
}
*dest = '\0';
return (dest);
}... |
You are losing your string as you incrementdest. At the enddestis pointing to a location which holds'\0'. You can use a temporary variable for modification whiledestis still pointing to the beginning of the allocated memory.
```
char *temp = dest;
while (*src)
{
*temp = *src;
temp++;
src++;
}
*temp = '\0'... |
I was trying to make a function that removes the string terminator and adds a newline character instead to a string. The way i do it leads to a segfault. And i am unable to wrap my head around why my string is immutable and how to make it work with my implementation. Thanks a lot for any help.
```
int main () {
c... |
C strings are immutable, effectivelychar const[]that only look likechar []for strange historical reasons.
If you want a mutable string, initialize a char array from a string literal:
```
char value[] = "message"; //autosized
```
|
I have come across this code and I am not sure what#regis doing:
```
#define FPGA_WRITE(reg,val) do { printf("%-20s %08X <<- %08lX\n", #reg, (reg), (unsigned long)(val));} while (0)
int main()
{
FPGA_WRITE(10,15);
return 0;
}
```
This prints this following:
```
10 0000000A <<- 0000000F
```
... |
It isStringizing Operator (#)used inside#definepre-processor macros,which turns the argument it precedes into a quoted string
|
I'm new to C programming. I was trying to write a program that accepts an integer from user and displays its multiplication table up to 10 multiples.
This is my program:
```
#include <stdio.h>
int main ()
{
int number;
int count = 1;
int sum;
printf("Enter a number to display its ta... |
This is due to the spaces used in your scanf command.
If you replace that with
```
scanf("%i", &number);
```
you get an instant response.
|
I have seenherethat is possible to get the length of all output to the console at a given time, however I am wanting to get the length of an individual line in the console (i.e. at a specificCOORD). Is this possible with Win32 API?
|
UseGetConsoleScreenBufferInfo()to get the width of the console screen buffer. Next do for every position fromwidthto0in the line you are interested inReadConsoleOutput()and check if the character at the position is a whitespace character (isspace()). If it is not you have found the position of the last character in th... |
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed4 years ago.Improve this question
This is the image wi... |
You may want to-Iinclude (an uppercase i like in include) your headers. Not-l(lowercase L).
|
I have a jni function
```
native float nativeMethod(int num);
```
That ties to a C function
```
void Java_com_package_name_nativeMethod(JNIEnv * env, jobject obj, jint num)
{
unsigned int nativeUnsignedNum = num;
}
```
And my C code requires the use of unsigned integers. How can I make this work? Using the cod... |
Cast it:
```
unsigned int nativeUnsignedNum = (unsigned int)num;
```
|
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed4 years ago.Improve this question
This is the image wi... |
You may want to-Iinclude (an uppercase i like in include) your headers. Not-l(lowercase L).
|
I have a jni function
```
native float nativeMethod(int num);
```
That ties to a C function
```
void Java_com_package_name_nativeMethod(JNIEnv * env, jobject obj, jint num)
{
unsigned int nativeUnsignedNum = num;
}
```
And my C code requires the use of unsigned integers. How can I make this work? Using the cod... |
Cast it:
```
unsigned int nativeUnsignedNum = (unsigned int)num;
```
|
```
int exp1 = ((1<<31)>>31)<<32 // output changes everytime
int exp2 = ((1<<31)>>31)<<31<<1 // 0
```
why is this happening?
it may be caused by overflow thing, but cannot understand properly.
I am trying to solve this problem for hours, need some help
(p.s integer for 32bits)
|
Shifting by the whole type size or more is undefined behavior, so anything can happen (it comes from the fact that many architectures shift instructions have bizarre behavior in these cases). Splitting the shift in two parts works around the issue.
|
In this code (keeping strict aliasing aside for a while):
```
#include<stdio.h>
int main(void)
{
int i=10;
void *ptr=&i;
printf("%lu\n",sizeof(ptr));
printf("%d\n",*(int *)ptr);
return 0;
}
```
It givessizeof(void*)as8, but when it has been dereferenced after typecasting it toint*it e... |
I think 8 bytes is to save the address of the "i" (int i =10;) in the memory, so it doesn't mean what kind of data you want to save, it just saves the address memory location and it required 8 bytes to suit any data type that need to cast
|
I have learned about typedef uses but I can't understand this following code,
```
typedef enum{FALSE, TRUE} Boolean;
```
What is the meaning of this code?
|
It means thatFALSEis aninttype with value 0 andTRUEis aninttype with value 1
ThenBooleancan be used as a type; you've introduced it into thetypedefnamespace. But note that otherintvalues other than 0 and 1 can be set to it. So it's not a trueBooleantype in the sense of the one in C++ or Java.
These days though don't... |
I have a function defined:
```
int32_t function(const bool inDebugPattern)
{
char tempBuff[256]; memset(tempBuff, 0, sizeof tempBuff);
/* use tempBuff[] */
}
```
which is called by multiple tasks, will the memory allocation oftempBuff[]be separate(unique) for each call of this function or will it be shared and ... |
Since tempBuff is a local variable it will be unique for each function call
Take a look atC Scope rules
|
For example i have a program thats "main" function is defined as wmain.
```
int wmain( int argc, wchar_t *argv[] ) {
wchar_t* lpModulePath = NULL;
wchar_t* lpFunctionName = NULL;
lpModulePath = argv[1];
lpFunctionName = argv[2];
}
```
and of course uses wchar_t types. How can i write a function
```
... |
On Windows you can useGetCommandLineW()andCommandLineToArgvW():
```
int main(int argc, char* argv[])
{
wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
int ret = wmain(argc, wargv);
LocalFree(wargv);
return ret;
}
```
On Linux I'm afraid you'd have to allocate the array and convert str... |
This question already has answers here:What's the point of malloc(0)?(18 answers)Closed4 years ago.
I am expecting NULL pointer exception but I am getting output 222. How is this working.
```
int main()
{
int *p = (int*)malloc(0);
*p = 222;
cout << *p;
return 0;
}
```
|
The behaviour of your program isundefined.
The behaviour ofmallocwith 0 passed isimplementation defined: itcanreturn 0ora pointer. If it returns a pointer, then you must pass that pointer tofree, but you mustnotdeference that pointer.
C and C++ do not differ in this respect.
|
I have learned about typedef uses but I can't understand this following code,
```
typedef enum{FALSE, TRUE} Boolean;
```
What is the meaning of this code?
|
It means thatFALSEis aninttype with value 0 andTRUEis aninttype with value 1
ThenBooleancan be used as a type; you've introduced it into thetypedefnamespace. But note that otherintvalues other than 0 and 1 can be set to it. So it's not a trueBooleantype in the sense of the one in C++ or Java.
These days though don't... |
I have a function defined:
```
int32_t function(const bool inDebugPattern)
{
char tempBuff[256]; memset(tempBuff, 0, sizeof tempBuff);
/* use tempBuff[] */
}
```
which is called by multiple tasks, will the memory allocation oftempBuff[]be separate(unique) for each call of this function or will it be shared and ... |
Since tempBuff is a local variable it will be unique for each function call
Take a look atC Scope rules
|
For example i have a program thats "main" function is defined as wmain.
```
int wmain( int argc, wchar_t *argv[] ) {
wchar_t* lpModulePath = NULL;
wchar_t* lpFunctionName = NULL;
lpModulePath = argv[1];
lpFunctionName = argv[2];
}
```
and of course uses wchar_t types. How can i write a function
```
... |
On Windows you can useGetCommandLineW()andCommandLineToArgvW():
```
int main(int argc, char* argv[])
{
wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
int ret = wmain(argc, wargv);
LocalFree(wargv);
return ret;
}
```
On Linux I'm afraid you'd have to allocate the array and convert str... |
This question already has answers here:What's the point of malloc(0)?(18 answers)Closed4 years ago.
I am expecting NULL pointer exception but I am getting output 222. How is this working.
```
int main()
{
int *p = (int*)malloc(0);
*p = 222;
cout << *p;
return 0;
}
```
|
The behaviour of your program isundefined.
The behaviour ofmallocwith 0 passed isimplementation defined: itcanreturn 0ora pointer. If it returns a pointer, then you must pass that pointer tofree, but you mustnotdeference that pointer.
C and C++ do not differ in this respect.
|
After assigning 26th element, when printed, still "Computer" is printed out in spite I assigned a character to 26th index. I expect something like this: "Computer K "
What is the reason?
```
#include <stdio.h>
int main()
{
char m1[40] = "Computer";
printf("%s\n", m1); /*prints out "Comp... |
At8thindex of that string the\0character is found and%sprints only till it finds a\0(the end of string, marked by\0) - at26ththe characterkis there but it will not be printed as\0is found before that.
|
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
I am reading the book "Advanced Programming in the UNIX Environment"
This library is important because all... |
No.
A "routine" is a series of instructions. Similar to a "function" or "program". The word "routine" is somewhat archaic (but "coroutine" is not).
Library routinesmeanslibrary functions. It has nothing to do with coroutines.
|
I have a working image encoder in C++ using ffmpeg as the backend. I am taking videos in and saving frames out as jpeg, but I am having difficulty adjusting the quality of the output jpegs.Things I have tried:SettingAVCodecContext'sglobal_qualityandcompression_levelfields.I have also tried settingqscalewith anAVDicti... |
The command line-qoption effects two things
```
enc_ctx->flags |= AV_CODEC_FLAG_QSCALE;
enc_ctx->global_quality = FF_QP2LAMBDA * qscale;
```
where enc_ctx is the AVCodecContext for the output stream and FF_QP2LAMBDA is 118
|
I use GoogleTest, and I want to test some functions with #ifndef inside.
file a.c
```
bool myFunction() {
#ifndef FOO
return true;
#else
return false;
#endif
}
```
Is it possible to force an #undef during a particular test ? Like that I can test the function in the 2 stats (with the define and without).
|
This is one of the reasons why people try to avoid having multiple versions of a function that you create with#define,#if, etc. It’s hard to test all these different versions.
If you want to test both versions, you must compile your program twice (one with#define FOOand once without), and then run the tests separatel... |
I was getting wrong values fromlog(), so I wrote this program just for testing:
```
#include <math.h>
#include <stdio.h>
void main()
{
printf ("%1f", log(10));
}
```
This should print "1", but I get "2.302585"
Why is this and how can I fix it?
|
Thelogfunction is for thenaturallogarithm with basee.
It seems you wantlog10instead.
|
I did a minimal c file (main.c)
```
#if !defined(MBEDTLS_CONFIG_FILE)
#error "not defined"
#else
#include MBEDTLS_CONFIG_FILE
#endif
int main(void)
{
while(1);
}
```
now callingarm-none-eabi-gcc main.cgiveserror: #error "no defined"and this is OK.
But callingarm-none-eabi-gcc main.c -DMBEDTLS_CONFIG_FI... |
It's theshellthat removes the quotes from the string you pass. You need to escape the quotes to keep them in the macro:
```
arm-none-eabi-gcc main.c -DMBEDTLS_CONFIG_FILE=\"test.h\"
```
|
I am using Visual Studio 2015 and ReSharper for my C programs but I can not make gets method work in this IDE. Why is this method not shown in autocomplete list?
|
From the Cdocumentation:.
The gets() function does not perform bounds checking, therefore this function is extremely vulnerable to buffer-overflow attacks. It cannot be used safely (unless the program runs in an environment which restricts what can appear on stdin). For this reason,the function has been deprecated in... |
I have a task to fulfil and part of it is to get certain file capabilities and check if they are set correctly using C/C++. I want to make sure that certain file has cap_new_raw+ep capability. What would be other way of achieving it than using system(get_cap file) and reading output (not returning value, output)?
|
So if I understand manual well, something like this should work:
```
capt_t file_cap;
cap_flag_value_t cap_flag_value;
file_cap = cap_get_file("/path/");
if(file_cap != 0) {
if(cap_get_flag(file_cap, CAP_NEW_RAW, CAP_EFFECTIVE, &cap_flag_value) == 0) {
if(cap_flag_value == CAP_SET)
// it works
... |
Why are there_BITmacros inlimits.hforCHAR_BIT,LONG_BIT,WORD_BIT? Why doesn't it define anINT_BIT?
Is there a reason why these macros are defined for other types, but not forint? Are these deprecated (out of use) withsizeof?
I see these are defined byPOSIX forlimits.h
|
It looks likeWORD_BITis what you want to beINT_BIT, from the document you link to:
{WORD_BIT}Number of bits in an object oftypeint.
Note thatCXmeans this is an extension to standard C.
TheC99 rationale documenttells us the committee saw little reason for anything besidesCHAR_BIT:
The macroCHAR_BITmakes available t... |
What would happen if an interrupt/thread preempts in middle of execution ofread(fd,buff,size)orwrite(fd,buff,size)functions and then it returns to where it was inread()/write()?
Can we assume it will continue reading or writing to the file descriptor without loss of data and order?
Assume there is no shared variable... |
readandwriteare system calls, so from the point of view of user-space, they are "atomic" -- there's no way for an interrupt or thread to preempt them "in the middle" of execution. Any signal will be delivered after the system call completes -- if it is an interrupting signal it may cause a "short" read or write (fewe... |
Here is code:
```
char number=4;
while(number<5) number=number-1;
printf("%d" , number);
```
result=127 , why ? can you explain me ? thanks
|
Your loop is set to iterate until number < 5. What happens is the value decrements to 5, 4, 3, 2, 1, 0, -1 ... -128. When it attempts to subtract one more value, you get a wrap around to the max value the char can hold (8 bits, 127, or 0x7F). At this point, the loop condition is no longer true, so your loop exits. The... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.