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 and the program return me 0 and 15 can somebody tell me why?
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 %hd instead of %d for short int printf("%hd%hd", n, x);// Notice %hd instead of %d for short int return 0; } ```
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 code. And if there was IO interrupt typed into my code, the kernel code executes. And so...which bit is the user mode code then?
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 will be kernel mode code. But most people most of the time are only writing user mode code.
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 trying to bind to an address that is not local at that time, the bind system call should return an error (EADDRNOTAVAIL). Finally, rebinding a connected TCP socket should result in an error because it doesn't make any sense.
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 and the program return me 0 and 15 can somebody tell me why?
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 %hd instead of %d for short int printf("%hd%hd", n, x);// Notice %hd instead of %d for short int return 0; } ```
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 code. And if there was IO interrupt typed into my code, the kernel code executes. And so...which bit is the user mode code then?
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 will be kernel mode code. But most people most of the time are only writing user mode code.
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 trying to bind to an address that is not local at that time, the bind system call should return an error (EADDRNOTAVAIL). Finally, rebinding a connected TCP socket should result in an error because it doesn't make any sense.
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 mystruct; ```
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; mystruct.series[1] = b; mystruct.series[2] = c; mystruct.series[3] = d; ``` Once you don't need it anymore, remember to free the memory to avoid a memory leak withfree(mystruct.series).
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 mathematical constant?
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! Even if there was a slight error, the very few people who need the constant could simply define it themselves.
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, too. Otherwise, includingunistd.hwould lead to an error, since the typemode_tis unknown there. In contrast,rmdir(2)doesn't take any arguments besides the filename, so it can remain inunistd.h, since there are no other dependencies.
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; } fgets(secret, 512, fps); printf("Secret: %s\n", secret); fclose(fps); return 0; } ``` When I am trying to run this program it is repeatedly throwing the following error: ``` ./attack1.c: line 4: syntax error near unexpected token `(' ./attack1.c: line 4: `int main ( int argc, char *argv[] )' ```
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 code?
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())) abort();)
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 eliminate the dead stores.
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 these output difference. echostate.c ``` #include <stdio.h> #include <termios.h> #include <stdlib.h> main() { struct termios info; int rv; rv = tcgetattr(0, &info); if (rv == -1) { perror("tcgetattr"); exit(1); } if (info.c_lflag & ECHO) printf("echo is on, since its bit is 1\n"); else printf("echo if OFF, since its bit is 0\n"); } ```
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: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types] queue->rear->next = node; ^
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_node *node, I don't know if you miss it while posting it here or in your code, just a reminder.
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(struct z z) { printf("%.3fi%.3f", z.re, z.im); } ```
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 account for it. When does not terminating the string create a problem?
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. If you pass anon-string to code that expects a string, you will invoke undefined behavior.
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 of 'unary *' (have 'int') How should I fix this?
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 of 'unary *' (have 'int') How should I fix this?
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 possible because withoutp_x,pp_xwould be pointless (No pun intended) because it wouldn't be pointing to anything.
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 currently using emacs. I don't know if there is any customisation that can do this ? Each time, I have to copy past the name in my terminal, run agrepand re copy past the file path in my emacs. (And you know, I am lazy...)
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 just need to navigate through code and more often than not ctags does the job.
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.txt", "r"); int num; while (fscanf(fp, "int%d", &num) == 1) printf("%d\n", num); fclose(fp); ```
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 this to me?
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). So the array A gets the input : "aaaaaaaaaaaaaaa" (15 times), and when I reach line 5 ,it jumps to line 6 and the array B gets the input: "aaaaaaaaaaaaaaa" (15 times). How can this be prevented? And allow the user to insert his input into array B ?
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 explain the reason behind error in last line of this C Code? I am trying to print address of a single dimension array element. Array a is defined as: ``` int a[5]={1,2,3,4,5}; printf("%p",a+1); //No Error printf("%p",&a); //No Error printf("%p",&(a+1)); //lvalue required as unary '&' operand Error ```
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 aaa = 0x5c0000a3; printf( "%08x %08x\n", (aaa >> 12), (aaa << 16) ); ```
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 all bits to the left 16 places and convert again.
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 correct it?
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 n){ return (n/2 + 9); } unsigned char return_f(char n){ return ((n=='f' || n=='F') ? n+1 : 'f'); } ``` Since I assumestaticshould limit globals and functions to their files, how does it allow to run/print out: ``` g f 14 ``` Or is that just not how it's supposed to work?
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=0;i<n;i++) { for(j=0;j<m;j++) { scanf("%d",ptr[i][j]); } } ```
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); // Call free only once ```
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 and heap are supposed to two different segments of memory I must get onlyaas the output as I have allocated memory in heap for only one char.
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 Undefined Behavior to do this. C doesn't have bounds checking, so it won't save you from this mistake.
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 correct it?
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 n){ return (n/2 + 9); } unsigned char return_f(char n){ return ((n=='f' || n=='F') ? n+1 : 'f'); } ``` Since I assumestaticshould limit globals and functions to their files, how does it allow to run/print out: ``` g f 14 ``` Or is that just not how it's supposed to work?
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=0;i<n;i++) { for(j=0;j<m;j++) { scanf("%d",ptr[i][j]); } } ```
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); // Call free only once ```
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 time looking for answers but can't find the issue. Any ideas? ``` #include <stdlib.h> #include <stdio.h> #include <string.h> #define BUFFER_SIZE 100 int main() { char request[BUFFER_SIZE]; while(strcmp(request, "quit") != 0 && strcmp(request, exit) != 0) { fgets(request, BUFFER_SIZE, stdin); } return 0; } ```
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 when I opened the file it is not there. How can I make this work?
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 this: ``` typedef int gid_t; ``` except if you really know what you are doing, andgid_tmight be a different type in your specific case.
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 know I'm "wasting" memory in word_1, since I'm asking more space (size = 20) than I need but what happens with word_0 (size = ?)?
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. And whatvx.ivalue is actually? Thank you.
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 stored in memory. Refer the excellent answer hereHow are floating point numbers are stored in memory? From the answer linked, Ifvx.fis1.0thenvx.iwill be3f800000(in hex)
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). Could someone explain how it works, because as far as I know the * sign is used to initialize or step into a pointer?
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> #include <sys/types.h> void * maFonction (void * val) { char * chaine = (char *) val; printf ("text received: %s\n", chaine); } int main(void) { pthread_t leThread; int ret = pthread_create (&leThread, NULL, maFonction, "First program with Pthreads"); if (ret != 0) { perror ("pthread_create"); exit(EXIT_FAILURE) ; } } ```
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(). Thissuggests initialization be performed in this order: ``` [first, set up threading callbacks if your program is multithreaded] SSL_load_error_strings (); SSL_library_init (); OpenSSL_add_all_algorithms (); OPENSSL_config (NULL); ``` You may also want to check out what it says in theOpenSSL Wiki on initialization
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++ unlike in ++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 value. Had you instead had the following code: ``` while(i < 10) { printf("%d\n",i++); } ``` Then 0wouldbe printed on the first iteration. In this case, the value ofiis incremented, but the postfix++operator means that the old value ofiis passed to theprintfcall.
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"){ strcpy(ds, "HONG KONG"); } else{ strcpy(ds, "INPUT ERROR"); } p("Destination: %s", ds); return 0; ```
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.Any bytes in the new object beyond the size of the old object have indeterminate values.
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 always execute the body. only a break (or exception) within the body would terminate it.
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 of new array - times copied { for(j = 0; j < size_X; j++) //size of old array { for(k = 0; k < inter_seq; k++) //times to be copied { b[i+k] = a[j]; } } } ``` thanks The order does matter. Thanks.
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() { char **test = NULL; init_test(&test); printf("1: %s, 2: %s", test[0], test[1]); printf("Hello World"); return 0; } ``` I have couple of different variations of this, but I am not sure how to correctly initialize a char** in a different function.
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 your data is "ZGUIHUOHJIOJOPIJMXAR" and your key is "akey", then the snippet basically does ``` ZGUIHUOHJIOJOPIJMXA ^ akeyakeyakeyakeyake ===================== yourplaintextresult (<- not really the result here, but you get the idea) ```
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 a new coder/New to C language and im stuck on how to proceed. Any guidance would be much appreciated. Thanks
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=0; i<numValues; i++){ set.insert(values[i]); } return set.size(); } ```
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 segfault or check the CPU model and compare it to a prepared table that have what CPU have the msr, but those solutions seems a bit messy to me. I looked over the Intel Manuel but I havn`t found any references to a way to check it. Is there a convention or a more proper way then the ways mentioned above ?
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 VPID)
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 will be no error. But this will make people confusing when using this library. How to detect this replicated implementation?Thanks.
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 functions in your library: ``` $ nm libstest.a | grep -P "^[^\\s]+ T " | cut -d' ' -f3 | sort | uniq -d ```
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 possible ? or that is not a return type.
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); return 0; } ``` Output:250
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/current ./ /dir2$ ./current COMPILE_DIR=/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 possible ? or that is not a return type.
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); return 0; } ``` Output:250
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/current ./ /dir2$ ./current COMPILE_DIR=/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); sleep(1); printf("\b\b"); fflush(stdout); return 0; } ``` but the result is:12345. Why does the sleep call make the second result different when I expect a "123" result? The code was running in the CLion. and My OS is macOS, if it matters.
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 { reportType* start; reportType* end; reportType arr[10]; }cb; int fun (reportType* report); main() { cb Diagcb; reportType report; report.a = 0; report.b = 1; report.c = 2; report.ptr = NULL; reportType* ptr2; ptr2 = cb.end; } ```
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 the/* C extensions */section. So__attributeand__attribute__are the same.
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] __attribute__ ((aligned(4))); uint32_t foo; foo = * ( (uint32_t *) &array[10]); ``` Despite this trick I however got the same warning. Is that normal or the warning should disappear?
__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 () { char* value = "message"; value[7] = '\n'; int success = write(1, value, 7); if (success == -1) { printf("write failed"); } } ```
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 ``` If I take out the#, I get a segfault when I execute the code. Strange. What is the usage of#?
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 table: "); scanf(" %i ", &number); while (count <=10) { sum = number * count; printf("%i x %i = %i\n", number, count, sum); count += 1; } return 0; } ``` Compilation successfully completes, but when I execute the output file, nothing happens, the terminal is stuck at nothing, i've to press ctrl+c to get out..
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'; return (dest); ```
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 () { char* value = "message"; value[7] = '\n'; int success = write(1, value, 7); if (success == -1) { printf("write failed"); } } ```
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 ``` If I take out the#, I get a segfault when I execute the code. Strange. What is the usage of#?
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 table: "); scanf(" %i ", &number); while (count <=10) { sum = number * count; printf("%i x %i = %i\n", number, count, sum); count += 1; } return 0; } ``` Compilation successfully completes, but when I execute the output file, nothing happens, the terminal is stuck at nothing, i've to press ctrl+c to get out..
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 the line and itsX-coordinate is the lenght of the line.
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 with the code, directories and the terminal error-output: I already tried to specify the include path from the root but that failed too. Am I just overlooking something for hours and being dumb or what is it?
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 code above I get an error:Using 'unsigned int' for signed values of type 'jint'. How can I pass a number ( it will always unsigned/positive ) from Java to a C method, and assign this value to an unsigned integer? Thanks!
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 with the code, directories and the terminal error-output: I already tried to specify the include path from the root but that failed too. Am I just overlooking something for hours and being dumb or what is it?
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 code above I get an error:Using 'unsigned int' for signed values of type 'jint'. How can I pass a number ( it will always unsigned/positive ) from Java to a C method, and assign this value to an unsigned integer? Thanks!
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 exactly prints the number assigned to variablei. How does compiler push/limit pointer of size 8 bytes to point to next 4 bytes (sizeof(int)on my system)?
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 do that. Use<stdbool.h>instead.
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 can be corrupted by a concurrent call from other tasks?
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 ``` int main( int argc, char *argv[] ) ``` that converts the parameters passed as char to wchar_t and then calls wmain by itself? Thank you
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 strings in loop.
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 do that. Use<stdbool.h>instead.
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 can be corrupted by a concurrent call from other tasks?
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 ``` int main( int argc, char *argv[] ) ``` that converts the parameters passed as char to wchar_t and then calls wmain by itself? Thank you
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 strings in loop.
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 "Computer"*/ m1[26] = 'K'; printf("%s\n", m1); /*prints out "Computer"*/ printf("%c", m1[26]); /*prints "K"*/ } ```
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 contemporary UNIX systems, such as the ones described in this book, provide thelibrary routinesthat are specified in the C standard. I am very confused here about the word routineCoroutine - Wikipedia Does it has any relations to coroutines?
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 anAVDictionaryof options, but have been unsuccessful there too. I know its possible because with the command line I canffmpeg -i INPUT -q:v 2 output_frame_%02d.jpgand get higher quality images.
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 separately. The only way to change the value ofFOO, as written, is to recompile the program. Alternatively, you can refactor your code so the#defineis unnecessary.
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_FILE="test.h"giveserror: #include expects "FILENAME" or <FILENAME>so it is defined but not to the value I expect. What is the correct syntax ? (context: this is working from the IDE but I want to move to cmake)
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 the third corrigendum to the C99 standard and removed altogether in the C11 standard. fgets() and gets_s() are the recommended replacements.Never use gets().
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 } else // handle error if(cap_get_flag(file_cap, CAP_NEW_RAW, CAP_PERMITTED, &cap_flag_value) == 0) { if(cap_flag_value == CAP_SET) // it works } else // handle error } else // handle error ```
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 the number of bits in a char object. The C89Committee saw little utility in adding such macros for other data types. likely becauseCHAR_BIT*sizeof(type)does what you need.
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 variables to worry about synchronization.
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 (fewer bytes read or written than expected) or anEINTRerror value, in which case the user-level program (when it resumes after the interrupt and system call) will need to deal with that.
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. Therefore, your final value after the wrap around is 127.