question
stringlengths
25
894
answer
stringlengths
4
863
This is something I did as part of simple experimentation; ``` #include <stdio.h> #include <stdlib.h> #include <unistd.h> int fun() { int d=10; write(1,(int*)d,sizeof(d)); } int main() { int x; fun(); read(1,(int*)x,4); printf("x=%d\n",x); return 0; } ``` As you can see I am trying to access value ofdinfun()function via the IO stream (IO files)stdout; I tried usingstdinas well but the thing isxvalue is not changing. (I tried in an online IDE.) But as per my thought stream, it should change to value ofd. Can anyone help me see why it is not doing that?
read and write requirepointers. In your case it is&dand&x. Castinginttoint*usually makes no sense.
Hello currently I don't know why I can't check the pointer whether it is NULL or not. I am trying to check whether task->signal->tty->name has a name or NULL but it actually identifies itself as a NULL even if it has a name. I have used the simple iterating function suggestions? regarding to this issue?
You should try it like this: ``` for_each_process(task) { char *tty_name = NULL; if (task && task->signal && task->signal->tty) tty_name = task->signal->tty->name; if (tty_name == NULL) { // Handle NULL pointer } else { // Handle valid pointers } } ```
I need to build a string in python and pass it to the wrapped C lib. The C lib defines the function: ``` unsigned char load(char const *FileName) ``` In the .pyx file: ``` def test(): PATH = '/usr/lib/libnx.so' PATH = <char*>PATH load(PATH) ``` But I get:TypeError: expected bytes, str found I have tried encoding the python string but get the same error.
In Python,strobjects are not byte arrays as in C. To get that, you must encode the string. The default is UTF-8 encoding, which is backwards compatible with ASCII. Here are two ways to pass the array of bytes: Option 1: DefinePATHto be abytesobject from the get-go:PATH = b'/usr/lib/libnx.so', or:PATH = 'usr/lib/libnx.so'.encode()Option 2: EncodePATHinto a byte array when you pass it:load(PATH.encode())
``` int main(int argc, char *argv[]) { FILE *fp; printf("%s\n", argv[0]); printf("%s\n", argv[1]); printf("%s\n", argv[2]); fp = fopen(argv[1], "r"); if((fp == NULL) || strcmp(argv[0], "MySearch") != 0) { fprintf(stdout, "File is NULL "); fflush( stdout ); exit(0); } ``` in the command line I put ``` gcc Lab2.c -o MySearch ``` and then ``` ./MySearch arr_file.txt 6 ``` the function prints ``` ./MySearch arr_file.txt 6 File is NULL ``` There is a file called arr_file.txt, but why it failed to open it? Can someone help? Thanks in advance.
argv[0]is"./MySearch"which is different from"MySearch"sostrcmp()returns non-zeroso theifcondition is satisfied irrespective of the value offp.
I can't seem to find the answer on here, but I'm sorry if this is a duplicate. Here's my question: When I have two pointers to the same location, then I change the address of one (let's say pointer A), will I (by accident) be changing the address of the other pointer (pointer B)? Or will pointer B's location stay the same?
Changing the contents of a pointer (as opposed to the object being pointed to) will not affect other pointers to the same object.
Is it possible use anintvector instead of usingdoublevectors for fft calculation?
No, not using FFTW (which you tagged in the question). There are other libraries, but to be useful in practice you will need to give some thought to the fixed point representation of your choice. Note that floating point additions and multiplications, what's used in an FFT, is just as fast on modern x64 chips as integer operations of corresponding word size. The extra care needed to create an integer FFT result with reasonable precision would maybe even cause a slowdown in practice. The story is very different on chips with slower (or none) floating point hardware. Of course, conversion from integer to floating point itself is not free in the first place, so sometimes it makes sense to stay in floating point for a longer time than what is critically needed.
I have a question regarding the for loop in the release list func. (The head is a dummy so we don't need to release it). I don't understand the: ``` next = next? ``` part in the loop. What does it actually do, and why simply ``` next? ``` won't suffice? here is the code: ``` typedef struct NODE { int num; struct NODE* next; } Node; void release_list(Node* head) { Node* next = head->next ? head->next->next : NULL; for( Node* curr = head->next; curr != NULL; curr = next, next = next? next->next : NULL) { free(curr); } } ```
Ternary operator?:has higher precedence than assignment=. Code is equivalent to: ``` next = (next? next->next : NULL) ``` Or: ``` if(next != NULL) next = next->next; else next = NULL; ``` Point of the code is to avoid accidentally doingNULL->nexton last element.
This is something I did as part of simple experimentation; ``` #include <stdio.h> #include <stdlib.h> #include <unistd.h> int fun() { int d=10; write(1,(int*)d,sizeof(d)); } int main() { int x; fun(); read(1,(int*)x,4); printf("x=%d\n",x); return 0; } ``` As you can see I am trying to access value ofdinfun()function via the IO stream (IO files)stdout; I tried usingstdinas well but the thing isxvalue is not changing. (I tried in an online IDE.) But as per my thought stream, it should change to value ofd. Can anyone help me see why it is not doing that?
read and write requirepointers. In your case it is&dand&x. Castinginttoint*usually makes no sense.
Hello currently I don't know why I can't check the pointer whether it is NULL or not. I am trying to check whether task->signal->tty->name has a name or NULL but it actually identifies itself as a NULL even if it has a name. I have used the simple iterating function suggestions? regarding to this issue?
You should try it like this: ``` for_each_process(task) { char *tty_name = NULL; if (task && task->signal && task->signal->tty) tty_name = task->signal->tty->name; if (tty_name == NULL) { // Handle NULL pointer } else { // Handle valid pointers } } ```
I need to build a string in python and pass it to the wrapped C lib. The C lib defines the function: ``` unsigned char load(char const *FileName) ``` In the .pyx file: ``` def test(): PATH = '/usr/lib/libnx.so' PATH = <char*>PATH load(PATH) ``` But I get:TypeError: expected bytes, str found I have tried encoding the python string but get the same error.
In Python,strobjects are not byte arrays as in C. To get that, you must encode the string. The default is UTF-8 encoding, which is backwards compatible with ASCII. Here are two ways to pass the array of bytes: Option 1: DefinePATHto be abytesobject from the get-go:PATH = b'/usr/lib/libnx.so', or:PATH = 'usr/lib/libnx.so'.encode()Option 2: EncodePATHinto a byte array when you pass it:load(PATH.encode())
``` int main(int argc, char *argv[]) { FILE *fp; printf("%s\n", argv[0]); printf("%s\n", argv[1]); printf("%s\n", argv[2]); fp = fopen(argv[1], "r"); if((fp == NULL) || strcmp(argv[0], "MySearch") != 0) { fprintf(stdout, "File is NULL "); fflush( stdout ); exit(0); } ``` in the command line I put ``` gcc Lab2.c -o MySearch ``` and then ``` ./MySearch arr_file.txt 6 ``` the function prints ``` ./MySearch arr_file.txt 6 File is NULL ``` There is a file called arr_file.txt, but why it failed to open it? Can someone help? Thanks in advance.
argv[0]is"./MySearch"which is different from"MySearch"sostrcmp()returns non-zeroso theifcondition is satisfied irrespective of the value offp.
I can't seem to find the answer on here, but I'm sorry if this is a duplicate. Here's my question: When I have two pointers to the same location, then I change the address of one (let's say pointer A), will I (by accident) be changing the address of the other pointer (pointer B)? Or will pointer B's location stay the same?
Changing the contents of a pointer (as opposed to the object being pointed to) will not affect other pointers to the same object.
I have this struct: ``` typedef struct person_st{ char *first_name, *last_name; int id; Date birthday; }*pPerson, Person; ``` lets say i reallocatesizeof(Person)*(++n)few times. inside each struct i also allocate space for thefirst_nameandlast_name. assuming that at some point there will be allocation failure while i userealloc, what is the safest/smartest way to handle all thefirst_nameandlast_nameallocations? its there still a way to free them after the realloctaion failure of thePersonstruct? thanks.
the best way to call realloc is something like this: ``` more_people = realloc(people, count * sizeof(Person)); if (!more_people) { // handle failure } else { people = more_people; } ``` This way you check the return code from realloc and safely handle the failure
I'm attempting to print the height y as a function of time t. EDIT: Alright I got the code to work now, thanks to all of you! I appreciate your help! ``` #include <stdio.h> int main() { double t, g = -9.8, v = 20; double y; for(t = 0; t < 4.079; t = t + .02){ y = (( v * t) + ( .5 * g * t * t )); printf("value of y: %f\n", y); } return 0; } ```
On this line: ``` printf("value of y: %d\n", y); ``` %dis for printingintegers(int). You are trying to print adouble. Use%fto print adouble. You will have to re-calculate the value of y every time in your loop: ``` for(t = 0; t < 4.079; t = t + .02) { y = ((v * t) + (.5 * g * ( t * t)); printf("value of y: %d\n", y); } ```
This question already has answers here:What is the difference between an identifier and variable?(15 answers)Closed6 years ago. Identifiers are names that are given to various program elements, such as variables, functions and arrays. We can write a function, for example: ``` int function (int x); ``` Here, the parameter of the function isint x. My question is: can we call the parameter an identifier?
xidentifies a parameter of your function, which can be used as a variable (identifier) in calculations. So yes,xis an identifier.
I am trying to compile some C functions, usinggccnot to run over any registers. I am working onx86_64. I am trying to useno_caller_saved_registers, but all I get is this: warning: ‘no_caller_saved_registers’ attribute directive ignored [-Wattributes]void foo()attribute((no_caller_saved_registers)); My temporary solution was to write inline assembly prologue and epilogue to save and restore all registers, but I REALLY prefer to make the attribute work. Did anyone have this problem?
No_caller_saved_registers has only been implementedin June 2016so it's not available in any official GCC release atm.
I have this struct: ``` typedef struct person_st{ char *first_name, *last_name; int id; Date birthday; }*pPerson, Person; ``` lets say i reallocatesizeof(Person)*(++n)few times. inside each struct i also allocate space for thefirst_nameandlast_name. assuming that at some point there will be allocation failure while i userealloc, what is the safest/smartest way to handle all thefirst_nameandlast_nameallocations? its there still a way to free them after the realloctaion failure of thePersonstruct? thanks.
the best way to call realloc is something like this: ``` more_people = realloc(people, count * sizeof(Person)); if (!more_people) { // handle failure } else { people = more_people; } ``` This way you check the return code from realloc and safely handle the failure
I'm attempting to print the height y as a function of time t. EDIT: Alright I got the code to work now, thanks to all of you! I appreciate your help! ``` #include <stdio.h> int main() { double t, g = -9.8, v = 20; double y; for(t = 0; t < 4.079; t = t + .02){ y = (( v * t) + ( .5 * g * t * t )); printf("value of y: %f\n", y); } return 0; } ```
On this line: ``` printf("value of y: %d\n", y); ``` %dis for printingintegers(int). You are trying to print adouble. Use%fto print adouble. You will have to re-calculate the value of y every time in your loop: ``` for(t = 0; t < 4.079; t = t + .02) { y = ((v * t) + (.5 * g * ( t * t)); printf("value of y: %d\n", y); } ```
``` int main () { int a, b; call(&b); printf("%d, %d",a , b); } void call(int *ptr) { } ``` Desired output: ``` 50, 100 ``` How to write the call function so as to modify both the variables to get the desired output??
Not sure where the values50and100are coming from or exactly what you are asking but maybe this will help with your question. Since C is pass by value you need to send pointers to actually change the value inside another function. Since thecallfunction will have pointer values you need to dereference the pointers before changing the value. Here is an example: ``` void call(int *a, int *b) { *a = 50; *b = 100; } int main() { int a, b; call(&a, &b); printf("%d, %d\n", a, b); } ```
``` void s1(char dest[], char src[]) { int i=0; while(dest[i++]=src[i++]); } void s2(char * dest, char *src) { while(*dest++=*src++); } ``` Also, note that I took this problem from a book, and don't know if the code is correct or not(I think there should be two '=' in the while loop)
The second code performs a string copy. It is equivalent tostrcpy(). The first code has undefined behaviour because it updatesitwice in one statement without an intervening sequence point. So the answer is that they are not the same. The first code could be corrected. For example like this: ``` void s1(char dest[], char src[]) { int i=0; while(dest[i]=src[i]) i++; } ```
Whether you use winsock or posix the function you use to create network socket requires you to specify address family, protocol and 'type' of the socket. Yet it seems this parameter has very little significance to the programmer and it can also be determined by looking at the other two parameters. So what's the deal here? Is there some historical reason? Like did vikings use this parameter to lure the english out of their castles?
Forudpliteprotocol, for example, the socket is created like this: ``` sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDPLITE); ``` SCTPsockets: ``` sctp_socket = socket(PF_INET, SOCK_STREAM, IPPROTO_SCTP); sctp_socket = socket(PF_INET, SOCK_SEQPACKET, IPPROTO_SCTP); ``` In other words, the third argument tosocketcalls is not always derived from the first two.
``` typedef struct node { int value; struct node *next; } NodeT; const NodeT *a,b,c; ``` Is variable b actually a constant struct element?
Is variable b actually a constant struct element? Yourbhas typeconst NoteT, which meansconst struct node, as the declaration : ``` const NoteT *a,b,c; ``` is equivalent to : ``` const NoteT *a; const NoteT b; const NoteT c; ``` In general, if you have a declaration like : ``` type *x, y, z, *w, ... ; ``` the typetypeapplies to all variable, but only those who have a*in front of them are pointers to that type.
I have barcode scanner, attached to Linux computer via USB. The scanner emulates a keyboard device. I have to write a program that to read the scanned barcodes and process them. The program runs on background as a service and should read the barcode scanner regardless of the current X focus. How this can be made in Linux? Some lower level solution/explanation is preferred.
It sounds like you want to capture the data from a specified device, In which case the method described in this post should help: (EDIT: original link dead, Archive link provided) https://web.archive.org/web/20190101053530/http://www.thelinuxdaily.com/2010/05/grab-raw-keyboard-input-from-event-device-node-devinputevent/ That will listen out for keyboard events stemming from only the specified source. A word of caution though, as far as I know, that won't stop it from propagating to whatever your current window focus is.
This question already has answers here:Short circuit evaluation and side effects [duplicate](3 answers)Closed6 years ago. This is the exemplar code that I encountered in entry level Computer Programming course: ``` #include <stdio.h> int main() { int l = 20, m = 10; int z; z= l++ || m++; printf("z = %d l = %d m = %d\n", z, l, m); } ``` The code prints l=21, m=10 and z=1 values of l and z are what was expected by me, but value of m is troubling me. Shouldn't it be 11 as m++ is present in code.
It is becausem++would only be executed ifl++ == 0. Sincel++evaluates to20thenm++is never executed. Iflwas0initially thenm++would be executed.
We can create many wrapper scripts to call specific binary files and use alias to point to different string. My requirement is we need to call the alias string in exec system call. If we run that string directly in exec call, the system call fails Ex: ``` af45sp01> alias | grep bulk bulkactivation=wrap_alias=''\''bulkactivation 1'\'' /iscp/node/bin/isnm_wrapper /iscp/space/scr/issp_bulk_activation' char *pgm_name = "bulkactivation"; execl((char*)(const char*)path_name, (char*)(const char*)pgm_name,0); ``` The above execl system call fails. I think it is unable to find alias string in the PATH and that is expected. How to get away from this problem??
The usage of ksh/bash with command as options worked like a charm. Thanks
here is a little function on a old book: ``` unsigned long f() { __asm__("movl %eax,%esp"); } ``` the function explained to get the stack point,but it seems not.It actually gets a 8-bit address much lower than my frame address.I guess it's designed for 32-bit system? Please forgive me if I said something stupid.
Indeed, as @James mentioned in the comments, in 64 bit mode,%eaxand%esprepresent the least significant 32 bits of the 64 bit%raxand%rspregisters.
Input: ``` char arr1[9] = "+100-200" // (+ is 2B, - is 2D, 1 is 31 and 2 is 32) ``` Output: ``` unsigned int arr2[4]= [0x2B31,0x3030,0x2D32,0x3030] ``` How can I do this?
Your question seems inconsistent:0should convert to0x30, its ASCII value. Why this modification, the code is quite straightforward: ``` char arr1[8] = "+100-200"; unsigned int arr2[4]; for (int i = 0; i < 8; i += 2) { arr2[i / 2] = ((unsigned int)(unsigned char)arr1[i] << 8) | (unsigned int)(unsigned char)arr1[i + 1]; } for (int i = 0; i < 4; i++) { printf("0x%04X ", arr2[i]); } printf("\n"); ``` Output: ``` 0x2B31 0x3030 0x2D32 0x3030 ```
Coming from a C++ background here. I'm required to write C for my one of my courses, which I've never been exposed to. What's' the difference beteween these two declarations? Why include the struct keyword? Are there different meanings? Do they have different meanings in C++ vs C? ``` struct A { int dataA; A* nextA; }; struct B { int dataB; struct B* nextB; }; ``` The comments below say that the first is invalid in C. However, I'm compiling just fine with gcc. Edit: I was compiling a .cpp file with gcc. I'm such a noob lol. Solution: The the second is required for C where the first is only valid in C++.
``` struct B { int dataB; B* nextB; }; ``` is the same as ``` struct B { int dataB; struct B* nextB; }; ``` in C++ but not in C. When using C, you'll have to use the second form. The first form is not legal C.
``` for(i=0;i<5;i++) for(i=0;i<5;i++) fork(); ``` How many child processes are created in the above code ? My attempt : I first solved the inner loop, and got total 32 processes in which 31 are child processes and 1 parent process. Then, I went for outer loop which loops 5 times, thus producing 31 * 5 = 155 child processes. Have I got this right ?
``` for(int i=0; i<n; i++) fork(); ``` For such kind of situation the total no of processes created is always2^n - 1asfork()will get called byntime. ``` for(int i=0; i<n; i++) for(int j=0; j<n; j++) fork(); ``` For this doublefor-loop,fork()gets called byn^2times, Hence total no of processes created will be, ``` 2^(n^2) - 1 ``` What is important for such questions is to calculate the no of times yourfork()gets called. For you casen=5so total no of child processes will be2^25 - 1.
I have recently started to learn ANSI C. I have come across this: ``` int a[7]; *(a+2); ``` I don't understand how it's possible to add 2 toa. Does it add 2 to every element ina? Also, what is the function of the*? Does it create a pointer?
a+2causesato be interpreted as a pointer toa's first element. This is calledarray decaying. It then offsets that pointer by2anddereferences(*) the resulting pointer. So it's the same asa[2].
I would love if you guys could explain to me why the following piece of recursive code doesn't print the word 'test'. Thanks in advance. ``` void drawTetriminosEachPosition(int **tetriminos, char **dBoard, int **tBoard, int i){ char c; char **dBoard2; if(tetriminos[i] == '\0') { return; } else { dBoard2 = dBoard; DrawTetrimino(tBoard, tetriminos[i], dBoard, i+65); } i++; return (drawTetriminosEachPosition(tetriminos,dBoard,tBoard,i)); ft_putstr("test"); if(checkChar(tBoard,tetriminos[i])) { dBoard = dBoard2; return (drawTetriminosEachPosition(tetriminos,dBoard,tBoard,i)); } } ```
Statements after a return are never executed. Since the first ``` return (drawTetriminosEachPosition(tetriminos,dBoard,tBoard,i)); ``` does not depend on any condition, the following code is not executed.
I need to get the last character from a string. Say the string looks like this: ``` blue;5 ``` I was thinking I could use strlen and then just subtract by 1 to get the 5. I have tried a bunch of different ways but none of them work. That's the way I have the way I think it should look or do, but I know that its not working. Any suggestions? This is sort of my code-pseudocode. I know it doesn't work for a variety of reasons but its sort of the flow I had in mind. ``` len = strlen(Input); Position = Input[len - 1]; strcpy(value, Input[Position]); ```
``` len = strlen(Input); //ok ``` Here you are going wrong . Putting a character into integer is incorrect. You need this. ``` Position = Input[len - 1]; //incorrect ``` Do it as ``` Position = strlen(Input) - 1 //correct strcpy(value, &Input[Position]);//ok ```
Input: ``` char arr1[9] = "+100-200" // (+ is 2B, - is 2D, 1 is 31 and 2 is 32) ``` Output: ``` unsigned int arr2[4]= [0x2B31,0x3030,0x2D32,0x3030] ``` How can I do this?
Your question seems inconsistent:0should convert to0x30, its ASCII value. Why this modification, the code is quite straightforward: ``` char arr1[8] = "+100-200"; unsigned int arr2[4]; for (int i = 0; i < 8; i += 2) { arr2[i / 2] = ((unsigned int)(unsigned char)arr1[i] << 8) | (unsigned int)(unsigned char)arr1[i + 1]; } for (int i = 0; i < 4; i++) { printf("0x%04X ", arr2[i]); } printf("\n"); ``` Output: ``` 0x2B31 0x3030 0x2D32 0x3030 ```
This question already has answers here:Printf variable number of decimals in float(3 answers)Closed6 years ago. A simple question.I want to print a floating point number with precision given input from the user, i.e. fornum=2.34567andprec=2, I should print2.35as the answer, and forprec=3, I should print2.346. How can we achieve this? (prec is given input from the user during runtime).Thanks in advance.
This is probably what you are looking for: ``` float num = 2.34567; int prec = 3; printf("%.*f", prec, num); ```
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed6 years ago.Improve this question i am curious to know is it possible to write program in c language to search something in google and show the first search result as output accessing network? Is yes please tell me how with some codes.
Some helpful references (don't ask for complete code here, do it yourself! if you run into errors, ask about them here): Google's opinion on automated queriesC program example to fetch an html resourceA possible way to do what you wanted(combine this answer with reference #2) Good luck!
I try to compile the following code, but I constantly get this error. ``` char command[100]; FILE *fp; command = sprintf(command, "sudo asterisk -rx \"pjsip show aor %s\"", row[i]); fp = popen (command, "r"); if (fp == NULL) { printf("Failed to run command\n" ); exit(1); ``` This error appears: "error: assignment to expression with array type"
You are assigning the value ofsprintf()to a variable which has array type. Arrays are not modifiable lvalues; so you can't assign to them.sprintf()returns anint-- so you need to assign its value to anint. However, I'd suggest to avoidsprintf()and usesnprintf()instead. Becausesprintf()is prone to buffer overflow. ``` int rc = snprintf(command, sizeof command, "sudo asterisk -rx \"pjsip show aor %s\"", row[i]); ```
the code below is giving segmentation code dump. Unable to get the output. ``` #include <stdio.h> int main() { char word[]="CS311CS312CS313"; printf("%s" , *word); return 0; } ```
Use this ``` printf("%s" , word); ``` instead of ``` printf("%s" , *word); ``` Because the*wordwill be the value atword[0]which is a character. Theprintfhowever is looking for an array of chars, thus causing it to segfault. strings are just arrays of characters terminating with'\0'.
I'd like pass a command to another cmd window when starting it with the start command. For example, I'd like to be able to type something likestart cmd dirwhere the dir command is run in the new window. Unfortunately the way I wrote it, it doesn't work. I'd like to run this task in a c/c++ program; however, that command can be run easily by typing the command into thesystem("start cmd dir");function
``` start "windowtitle" cmd /c dir start "windowtitle" cmd /k dir ``` /cRun the command and exit/kRun the command and continue reading commands interactively For more complicated commands, use doublequotes, for example: ``` start "windowtitle" cmd /c "dir && pause" ``` This can be also written as ``` start "windowtitle" cmd /c dir ^&^& pause ``` because^literalizes the next character, and prevents the originalcmdseeing&&as a command separator.
Code ``` #include<stdio.h> main() { int big, x = 3, y = 2, z = 1, q = 4; big = (x > y ? (z > x ? 20 : 10 && x > y ? 85 : 12) : (y > z ? 40 : 10 || x < q ? 30 : 10) ); printf("\nbig =%d", big); //getch(); } ``` Ouput is 85 But Iam not sure how it's working Help me to understand it..
&&has higher precedence than?:. ``` big=(x>y?(z>x?20:10 && x>y?85:12): (y>z?40:10 || x<q?30:10));` ``` will be parsed as ``` big=(x>y?(z>x ? 20: ( (10 && x>y) ?85:12) ): (y>z ? 40: (10 || x<q?30:10))); ``` Sincexis greater thany, so20: (10 && x>y?85:12)will be executed. Both10andx > ywill be evaluated totrue,(10 && x>y) ?85:12)will give85.
I have the following code: ``` #define MAX_VIDEOS 100 typedef struct video_t { int likes; int dislikes; char* title; user_t* uploader; } video_t; typedef struct user_t { char* username; char* password; video_t videos[MAX_VIDEOS]; } user_t; ``` I want to useuser_tinvideo_tand vice versa. In every case,gccjust says"unknown type name": youtube.c:9:5: error: unknown type name ‘user_t’user_t* uploader; ^ which is normal, but I can't think of a way to solve this problem.
You need toforward-declareuser_t: ``` #define MAX_VIDEOS 100 typedef struct user_t user_t; typedef struct video_t { int likes; int dislikes; char* title; user_t* uploader; } video_t; typedef struct user_t { char* username; char* password; video_t videos[MAX_VIDEOS]; } user_t; ```
I have two structs: ``` struct Parent { struct *Child child; // Pointer to a child } struct Child { int id; } ``` I wish to init an array of 'Parent' ``` int size = 2; struct Parent *parents = (struct Parent*) malloc(sizeof(struct Parent) * size); ``` this breaks when runs. Any solution for this? I want to initialize in such way: ``` struct Parent { struct *Child child = nullptr; // Points to null upon initialization. } ```
Don't mix C and C++; compile your C code using a C compiler, your C++ code using a (compatible) C++ compiler then link it using the linker, as you would with any other language. Don't usemallocin C++; usenewinstead. Don't castmalloc(or othervoid *values) in C. Don't useintfor size values in C; usesize_t, instead. Don't usenullptrin C; it doesn't exist. UseNULLinstead.
Code ``` #include<stdio.h> main() { int big, x = 3, y = 2, z = 1, q = 4; big = (x > y ? (z > x ? 20 : 10 && x > y ? 85 : 12) : (y > z ? 40 : 10 || x < q ? 30 : 10) ); printf("\nbig =%d", big); //getch(); } ``` Ouput is 85 But Iam not sure how it's working Help me to understand it..
&&has higher precedence than?:. ``` big=(x>y?(z>x?20:10 && x>y?85:12): (y>z?40:10 || x<q?30:10));` ``` will be parsed as ``` big=(x>y?(z>x ? 20: ( (10 && x>y) ?85:12) ): (y>z ? 40: (10 || x<q?30:10))); ``` Sincexis greater thany, so20: (10 && x>y?85:12)will be executed. Both10andx > ywill be evaluated totrue,(10 && x>y) ?85:12)will give85.
So I just have a simple question. How can I use a variable inside quotation marks? For example ``` number =1 system (sudo asterisk -rx "pjsip show aor [number]") ``` Thank you in advance
This is not that simple a question: you need to construct the string in memory at runtime, for example, by usingsprintf: ``` char command[100]; int number = 1; sprintf(command, "sudo asterisk -rx \"pjsip show aor [%d]\"", number); system(command); ``` The above code writes the command, including the value ofnumberconverted to decimal, into achar[]buffer calledcommand, and passes this command tosystemfor execution.
I tried to read around this site to find answer but none of the posts quite answered my problem (which is probably easy one). I have a struct of person's id ``` struct user_id { uint8_t birthday; uint8_t birthmonth; uint16_t birthyear; }; struct user_id xxxxx; xxxxx.birthday=2; xxxxx.birthmonth=2; xxxxx.birthyear=2017; ``` I have to access person's birth year and save it to pointer and later use it in that format. ``` uint16_t *year; *year = xxxxx.birthyear; ``` When I try to save value to *year I get the error described in title. What am I doing wrong?
``` *year = xxxxx.birthyear; ``` This line means that you are trying to dereferenceyearwhich is not pointing to anything yet. To make it point toxxxxx.birthyear, do this ``` year = &xxxxx.birthyear; ```
I used Paho - MQTT client library for MQTT connection, but it takes default interface to connect the internet. Is there any MQTT API for the select specific interface like eth0/wlan0 and through it I connect to the internet.
Paho MQTT C library does not seem to usebind()betweencreating the socketandcallingopen(), so the answer would be NO. Anyway it's opensource and from skimming the project, i went through at most 2 levels of abstraction between library interface and raw POSIX metal, so it should be fairly simple to add such functionality yourself.A random answer describing socket binding howto.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed6 years ago.Improve this question ``` int factorial(int n) { return ( n==0 ? 1 : factorial(n-1)*n ) ; } ``` vs. ``` int factorial(int n) { return ( n==0 ? 1 : n*factorial(n-1) ) ; } ``` I want to know which one is prefered to use. is there any diference between them. is there a situation that we must consider in order of function calls or variable calculations to achive better run time.
There's no difference. C doesn't specify the order of execution of the*operands, soa * bandb * aare effectively equivalent, for any expressionsaandb.
So I just have a simple question. How can I use a variable inside quotation marks? For example ``` number =1 system (sudo asterisk -rx "pjsip show aor [number]") ``` Thank you in advance
This is not that simple a question: you need to construct the string in memory at runtime, for example, by usingsprintf: ``` char command[100]; int number = 1; sprintf(command, "sudo asterisk -rx \"pjsip show aor [%d]\"", number); system(command); ``` The above code writes the command, including the value ofnumberconverted to decimal, into achar[]buffer calledcommand, and passes this command tosystemfor execution.
I have to accomplish bit manipulation. My task is to iterate through many one byte values, and pull out certain amount of bits from each byte (sometimes odd, sometimes even) and be able to combine all those together. Is there a good way to accomplish this? Here's a better explanation. My goal is to allow me to take certain bits from one byte and combine them with bits from another byte. So for example, combine the first 3 bits from 0xE1, with the last 5 bits from 0xA1.
Extracting bits from integral values can be done with the bitwiseandandshiftoperations. ``` unsigned int c = 23; c & 0xF // extract the lowest 4 bits, 0xF is binary 1111 c & 0x7F // extract the lowest 7 bits, 0x7F is binary 1111111 (c >> 4) & 0x3 // extract 2 bits starting at bit 4 (0 indexed). ```
Hy all, I want to build a project with Conan C/C++ Package manager, i have some issues... it can't find the Conanfile but the Conanfile exists! ... CentOs ... I have a folder "mytimer" : ``` [user mytimer]$ ls build CMakeLists.txt Conanfile.txt LICENSE README.md timer.cpp ``` and I want to build in "build" folder : ``` [user mytimer]$ cd build [user build]$ conan install --file ../Conanfile.txt .. **ERROR: Conanfile not found!** ``` How can I fix this ? thank you :)
You have an extra leading path. Use either: ``` [user build]$ conan install --file ../Conanfile.txt ``` or ``` [user build]$ conan install --file Conanfile.txt .. ```
I found some lines of code, those are dimmed in my preprocessor block of source code inC. My compiler, MS Visual Studio, naming it "inactive preprocessor block". What does this mean, will my compile do not consider these lines of code, and how to make it active block?
An inactive preprocessor block is a block of code that is deactivated because of a preprocessor directive. The simplest example is: ``` #if 0 //everytyhing here is inactive and will be ignored during compilation #endif ``` A more common example would be ``` #ifdef SOME_VAR // code #else // other code #endif ``` In this case either the first or the second block of code will be inactive depending on whetherSOME_VARis defined.
eg. ``` int main(){ int s = 4, i = 3; if(s & i == 0) cout << (s & i) << endl; if(!(s & i)) cout << (s & i) << endl; return 0; } ``` Output only one zero. Why not no print or print two zero?
==has higher precedence than&. So ``` if (s & i == 0) ``` is actually equivalent to ``` if (s & (i == 0)) ``` In other words, you're checking ifiis0and then&ing the result (0 or 1) withs. You probably wanted ``` if ((s & i) == 0) ```
I can't understand why it prints 8 times the text. In my conception it should prints just 2 times. Could anynone help me? The code: ``` #include <stdio.h> #include <stdlib.h> int main(void) { pid_t x=0; pid_t y=0; x=fork(); if(y>0) fork(); if(x==0) y=fork(); fork(); if(y==0){ fork(); printf("Some text\n"); } } ```
x = fork();is executed and 2 processes are running. if (y>0) fork();will never be executed. if (x==0) y=fork();will be executed by the child process so now there are 3 processes running. For the initial parentyis still0. For the child it'sy == child_child's pidand for the child's child it'sy==0. All 3 processes will executefork()so there are 6 processes in total, 4 of these havey==0in their memory. These 4 processes fork again, so there are 8 processes and they execute thatprintf(...);
When i run this code it prints the dos 0 character(space) once, puts a space and prints dos 1 character(smiley face with white eyes and mouth). ``` int c = 0, b = 1; printf("%c %c", c, b); ``` But when i run this code below the result is being printed twice. I either get 2 spaces or 2 smiley faces. ``` while(c != -1) { c = getchar() != EOF; putchar(c); } ``` Edit: My code doesnt have paranthesis so it compares every single entered character with EOF and assigns the result (0 or 1) to c and then prints c as a char. In order to prevent this, we can use paranthesis to force the program to do c = getchar() first and then compare that value with EOF. ``` while((c = getchar()) != EOF) ```
Your problem is that a '\n' character is not equal to EOF. The '\n' is being read in as a second character.
I do not understand why before if-statement ++b[1] is equal to 1, but after if-statment ++b[1] is equal to 0. Why ++b[1] does not increase inside if-statement? ``` #include <stdio.h> int main() { int c = 0; int b[3] = {4}; printf("%d\n", ++b[1]); // return 1 b[1]--; if((c-- && ++b[1])|| b[0]++) { printf("%d\n", b[1]); // return 0 printf("%d\n", c); // return -1 } return 0; } ```
``` if((c-- && ++b[1])|| b[0]++) ``` c--yields0, so++b[1]is not evaluated. This is calledshort-circuit evaluation.
Are there any static code metrics tools that measure total size of static local variables in c functions. The tools that I explored report the stack size but not the size of the static local variables. Is there another option apart from using linux objdump and parsing the output?
The POSIXsizecommand can be used for this purpose. The size of the data section is the size of all data in static storage (except data declared const on some targets).
I have a program in C that reads /proc/net/dev and parses the number of bytes downloaded and uploaded. I use it to show notifications when I'm about to cross certain threshold and to keep statistics of download/upload. My question is, how do I make this work on Windows as well? Is there any file with the same function as /proc/net/dev on Unix systems? Or how do I get number of bytes transferred since boot on Windows? Thanks.
In your C program you could do something such assystem('netstat -e')and parse the results. Other netstat options may help for this type of thing as well.
I've run into the__loaddskeyword as a function declaration modifier in some old code for 16-bit Windows that I was looking at out of curiosity. AGoogle searchdid not yield anything useful, presumably because no one uses the compilers that supported that keyword anymore. I'm guessing from its name that it had something to do with theDS(data segment) register and the segmented memory model of x86 real mode.
The online documentation for the Digital Mars compilertalks about this function declaration modifier: __loaddsThis keyword aid those programming Microsoft Windows.__loaddscauses the compiler to loadDSfromDGROUPon entry to the function and to restoreDSon exit.The-mucompiler option applies__loaddsto all functions. Note that this modifier is completely obsolete, as applies only to16-bitWindows environments, like Windows 3.1.
I'm revising for my mid-term exam in concurrent programming in C and I'm stuck on this question. Say you have the following loop: ``` int x = 20; for (int i = -3; i <= 7; i++) x -= 2; } ``` On a monoprocessor machine, what are the minimum and maximum values possible for the variable int x after being executed simultaneously by 5 threads? EDIT : x is of course a shared (global) variable with each thread.
The behaviour of the program isundefineddue to the potential for simultaneous read and write tox. Access toxneeds to be controlled by mutual exclusion, or steps need to be taken to ensure thatx -= 2isatomic. Only then can we talk about the possible values thatxcan take.
I have a program in C that reads /proc/net/dev and parses the number of bytes downloaded and uploaded. I use it to show notifications when I'm about to cross certain threshold and to keep statistics of download/upload. My question is, how do I make this work on Windows as well? Is there any file with the same function as /proc/net/dev on Unix systems? Or how do I get number of bytes transferred since boot on Windows? Thanks.
In your C program you could do something such assystem('netstat -e')and parse the results. Other netstat options may help for this type of thing as well.
I've run into the__loaddskeyword as a function declaration modifier in some old code for 16-bit Windows that I was looking at out of curiosity. AGoogle searchdid not yield anything useful, presumably because no one uses the compilers that supported that keyword anymore. I'm guessing from its name that it had something to do with theDS(data segment) register and the segmented memory model of x86 real mode.
The online documentation for the Digital Mars compilertalks about this function declaration modifier: __loaddsThis keyword aid those programming Microsoft Windows.__loaddscauses the compiler to loadDSfromDGROUPon entry to the function and to restoreDSon exit.The-mucompiler option applies__loaddsto all functions. Note that this modifier is completely obsolete, as applies only to16-bitWindows environments, like Windows 3.1.
I'm revising for my mid-term exam in concurrent programming in C and I'm stuck on this question. Say you have the following loop: ``` int x = 20; for (int i = -3; i <= 7; i++) x -= 2; } ``` On a monoprocessor machine, what are the minimum and maximum values possible for the variable int x after being executed simultaneously by 5 threads? EDIT : x is of course a shared (global) variable with each thread.
The behaviour of the program isundefineddue to the potential for simultaneous read and write tox. Access toxneeds to be controlled by mutual exclusion, or steps need to be taken to ensure thatx -= 2isatomic. Only then can we talk about the possible values thatxcan take.
This question already has answers here:C/C++ line number(10 answers)Closed6 years ago. Is there any way to get the source code line number in C code in run time? The thought behind it is, suppose a software is made in plain C language. the .exe file is distributed to a user who knows nothing about C. Now if there is any error, the user can see the line number and report the error to the manufacturer so that the debugging can be done at manufacturer site. I just to debug the run time errors and get the corresponding line numbers in the source code while running it. I am a beginner in these stuffs.
If you are using the GCC compiler, you can use the Standard Predefined Macro -__LINE__as a line number placeholder. The compiler will fill in the line number while compiling. Eg :- printf("%d",__LINE__);
I want to save and execute my codes that's written in C programming language with just pressing F5 key in vim (in normal mode). So I added this line to .vimrc file : ``` :autocmd FileType c nnoremap <F5> <Esc>:w!<CR>:!clear && gcc %<CR> && ./<CR> ``` But it doesn't work ! (It's make .Out file but it isn't run that file) How can I do that's purpose with editing .vimrc file?
Add these lines to your.vimrc ``` autocmd FileType c \ set makeprg=gcc\ -Wall\ %\ -o\ output | \ nnoremap <special> <buffer> <F5> :w!<cr>:make<cr>:!./output ``` With this form you use:makealone for compiling. PressF5and then pressEnterto execute the output.
How do I check if my structure has a membersomethingin C99? ``` #include <stdlib.h> #include <string.h> struct some { char title[50]; char name[50]; }; int main() { struct some s; if (*s.something) { // Error: no member named 'something' in 'struct.some' strcpy(s.something, "Hello"); } } ``` UPDATED: I don't need to know if it exists at compile time, but in a built program. The members and their values will be parsed from a file and then consumed to the struct in a loop but I need to be sure that it will skip all non-existing members.
C99 (or even C++) does not support reflection. So there is no way of checking if a struct contains a member with a particular name at runtime; the compiler will tell you at compile time instead. This is different from other languages, like, for example, java, which support reflection.
How do I check if my structure has a membersomethingin C99? ``` #include <stdlib.h> #include <string.h> struct some { char title[50]; char name[50]; }; int main() { struct some s; if (*s.something) { // Error: no member named 'something' in 'struct.some' strcpy(s.something, "Hello"); } } ``` UPDATED: I don't need to know if it exists at compile time, but in a built program. The members and their values will be parsed from a file and then consumed to the struct in a loop but I need to be sure that it will skip all non-existing members.
C99 (or even C++) does not support reflection. So there is no way of checking if a struct contains a member with a particular name at runtime; the compiler will tell you at compile time instead. This is different from other languages, like, for example, java, which support reflection.
I am reading source atopenssl, and the following lines apparently definesSSL_OP_NO_SSLv3if it is not defined yet. Never saw such magic before. Can anyone teach me the syntax here? ``` #if !defined(OPENSSL_NO_SSL3) | SSL_OP_NO_SSLv3 #endif ``` You can referencethis linkfor full file and see line 327.
The question makes sense only with the surrounding code (slightly simplified here): ``` mask = SSL_OP_NO_TLSv1_1|SSL_OP_NO_TLSv1 #if !defined(OPENSSL_NO_SSL3) |SSL_OP_NO_SSLv3 #endif ; ``` The preprocessor just does textual substitution. So if the preprocessor macroOPENSSL_NO_SSL3is not defined, the preprocessed code will look like this: ``` mask = SSL_OP_NO_TLSv1_1|SSL_OP_NO_TLSv1 |SSL_OP_NO_SSLv3 ; ``` otherwise the preprocessed code ill look like this: ``` mask = SSL_OP_NO_TLSv1_1|SSL_OP_NO_TLSv1 ; ```
Having defined this: ``` int var1 = 1; int var2 = 2; int var3 = 3; ``` I want to make this: ``` int result = varc * 70; // Where c is a previously defined int that can take 1,2 or 3 value. ``` Solutions? Thank you.
In C you're out of luck on this since it's not areflectivelanguage. That is you can't get the value of a variable by somehow "stringifying" the name you gave it in the source code. But what you could do is use anarray: ``` int vars[] = {1, 2, 3}; int result = vars[i] * 70; ``` whereiis 0, 1, or 2.
I have been looking up some examples of reading from a file in C and I see both ``` fgets(buff,255,(FILE*)fp); ``` and ``` fgets(buff,255,fp); ``` assuming fp is the file pointer defined earlier "FILE *fp;" Is there any difference in this at all? or does the compiler just convert one to another? Also I notice in some "While" loops that read the entire file, some say while(fgets(buff,255,fp)) (so assuming while it's true) and some will specifically check while(fgets(buff,255,fp)!= NULL). Shouldn't the "true" one fail? since it returns the buff if it succeeds and null if it fails? Thanks
A non-null pointer is treated as true in a conditional statement. Therefore, ``` while(fgets(buff,255,fp)) ``` is equivalent to ``` while(fgets(buff,255,fp)!=NULL) ``` Also, the(FILE*)fpis a typecast. Sincefpis already declared asFILE *fp;the cast has no effect.
I am curious to know,Is it possible to use array of bit fields?Like: ``` struct st { unsigned int i[5]: 4; }; ```
No, you can't. Bit field can only be used with integral type variables. C11-§6.7.2.1/5 A bit-field shall have a type that is a qualified or unqualified version of_Bool,signed int,unsigned int, or some other implementation-defined type. Alternatively you can do this ``` struct st { unsigned int i: 4; } arr_st[5]; ``` but its size will be 5 times the size of astruct(as mentioned incommentby @Jonathan Leffler) having 5 members each with bit field4. So, it doesn't make much sense here. More closely you can do this ``` struct st { uint8_t i: 4; // Will take only a byte } arr_st[5]; ```
This question already has an answer here:C: error: expected ')' before ';' token(1 answer)Closed6 years ago. I'm not sure why I'm not allowed to do this. Can someone explain to how to get around the compilation error. I'm new to C, came from Java. error: expected ':' or '...' before ';' token ``` #define NORTH 1; int main (void){ switch (functionCallThatReturnsAnInt()){ case NORTH : //compile time error here printf("NORTH"); break; case 2 : // no compile time error printf("2"); break; //removed rest to reduce clutter } } int functionCallThatReturnsAnInt(void){ return NORTH; } ```
For future viewers: As noted above by @PSkocik and @BLUEPIXY when using define leave off the semicolon. Instead of ``` #define NORTH; ``` Use ``` #define NORTH ```
I am curious why the following implementation always return 0 using the visual studio compiler, but it works fine when compiled with gcc and clang ``` int poissrand(double lambda){ int k=0; double L=exp(-lambda), p=1; do { ++k; p *= rand()/(double)INT_MAX; } while (p > L); return --k; } ``` Exampleshere(vc) andhere(gcc)
In MSVC the range ofrand()is different. In all versions it is specified byRAND_MAXinstdlib.h. If the value you multiplypby is supposed to be in the range0..1then please try ``` p *= (double)rand() / RAND_MAX; ```
The POSIXacceptfunction returns the descriptor for the socket that has been accepted. Howeveruv_acceptreturns an error indicator instead. How to get the file descriptor then?
The question can be slightly reformulated as: Extracting the file descriptor out of a handle Ironically, that is the title of a section of the migration guide to libuv 1.0 (seeherefor further details). Before version 1.0, the not recommend way to do that was accessing the internals of the library as it follows: ``` handle->io_watcher.fd ``` Since libuv v1.0, the recommend way is usinguv_filenoinstead.The documentation states that: Gets the platform dependent file descriptor equivalent.The following handles are supported: TCP, pipes, TTY, UDP and poll. [...] Therefore, it depends on what version of libuv you are using which is the best way to get it out of a handle.
From the C standard (5.2.2 Character display semantics): \t (horizontal tab) Moves the active position to the next horizontal tabulation position on the current line.If the active position is at or past the last defined horizontal tabulation position, the behavior of the display device is unspecified. Can someone give me a case where this is applicable?
Say, your text console has 80 character width and tabulation positions are 0,8,16,....72. According to the standard, you know that if you send (print) one tabulation character to the console, your cursor moves to the 8th position. If two, then to 16th position .... If nine, then to 72th position. But if you send more tabulations, it's not specified where your cursor should be placed. For example, on my current console it's placed to the rightmost (79) position in that case but in no way should we rely on this assumption.
I have a warning note: expected 'float *' but argument is of type 'int *' My program is ``` #include <stdio.h> //header file void foo(float *); int main() { int i = 10, *p = &i; foo(&i); } void foo(float *p) { printf("%f\n", *p); } ``` Output is 0.000 000 Why?
The foo function expects a parameter of typeint *(pointer to integer), not of typefloat *(pointer to float). Change the data typefloatto anintand substitute"%d"instead of"%f"to get rid of the warning.
This function is supposed to get a line from the terminal. But it doesn't! I have gone over the code multiple times, but I haven't been able to pinpoint the problem! Please help! It doesn't seem that the code is entering the while block. ``` int getline(char line[]) { int i = 0 ; int c ; while( ((c=getchar()) != EOF) && (c =! '\n') ) { line[i++] = c ; } line[i] = '\0' ; return i ; } ```
Well this is incorrect ``` while( ((c=getchar()) != EOF) && (c =! '\n') ) ``` it should be ``` while( ((c=getchar()) != EOF) && (c != '\n') ) ``` Do you notice the difference?!=is comparison (which is correct), and=!is completely different (which means negating'\n'and assign it toc) - which was wrong. So, attentions to the details please :)
This question already has answers here:fastest way to determine if a bit is set in a integer data type(3 answers)Closed6 years ago. For reading the 31th bit(MSB) of a 32bit integer one method is as below ``` int main(int argc, char *argv[]) { int b =0x80005000; if(b&(1<<31)) printf("bit is one\n"); else printf("bit is zero\n"); return 0; } ``` My question is, is there any other optimum method to do this with less instruction cycles?
In two's complement representation, the MSB is set when the number is negative and clear when the number is non-negative, so this would also work. ``` int b = 0x80005000; if (b < 0) printf("bit is one\n"); else printf("bit is zero\n"); ``` In fact, for theif(b&(1<<31))codeyouwrote, GCC does produce assembly that compares to 0 and checks the sign - identical to the output that GCC generates on this code.
There are plenty of examples written in C on how to verify a digital signature on a message but my use case requires me to provide only the message hash. So is there an alternative toEVP_DigestVerifyUpdate(mdctx, msg, strlen(msg));where I could directly provide a hash?
Is this what you are looking for? ``` EVP_PKEY *public_key = ...; EVP_PKEY_CTX *public_key_ctx = EVP_PKEY_CTX_new(public_key, NULL); EVP_PKEY_verify_init(public_key_ctx); if (1 != EVP_PKEY_verify(public_key_ctx, sig, siglen, hash, hashlen)) // invalid signature ```
The POSIXacceptfunction returns the descriptor for the socket that has been accepted. Howeveruv_acceptreturns an error indicator instead. How to get the file descriptor then?
The question can be slightly reformulated as: Extracting the file descriptor out of a handle Ironically, that is the title of a section of the migration guide to libuv 1.0 (seeherefor further details). Before version 1.0, the not recommend way to do that was accessing the internals of the library as it follows: ``` handle->io_watcher.fd ``` Since libuv v1.0, the recommend way is usinguv_filenoinstead.The documentation states that: Gets the platform dependent file descriptor equivalent.The following handles are supported: TCP, pipes, TTY, UDP and poll. [...] Therefore, it depends on what version of libuv you are using which is the best way to get it out of a handle.
From the C standard (5.2.2 Character display semantics): \t (horizontal tab) Moves the active position to the next horizontal tabulation position on the current line.If the active position is at or past the last defined horizontal tabulation position, the behavior of the display device is unspecified. Can someone give me a case where this is applicable?
Say, your text console has 80 character width and tabulation positions are 0,8,16,....72. According to the standard, you know that if you send (print) one tabulation character to the console, your cursor moves to the 8th position. If two, then to 16th position .... If nine, then to 72th position. But if you send more tabulations, it's not specified where your cursor should be placed. For example, on my current console it's placed to the rightmost (79) position in that case but in no way should we rely on this assumption.
I have a warning note: expected 'float *' but argument is of type 'int *' My program is ``` #include <stdio.h> //header file void foo(float *); int main() { int i = 10, *p = &i; foo(&i); } void foo(float *p) { printf("%f\n", *p); } ``` Output is 0.000 000 Why?
The foo function expects a parameter of typeint *(pointer to integer), not of typefloat *(pointer to float). Change the data typefloatto anintand substitute"%d"instead of"%f"to get rid of the warning.
This function is supposed to get a line from the terminal. But it doesn't! I have gone over the code multiple times, but I haven't been able to pinpoint the problem! Please help! It doesn't seem that the code is entering the while block. ``` int getline(char line[]) { int i = 0 ; int c ; while( ((c=getchar()) != EOF) && (c =! '\n') ) { line[i++] = c ; } line[i] = '\0' ; return i ; } ```
Well this is incorrect ``` while( ((c=getchar()) != EOF) && (c =! '\n') ) ``` it should be ``` while( ((c=getchar()) != EOF) && (c != '\n') ) ``` Do you notice the difference?!=is comparison (which is correct), and=!is completely different (which means negating'\n'and assign it toc) - which was wrong. So, attentions to the details please :)
This question already has answers here:fastest way to determine if a bit is set in a integer data type(3 answers)Closed6 years ago. For reading the 31th bit(MSB) of a 32bit integer one method is as below ``` int main(int argc, char *argv[]) { int b =0x80005000; if(b&(1<<31)) printf("bit is one\n"); else printf("bit is zero\n"); return 0; } ``` My question is, is there any other optimum method to do this with less instruction cycles?
In two's complement representation, the MSB is set when the number is negative and clear when the number is non-negative, so this would also work. ``` int b = 0x80005000; if (b < 0) printf("bit is one\n"); else printf("bit is zero\n"); ``` In fact, for theif(b&(1<<31))codeyouwrote, GCC does produce assembly that compares to 0 and checks the sign - identical to the output that GCC generates on this code.
There are plenty of examples written in C on how to verify a digital signature on a message but my use case requires me to provide only the message hash. So is there an alternative toEVP_DigestVerifyUpdate(mdctx, msg, strlen(msg));where I could directly provide a hash?
Is this what you are looking for? ``` EVP_PKEY *public_key = ...; EVP_PKEY_CTX *public_key_ctx = EVP_PKEY_CTX_new(public_key, NULL); EVP_PKEY_verify_init(public_key_ctx); if (1 != EVP_PKEY_verify(public_key_ctx, sig, siglen, hash, hashlen)) // invalid signature ```
First of all, I have a function where I have signs stored inunsigned char*type. For example forAbcdef!?it is[65 0] [98 0] [99 0] [100 0] [101 0] [102 0] [33 0] [63 0]2 bytes per sign in Unicode. When I usefor(unsigned char i=0; i<17; i++) printf("%c", pointer[i]);everything is ok, it showsAbcdef!?. But when I useprintf("%s" pointer);it gives me onlyAand nothing else. Could you tell me why?
Becauseprintf("%s", pointer)literally means:Print everycharstarting at the one stored atpointeruntil'\0'is encountered. There's a'\0'immediately after'A', so only the first character is printed.
In K&R book, Calc program's stack has ``` #define MAXVAL 100 int sp =0; /* next free stack position */ double val[MAXVAL]; /* value stack*/ /* push: push f onto value stack */ void push(double f) { if ( sp < MAXVAL ) val[sp++] = f; else printf ("error: stack full, can't push%g\n",f); } ``` It can push 1 extra value causing stack overflow. It should be (sp < MAXVAL - 1). But It is hard to believe such mistake in this book.
This is not a mistake. Assigning toval[]at indexes from0toMAXVAL-1, inclusive, is legal. Note thatsp++is apost-incrementexpression, meaning thatspis incrementedafterits value has been used for indexingval[]. Hence, there is no undefined behavior in this example.
I have a C static library with global variables. My goal is to print a message at compile time to the user whenever global variables from the library are used in its program. I tried to mark variables as__attribute__((deprecated)). But I need the user to be able to build even if-Werroris set. Therefore I tried to add#pragma GCC diagnostic warning "-Wdeprecated-declarations", but it only seems active within the library, not if a user link with the library.
You could employ linker instead as explained in e.g.ninjalj's blog. Here's a short example: ``` $ cat myvar.c int myvar = 0; static const char myvar_warning[] __attribute__((section(".gnu.warning.myvar"))) = "myvar is deprecated"; $ cat main.c extern int myvar; int main() { return myvar; } $ gcc main.c myvar.c /tmp/cc2uM5Vx.o: In function `main': tmp.c:(.text+0x6): warning: myvar is deprecated ```
First of all, I have a function where I have signs stored inunsigned char*type. For example forAbcdef!?it is[65 0] [98 0] [99 0] [100 0] [101 0] [102 0] [33 0] [63 0]2 bytes per sign in Unicode. When I usefor(unsigned char i=0; i<17; i++) printf("%c", pointer[i]);everything is ok, it showsAbcdef!?. But when I useprintf("%s" pointer);it gives me onlyAand nothing else. Could you tell me why?
Becauseprintf("%s", pointer)literally means:Print everycharstarting at the one stored atpointeruntil'\0'is encountered. There's a'\0'immediately after'A', so only the first character is printed.
In K&R book, Calc program's stack has ``` #define MAXVAL 100 int sp =0; /* next free stack position */ double val[MAXVAL]; /* value stack*/ /* push: push f onto value stack */ void push(double f) { if ( sp < MAXVAL ) val[sp++] = f; else printf ("error: stack full, can't push%g\n",f); } ``` It can push 1 extra value causing stack overflow. It should be (sp < MAXVAL - 1). But It is hard to believe such mistake in this book.
This is not a mistake. Assigning toval[]at indexes from0toMAXVAL-1, inclusive, is legal. Note thatsp++is apost-incrementexpression, meaning thatspis incrementedafterits value has been used for indexingval[]. Hence, there is no undefined behavior in this example.
I have a C static library with global variables. My goal is to print a message at compile time to the user whenever global variables from the library are used in its program. I tried to mark variables as__attribute__((deprecated)). But I need the user to be able to build even if-Werroris set. Therefore I tried to add#pragma GCC diagnostic warning "-Wdeprecated-declarations", but it only seems active within the library, not if a user link with the library.
You could employ linker instead as explained in e.g.ninjalj's blog. Here's a short example: ``` $ cat myvar.c int myvar = 0; static const char myvar_warning[] __attribute__((section(".gnu.warning.myvar"))) = "myvar is deprecated"; $ cat main.c extern int myvar; int main() { return myvar; } $ gcc main.c myvar.c /tmp/cc2uM5Vx.o: In function `main': tmp.c:(.text+0x6): warning: myvar is deprecated ```
In K&R book, Calc program's stack has ``` #define MAXVAL 100 int sp =0; /* next free stack position */ double val[MAXVAL]; /* value stack*/ /* push: push f onto value stack */ void push(double f) { if ( sp < MAXVAL ) val[sp++] = f; else printf ("error: stack full, can't push%g\n",f); } ``` It can push 1 extra value causing stack overflow. It should be (sp < MAXVAL - 1). But It is hard to believe such mistake in this book.
This is not a mistake. Assigning toval[]at indexes from0toMAXVAL-1, inclusive, is legal. Note thatsp++is apost-incrementexpression, meaning thatspis incrementedafterits value has been used for indexingval[]. Hence, there is no undefined behavior in this example.
I have a C static library with global variables. My goal is to print a message at compile time to the user whenever global variables from the library are used in its program. I tried to mark variables as__attribute__((deprecated)). But I need the user to be able to build even if-Werroris set. Therefore I tried to add#pragma GCC diagnostic warning "-Wdeprecated-declarations", but it only seems active within the library, not if a user link with the library.
You could employ linker instead as explained in e.g.ninjalj's blog. Here's a short example: ``` $ cat myvar.c int myvar = 0; static const char myvar_warning[] __attribute__((section(".gnu.warning.myvar"))) = "myvar is deprecated"; $ cat main.c extern int myvar; int main() { return myvar; } $ gcc main.c myvar.c /tmp/cc2uM5Vx.o: In function `main': tmp.c:(.text+0x6): warning: myvar is deprecated ```
Basically, I am learningpipeanddupsystem calls. I want to take a command-name (like ls,cd,mkdir etc) as input from the parent process and pass it on to the child process using pipe, the child process shouldopen up a new xterm windowand show the man page of the command recorded in the pipe in this new xterm window. The problem is that exec changes the whole process image of the child, so any code written after is simply ignored (if exec was successful).So if I exec the child to "/bin/xterm", then any exec calls in the child block are removed, as the process image changed to xterm. So how do I call /bin/man?
There is nothing stopping you callingforkagain - a process can have any number of children, grandchildren etc... In this particular instance you need the child toforkand create grandchildren thatexec"/bin/xterm" with your man command. And also handle clean up of them as they finish.
Which function can return current datetime withd/m/yformat in C language? EDIT: here is my code: ``` #include <stdio.h> #include <time.h> int main() { time_t tmp_time; struct tm * info; time ( &tmp_time ); info = localtime ( &tmp_time ); printf ( "%s", asctime (info) ); } ``` this returns to me something like that Thu Jan 26 13:08:01 2017 and i would like to return 26/01/17 or 26/01/2017
Like this: ``` int main () { time_t rawtime; struct tm * currentTime; time ( &rawtime ); currentTime = localtime ( &rawtime ); printf ( "%d/%d/%d", currentTime->tm_mday, currentTime->tm_mon+1, currentTime->tm_year+1900); return 0; } ``` Be careful,monthsare indexed since 0, andyearis since 1900 intmstruct.
I am trying to compilepyniftipackage from source (long story involving Anaconda Python distribution). After runningmake, I receive the following error: ``` gcc: error: unrecognized command line option ‘--Wl,--no-undefined’ ``` Indeed, the manual (man gcc) contains no information about--no-undefinedswitch. My version ofgccis 4.8.5. Also, I can not find theno-undefinedoption inhttps://gcc.gnu.org/onlinedocs/gcc/Option-Index.html#Option-Index However, fromForce GCC to notify about undefined references in shared librariesI infer that it is a valid switch at least for some version ofgcc.
This switch is alinker optionforld. It is not directly part ofGCCbut it is only encapsulated in a-Wloption to be passed to the linker (you seem to have--Wlwhich is wrong). Edit: Yugr deserves part of the credit as he pointed out the incorrect--Wloption!
This question already has answers here:What does a colon in a struct declaration mean, such as :1, :7, :16, or :32?(3 answers)Closed6 years ago. I'm working with a piece of code and I come across with something similar to this: ``` struct { int a : 1; int b : 1; }; ``` I don't know what is the function of: 1here. For your interest, that struct is inside aunionwhich in turn is inside atypedef struct. Thanks,
This is used to assign value to abit. You can read about bitfieldshere.
In the C programming language, a string such as"2147483649"overflows as an int since the largest unsigned int is2147483647. When I want to convert strings of integers toints, how do I go about checking for these overflow cases? I can't just check if it is>=-(2^32-1)and<= (2^32-1)since the process of converting this string to anint(egatoi()) already changes this value. Is there an easy way instead of checking the number of digits of the string before converting and also each digit at a time to make sure it's within the range ofints?
You can convert the resulting integer back to string and compare it to the source string. Although it doesn't look elegant to me. :-)
So i'm trying to extracts bits from a 32=bit binary integer using bit shifting and masking, but i'm sightly off by one. ``` #include <stdio.h> int main (){ int number = 87; //0000 000 0000 0000 0000 0000 0101 0111 int i; int bit; int g = 0; for(i = 32; i > 0; i--){ if(g%4==0 && g!=0){ printf(" "); } g++; bit = (number >> i) & 1; printf("%d", bit); } printf("\n"); return 0; } ```
There is logic missing in your code.. Use ``` for(i **= 31**; i **>=** 0; i--) ``` instead of ``` for(i **= 32**; i **>** 0; i--) ``` Comment if it works for you
My Source Code ``` for(i=0;str[i]!='\0';i++) { if(str[i]!=' '){ str2[j]=str[i]; flag=1; } if(flag==1 && str2[j]!=' ') { printf("\n"); printf("%c",str2[j]); flag=0; } } ``` My Output: ``` I am joe I a m j o e ``` But I want output like this: ``` I am joe ``` I want each of the word prints in new line likeIin one lineamin another line andjoein another line also need to remove extra space beforejoe
I found it easier to just replace the space characters by new lines ``` #include <stdio.h> int main() { char str[] = "I am joe"; for(int i = 0; str[i] != '\0'; i++) { if(str[i] == ' ') str[i] = '\n'; } printf("%s\n", str); return 0; } ``` All you have to figure out is how to trim those extra spaces....
Which function can return current datetime withd/m/yformat in C language? EDIT: here is my code: ``` #include <stdio.h> #include <time.h> int main() { time_t tmp_time; struct tm * info; time ( &tmp_time ); info = localtime ( &tmp_time ); printf ( "%s", asctime (info) ); } ``` this returns to me something like that Thu Jan 26 13:08:01 2017 and i would like to return 26/01/17 or 26/01/2017
Like this: ``` int main () { time_t rawtime; struct tm * currentTime; time ( &rawtime ); currentTime = localtime ( &rawtime ); printf ( "%d/%d/%d", currentTime->tm_mday, currentTime->tm_mon+1, currentTime->tm_year+1900); return 0; } ``` Be careful,monthsare indexed since 0, andyearis since 1900 intmstruct.
I am trying to compilepyniftipackage from source (long story involving Anaconda Python distribution). After runningmake, I receive the following error: ``` gcc: error: unrecognized command line option ‘--Wl,--no-undefined’ ``` Indeed, the manual (man gcc) contains no information about--no-undefinedswitch. My version ofgccis 4.8.5. Also, I can not find theno-undefinedoption inhttps://gcc.gnu.org/onlinedocs/gcc/Option-Index.html#Option-Index However, fromForce GCC to notify about undefined references in shared librariesI infer that it is a valid switch at least for some version ofgcc.
This switch is alinker optionforld. It is not directly part ofGCCbut it is only encapsulated in a-Wloption to be passed to the linker (you seem to have--Wlwhich is wrong). Edit: Yugr deserves part of the credit as he pointed out the incorrect--Wloption!