question
stringlengths
25
894
answer
stringlengths
4
863
I just realized that in a while loop, when I create a pointer of a structure, the pointer seems undefined when the loop is over. I am not sure if there is such a thing as Pointers created in while loops cannot be used outside of it. Here is a part of my code: ``` if('D'==Status) //depature { while(Top(T)->CarLicense != CarLin) { struct CarNode * tmp; tmp = Top(S); Push(TopAndPop(S), T); tmp->Movement++; } printf("Moved %d, bye!\n",tmp->Movement); DisposeCar(TopAndPop(T)); while(!(IsEmpty(T))) { struct CarNode * tmp2; tmp2 = Top(T); Push(TopAndPop(T),S); } } ``` Here, inprintf("Moved %d, bye!\n",tmp->Movement);,tmpseems undefined.
Because tmp is declared and defined in the while block it goes out of scope when the loop completes. You need to declare it in line above loop so it's still visible when it gets to the printf().
I am looking for an easier way to compare the data at two C-pointers in python. The method I have working now: ``` import cffi ffi = cffi.FFI() def ref_char_p(char_p): arr = [] null_term = 0; while(char_p[null_term] != 0): null_term += 1 for x in range(0, null_term): arr.append(char_p[x]) return arr char_p = ffi.new("char[]", '\x41\x42\x43') char_p2 = ffi.new("char[]", '\x41\x42\x43') if(ref_char_p(char_p) == ref_char_p(char_p2)): print "equal" else: print "not equal" ``` Is there any way I can do something closer to: ``` if(char_p == char_p2): print "equal" ``` I have read through the cffi docs but have not found anything promising.
You can useffi.string()to convert the char array to a bytes object: ``` ffi.string(char_p) == ffi.string(char_p2) ```
I am learning about working with shared libraries in C/C++ on Linux. I encountered a little problem that I don't know how to solve. Let's say I have a shared library and an executable. However I don't know the library's name or file location (so I can'tdlopenit). I can only find the address range where the library is mapped into my executable's memory. Is there a way to programmatically get either the handle of the library (something likehandle = dlopen(library_address)) or offset of a symbol within the library (something likeaddress = dlsym(library_address, symbol_name))?
If you knew the library's name, you could just calldlopenagain. From theman page: If the same shared object is loaded again withdlopen(), the same object handle is returned. To discover the loaded modules, you can usedl_iterate_phdr(). You can also usedladdr()to inquire about a specific address.
Looks like something basic. But I'm unable to see why ``` (*ptr).my_data_ptr->my_data[0].b ``` works, whereas ``` *((*ptr).my_data_ptr).my_data[0].b ``` doesn't. I'm giving the relation between the various datatypes below: ``` typedef struct { int a; int b;} MY_DATA; typedef struct { MY_DATA my_data[2];} MY_DATA_ARR; typedef struct { MY_DATA_ARR *my_data_ptr;} MY_PARAM; typedef MY_PARAM * MY_PARAM_PTR; ```
This is becausea->bis equivalent to(*a).b,not*a.b. Refer toC Operator Precedence, the precedence of member access.is higher than dereference*. Change to this - it will work: ``` (*((*ptr).my_data_ptr)).my_data[0].b ```
As far as I know, "Documents" and all other directories under home are localization related, my question is: is it possible to get full path of "Documents" in C/C++ on Linux (Ubuntu)? Didn't find it inPATHnor otherenv. I'm not looking for$HOME, I'm looking for${HOME}"Documents". For instance, it's "Documents" for English locale, but "文档" for Chinese, etc. Thanks.
It looks like, if this is based on the XDG FreeDesktop standard, then there are two files that contain the info: ``` ~/.config/user-dirs.locale ``` and ``` ~/.config/user-dirs.dirs ``` The former contains the locale itself, while the second contains the mapping to the actual folder paths. References: [1]https://blogs.gnome.org/simos/2007/11/11/localisation-issues-in-home-directory-folders-xdg-user-dirs/[2]https://www.freedesktop.org/wiki/Software/xdg-user-dirs/
I am looking for an easier way to compare the data at two C-pointers in python. The method I have working now: ``` import cffi ffi = cffi.FFI() def ref_char_p(char_p): arr = [] null_term = 0; while(char_p[null_term] != 0): null_term += 1 for x in range(0, null_term): arr.append(char_p[x]) return arr char_p = ffi.new("char[]", '\x41\x42\x43') char_p2 = ffi.new("char[]", '\x41\x42\x43') if(ref_char_p(char_p) == ref_char_p(char_p2)): print "equal" else: print "not equal" ``` Is there any way I can do something closer to: ``` if(char_p == char_p2): print "equal" ``` I have read through the cffi docs but have not found anything promising.
You can useffi.string()to convert the char array to a bytes object: ``` ffi.string(char_p) == ffi.string(char_p2) ```
I came across thefollowing programto implement a shared memory IPC between a client and a server. The following line is used to generate a unique sysv key (as mentionedhere): ``` ShmKEY = ftok(".", 'x'); ``` What does a pathname "." mean in this case? I am completely new to linux and a clear-cut answer will be much appreciated.
Pathname "." means the current directory. You can find more details of functionhereOr executing commandman ftokin your Linux machine.
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.Closed5 years ago.Improve this question This question confused a lot. I got this question from my mid-term as a TF question. Really hope someone can tell me why, Thanks!
On every processor I know of, the answer is NO. If it were, you applications could not allocate memory on the stack. ``` MOV SP, BP ADD #32, SP ``` or free up the memory ``` MOV BP, SP ```
I am trying to use popen to open a pipe to mail process and write a memory mapped array(shared_array) to the body of the email. The email sends but only lists the first entry of shared_array. Any help is appreciated ``` FILE *fp; char (*shared_array)[MAXLINE] shared_array= mmap(0,100*MAXLINE,PROT_READ | PROT_WRITE,MAP_SHARED | MAP_ANON,-1,0); fp = popen("mail -s testing [email protected]","w"); for(k =0; k<total_count;k++){ fwrite(shared_array[k],sizeof(shared_array[k]),1,fp); } fwrite(".\n",sizeof(char*),3,fp); pclose(fp); printf("\n\nEmail Sent\n\n"); } ```
Pablo had it right. I needed to use strlen ``` fwrite(shared_array[k],strlen(shared_array[k]),1,fp); ```
This question already has answers here:Scanf causes C program to crash(2 answers)Closed5 years ago. Whenever I start this code in CodeBlocks, it crashes the console and returns: Process returned -1073741819 (0xC0000005) The code: ``` #include <stdio.h> #include <stdlib.h> main() { int next, prev, max; while (1) { printf("Number: "); scanf("%d", next); if (next > prev) { prev = next; max = next; } if(next = 0){ break; } } printf("Max number is: %d", max); return 0; } ```
Change ``` scanf("%d", next); ``` to ``` scanf("%d", &next); // note & operator ``` The%dspecifier expects the corresponding argument to be an expression of typeint *- that is, a pointer to anint. You're passing the (uninitialized, indeterminate)valuestored innext, which is almost certainly not a valid pointer value.
This question already has answers here:This program sounds the bell!(13 answers)Closed5 years ago. I've just come across this: ``` #include <stdio.h> int main() { printf(" \a "); } ``` and the output isn't " \a " as expected. Does anybody know why?
The'\a'in an escaped representation of theBELcharcater which hasasciicode 7. The\is used to "escape" a character that otherwise has no representation and cannot be written in a string by other means. Another examples are the newline'\n'and carriage return'\r'.
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.Closed5 years ago.Improve this question ``` dow(m,d,y) { y-=m<3; return(y+y/4-y/100+y/400+"-bed=pen+mad."[m]+d)%7; } ``` The function's purpose is to find what day(Su-Sa) will the provided date(1-31) land on in any given month and year. I'm not sure how this function works because it was written in C. Mostly I don't know whatthey-=m<3is for, or what the"-bed=pen+mad."does (is this just a string?).here is my source:https://cs.uwaterloo.ca/~alopez-o/math-faq/node73.html
Just use the python datetime module: ``` import datetime dayOfWeek = datetime.datetime(y, m, d).weekday() ``` dayOfWeekwill then be an integer between 0 and 6 corresponding to Monday - Sunday. Have a look at thedocsfor more details.
I am trying to use popen to open a pipe to mail process and write a memory mapped array(shared_array) to the body of the email. The email sends but only lists the first entry of shared_array. Any help is appreciated ``` FILE *fp; char (*shared_array)[MAXLINE] shared_array= mmap(0,100*MAXLINE,PROT_READ | PROT_WRITE,MAP_SHARED | MAP_ANON,-1,0); fp = popen("mail -s testing [email protected]","w"); for(k =0; k<total_count;k++){ fwrite(shared_array[k],sizeof(shared_array[k]),1,fp); } fwrite(".\n",sizeof(char*),3,fp); pclose(fp); printf("\n\nEmail Sent\n\n"); } ```
Pablo had it right. I needed to use strlen ``` fwrite(shared_array[k],strlen(shared_array[k]),1,fp); ```
This question already has answers here:Scanf causes C program to crash(2 answers)Closed5 years ago. Whenever I start this code in CodeBlocks, it crashes the console and returns: Process returned -1073741819 (0xC0000005) The code: ``` #include <stdio.h> #include <stdlib.h> main() { int next, prev, max; while (1) { printf("Number: "); scanf("%d", next); if (next > prev) { prev = next; max = next; } if(next = 0){ break; } } printf("Max number is: %d", max); return 0; } ```
Change ``` scanf("%d", next); ``` to ``` scanf("%d", &next); // note & operator ``` The%dspecifier expects the corresponding argument to be an expression of typeint *- that is, a pointer to anint. You're passing the (uninitialized, indeterminate)valuestored innext, which is almost certainly not a valid pointer value.
This question already has answers here:This program sounds the bell!(13 answers)Closed5 years ago. I've just come across this: ``` #include <stdio.h> int main() { printf(" \a "); } ``` and the output isn't " \a " as expected. Does anybody know why?
The'\a'in an escaped representation of theBELcharcater which hasasciicode 7. The\is used to "escape" a character that otherwise has no representation and cannot be written in a string by other means. Another examples are the newline'\n'and carriage return'\r'.
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.Closed5 years ago.Improve this question ``` dow(m,d,y) { y-=m<3; return(y+y/4-y/100+y/400+"-bed=pen+mad."[m]+d)%7; } ``` The function's purpose is to find what day(Su-Sa) will the provided date(1-31) land on in any given month and year. I'm not sure how this function works because it was written in C. Mostly I don't know whatthey-=m<3is for, or what the"-bed=pen+mad."does (is this just a string?).here is my source:https://cs.uwaterloo.ca/~alopez-o/math-faq/node73.html
Just use the python datetime module: ``` import datetime dayOfWeek = datetime.datetime(y, m, d).weekday() ``` dayOfWeekwill then be an integer between 0 and 6 corresponding to Monday - Sunday. Have a look at thedocsfor more details.
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.Closed5 years ago.Improve this question I need to know how pointer is used and what it returns if USED in function called and has a defined empty parameters with asterisk only like in example (unsigned char *) ``` unsigned char func.name( unsigned char * ); ``` So, can we use empty parameter with pointer and when? and what shall the argument to be?
You can omit the name of an argument any time you want to. The only downsides to doing so are: If you omit the argument name in the function declaration (i.e. in .h file), it might make the intended purpose of that argument harder for a (human) reader to understand.If you omit the argument name in the function definition (i.e. in the .cpp file), the code in your function body will not be able to refer to that argument.
I am trying to build a small quadratic calculator in C, but I am getting the following result no matter what my input is.... Here is my code: ``` #include <stdio.h> #include <stdlib.h> #include <math.h> int main(void) { float a, b, c; printf("Enter a:"); scanf("%f", &a); printf("Enter b:"); scanf("%f", &b); printf("Enter c:"); scanf("%f", &c); float discriminant = sqrt(b*b - 4*a*c); float root1 = (-b + discriminant) / (2*a); float root2 = (-b - discriminant) / (2*a); printf("Root 1: %f\n", root1); printf("Root 2: %f\n", root2); } ```
float discriminant = sqrt(b*b - 4*a*c) This line is potentially dangerous, as it'll sometimes do the square root of a negative number. If you want to be able to handle complex roots you'll have to custom build a solution for that. What you can change with this is to just verify that input doesn't cause that to be negative.
This question already has answers here:Why is this happening with the sizeof operator when comparing with a negative number? [duplicate](2 answers)sizeof() operator in if-statement(5 answers)Closed5 years ago. According to the code below, size of int is not greater than -1. Why is it so? Why "False" was printed instead of "True"? ``` #include <stdio.h> #include <stdlib.h> int main() { if(sizeof(int) > -1) { printf("True\n"); } else { printf("False\n"); } // Here size of int is equals to 4 printf("Size of int: %ld\n", sizeof(int)); return 0; } ```
Wellsizeofreturnssize_twhich is unsigned and when it is compared withintthe int is promoted to unsigned and the bit representation all 1's now considered as unsigned, which is bigger than-1and also that ofsizeof int. That's why this result. Correct format specifier forsize_tis%zu.
In myCcode I want to run an external program. For this I usesystem()function like this example: ``` system("/bin/myprog"); ``` But I want to detect if my external program have error or not exit correctly. How can I get the error?
If you want to get the error message then you need to trap thestderrfrom the external program. Note thatpopentrapsstdout, so you need to redirect using the shell construct2>&1(fortunatelypopenalso runs a shell). For example: ``` #define BUFF_SIZE 1024 int main() { char buffer[BUFF_SIZE]; FILE *p = popen("/bin/myprog 2>&1", "r"); while (fgets(buffer, BUFF_SIZE, p)) printf("Recieved: %s\n", buffer); return 0; } ``` EDIT: To ignorestdoutmessages and only getstderrmessages then use: ``` FILE *p = popen("/bin/myprog 2>&1 1>/dev/null", "r"); ```
For example, I have two digit bits: ``` 0b0111111 0b0000110 ``` I want to shift a state variable by 7 digits and combine them together. ``` 0b00001100111111 ``` Can I accomplish by shifting?
You do this by shifting the bottom number left 7 digits, then performing a bitwise OR of the result and the first number. ``` unsigned int a = 0x3f; unsigned int b = 0x06; unsigned int result = (b << 7) | a; ```
I feel like I've been searching for hours today on how to make#include <pthread.h>work in Visual Studio 2017 on Windows 10 and haven't come across an answer that has worked. Can someone please instruct me how to get this to work? The error I receive is: cannot open source file "pthread.h"
In Visual Studio 2017 Project -> Manage Nuget PackagesIn browse Tab search for 'pthread'Select Install[Search Results in Nuget packages]
I feel like I've been searching for hours today on how to make#include <pthread.h>work in Visual Studio 2017 on Windows 10 and haven't come across an answer that has worked. Can someone please instruct me how to get this to work? The error I receive is: cannot open source file "pthread.h"
In Visual Studio 2017 Project -> Manage Nuget PackagesIn browse Tab search for 'pthread'Select Install[Search Results in Nuget packages]
I feel like I've been searching for hours today on how to make#include <pthread.h>work in Visual Studio 2017 on Windows 10 and haven't come across an answer that has worked. Can someone please instruct me how to get this to work? The error I receive is: cannot open source file "pthread.h"
In Visual Studio 2017 Project -> Manage Nuget PackagesIn browse Tab search for 'pthread'Select Install[Search Results in Nuget packages]
What is the meaning of the following operation in C ``` USIC2_CH0->PSR &= ~((uint32_t)USIC_CH_PSR_ASCMode_TFF_Msk); ``` I know that ifA|=BmeantA=A|Bthen what is meant by A&=~B;? Does that meantA=~(A&B)??
A &= ~BmeansA = A & (~B), notA=~(A&B). You can see those two are different if you take A=b010 and B=b110, for example. In context it's disabling the bits in that PSR bitfield that are set in the constant whose name ends in "TFF_Msk" above.
I'm learning bitwise operation and i came across a xor operation, ``` #include<stdio.h> #include<conio.h> int main { printf("%d\n",10 ^ 9); getch(); return 0; } ``` the binary form of 10 ---> 1 0 1 0 the binary form of 9 ---> 1 0 0 1 So in XOR the output is 1 when one of the input is 1 and other is 0. So the output of 10 ^ 9 is 0 0 1 1 => 3 So when trying for the -10 ^ 9, I'm getting the output as -1. ``` #include<stdio.h> #include<conio.h> int main { printf("%d\n",-10 ^ 9); getch(); return 0; } ``` Can some one explain me how it is -1? Thanks in advance for all who helps!
Because the operator precedence of XOR is lower than the unary minus. That is,-10 ^ 9is equal to(-10) ^ 9.-10 ^ 9is not equal to-(10 ^ 9). -10 is 11110110(2)and 9 is 00001001(2). 11110110(2)XOR 00001001(2)= 11111111(2) 11111111(2)is -1 in 2's complement representation.
I'm trying to write a code that outputs a checkerboard type effect with astericks by using for loops. I cant seem to get it to work. Here's my code. Any help is greatly appreciated. ``` #include <stdio.h> int main (void) { int a; int b; for(a=1; a<=10; a+=2) { printf("* * * * * * * * * *"); } for (b=2; b<=10; b+=2) { printf(" * * * * * * * * * "); } return 0; } ```
You need to alternate each row ``` #include <stdio.h> int main (void) { int a; for(a=1; a<=10; a+=2) { printf("* * * * * * * * * *\n"); printf(" * * * * * * * * * \n"); } return 0; } ```
I am writing a program in C where I am comparing two bytes of data, and then seeing if the bytes are different, and if so, at which bits. This is what I have so far: ``` int var1 = 81; //Binary: 0101 0001 int var2 = 193; //Binary: 1100 0001 int diff = var1 ^ var2; //diff = 1001 0000 / 144 ``` Basically I know how to use the XOR bitwise operator to see which bits are different between the two variables, but from here I don't know how to use diff to figure out which bits are the differences. For example, in my above code I'd want to use diff to output "Bit 5 and Bit 8 are different".
You can use a forloopto get that idea and make bitwiseANDwith1properly left shifted to get the set bits positions ``` for(size_t i = 0; i < sizeof(int)*8; i++){ if( diff & (1U << i)) printf("%zu is different\n",i+1); } ```
I have long string in C and I want pass this to lua function. but beacause string is long I don't want pass it, I want pass pointer of string to lua. I do this by use lua_pushlightuserdata but in Lua I can't use this pointer. C code : ``` char* st = "abcdefghijklmnopqrstuvwxyz1234567890"; lua_getglobal(myLuaState,"kk"); lua_pushlightuserdata(myLuaState,st); lua_pcall(myLuaState, 1, 0, 0); ``` Lua code : ``` function kk(a) print(a) end ``` result of code is: ``` userdata: 0x41b4d8 ```
you can use ffi in Luajit ``` function kk(a) local ffi = require("ffi") s = ffi.string(a) print(s) end ``` the result is: ``` abcdefghijklmnopqrstuvwxyz1234567890 ```
How can I use assembly instructions that contain quotation marks insideasm()? like: ``` asm( ".section .rdata,"dr"\n" ); ``` The code above gives me this error: ``` expected ')' before 'dr' ```
Any string literal, not just the ones required by anasmdeclaration, can contain double quotes if they are escaped. You escape them with a\. So when applied to your example: ``` asm( ".section .rdata,\"dr\"\n" ); ```
I found this code for converting a string into separate strings: ``` const char *s = " ,.?\n\0"; char *token; /* get the first token */ token = strtok(buffer, s); /* walk through other tokens */ while( token != NULL ) { printf( " %s\n", token ); token = strtok(NULL, s); ``` buffer containing the string. The problem that I am having now, is that I want to count how many times a token (sub-string) occurs and print that to the user. Can someone help?
Could be done relatively simple using a structure with the token and its counter as a member, and then having a dynamic array or list or other container-like data-structure. When you read a token, see if you already have it save, and then increase its counter. Otherwise add it with a count of one.
There are new format specifiers forintN_ttypes, for example%"PRIiN"and%"SCNiN", forprintfandscanffamilies of functions. What are, if any, the new format specifiers forfloat_tanddouble_t? (defined inmath.h) Can I -safely- use%fand%lf? I don't think so, becausefloat_tis only at least as large asfloat, but could be defined aslong double. As nobody answered, and I don't find the answer anywhere, may it be a bug in C?
To be cautious and portable you could us%Lfin yourprintfcontrol string and cast values of typefloat_tordouble_ttolong double. Edited:Format specifier for long double is%Lfand not%lf You have to be more cautious for scanf because in that case casting won't help you. Alternatively you could define your ownprintfandscanfformat specifiers forfloat_tanddouble_t, making use of theFLT_EVAL_METHOD[1] macro to find out which built-in types thatfloat_tanddouble_tare respectively equivalent to.
In nginx, a pointer initial byngx_pcalloc()make sure that the lowest 2 bit is00? For example,p = ngx_pcalloc(pool, size), make sure((uintptr_t)p)&(0x3) == 0? I will appreciate it if you help me.
The code forngx_pcallocis inngx_palloc.cso you can follow its calls to see that it returns memory aligned toNGX_ALIGNMENT. On most platforms,NGX_ALIGNMENTis definedas the size of anunsigned long. Solaris appears to be the exception: there it is defined as_MAX_ALIGNMENTwhich is"Equal to the maximum of all the above _XXX_ALIGNMENT values"which includes the alignment for unsigned longs. The C standard requiresunsigned longto have a minimum size of 32 bits (4 bytes). Hence the returned pointer value must be a multiple of 4, and the lower two bits (representing the values 1 and 2) will always be zero.
The C17 standard deprecatesATOMIC_VAR_INITfromstdatomic.h, meaning it still supports it but would rather it not be used. What is the correct non-deprecated way of initializing atomics in C17? Same as non-atomic types: ``` atomic_int foo = 42; ``` Or something new?
C17 makes it ok to initialize atomics using the usual explicit initialization: ``` atomic_int n = 42; ``` C17 literally just dropped the two words "using ATOMIC_VAR_INIT" from the sentence in 7.17.2.1.
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.Closed5 years ago.Improve this question ``` #include <stdio.h> int main() { int i = 0; int *a; do { scanf("%d",&a[i]); i++; } while (a[i-1]!=-1); } ``` This code reads numbers until-1is encountered. The pointerais not initialized but the code still compiles & runs without any error. Why? Can this be a way to initialize an array without declaring its size?
GCC doesn't warn of uninitialized values by default. You need the-Wuninitializedoption: ``` gcc -Wuninitialized your_file.c ``` You should probably use the-Walloption instead to enable this warning alongside lots of other useful warnings. More information on warning optionshere
I am writing a multithreaded application in windows using C. In my application I have to terminate the thread from within the thread. I am not having the handle to the thread, so I cannot use the close handle() function. Can anyone suggest an idea to handle the situation. Both MSDN c++ and WIN32 functions are accepted....Thanks, in advance :-)
In order to terminate the thread you can useExitThread. Edit: As Oliv mentioned in the commentsstd::terminatelikeabortandexitcloses the entire program.
I was wondering, how can I add up the divisors displayed once I run my code? ``` #include <stdio.h> #include <stdlib.h> int main() { int n, i; scanf("%d", &n); for(i = 1; i < n; i++) { if(n % i == 0) { printf("%d\n", i); } } return 0; } ``` If I were to enter, say, 25, it would print out 1, 5. I was wondering how to add up the two numbers 1 and 5?
Could it be as simple as this? You will want to use a simple increment operator (+=), to increment the variablesum. ``` int main(void) { int n, i, sum = 0; if( scanf("%d", &n)!= 1){ fprintf(stderr,"Error in input\n"); exit(EXIT_FAILURE); } for(i = 1; i < n; i++) { if(n % i == 0) { printf("%d\n", i); sum += i; } } printf("Sum of divisors: %d\n", sum); return 0; } ```
I have a Linux-specific source file that includes a few Linux-specific headers, such asdirent.h. I added this source file to my cross-platform (Linux) project in VS2017, but IntelliSense is throwing flags at me that it cannot find these headers. Is there a specific directory I should be adding to my include list to find them? If not, how do I handle platform specific headers in a cross-platform project? Edit for clarification: I'm specifically trying to assume that it is a Linux header, but I am editing on a Windows machine using the cross-platform VS feature.
I found the answer in the MS blogs. The short answer is that the includes are never present, and need to be copied over from the Linux machine into a local folder to add. https://blogs.msdn.microsoft.com/vcblog/2016/03/30/visual-c-for-linux-development/#includes
This question already has answers here:Why do linked lists use pointers instead of storing nodes inside of nodes(11 answers)Closed5 years ago. I could not grasp the reason we create pointers of nodes instead of node structures when we try to implement linked lists as here: ``` typedef struct node { int val; struct node * next; } node_t; ``` and ``` node_t * head = NULL; head = malloc(sizeof(node_t)); if (head == NULL) { return 1; } head->val = 1; head->next = NULL; ``` here, why do we declare nodes such asheadas pointers of structures instead of direct structures>
Havingheadas a pointer allows for things like empty lists (head == NULL) or a simple way to delete elements at the front of the list, by moving theheadpointer to another (e.g. second) element in the list. Havingheadas a structure, these operations would be impossible or at least much less efficient to implement.
I was looking at sequence point operations. In the code below, the value of i is printed as 1. But I get the warning message that "Operation on i is undefined". I was thinking that though & operator is not a sequence point, but function call printf is considered as a sequence point and hence i is completely evaluated during %d. But Why the operation is undefined? ``` int i = 0; if((i++) & printf("i = %d\n",i)) { // Something } else { // some code here } ```
A function call is a sequence point, but arguments to the function are evaluated before the function call. Soi++andias an argument to printf are unsequenced.
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.Closed5 years ago.Improve this question I need to extract hex numbers fromchar*which length = 16, for ex.fa45cb15and I need to get the value of each bit How to do it in correct way? Now I'm just printingprintf("%x");
Not very hard, all you need is a loop and a cast to make sure your numbers are unsigned ``` for (int i = 0; i < 16; ++i) printf("%02X", (unsigned char)data[i]); ```
Note: I'm still pretty new to C. I'm trying to write a little C utility that takes in a hex color from stdin or an argument and a flag to dictate if the color should be darkened or lightened, and by what percentage. How should I go about doing the lightening or darkening? Thanks!
To do it right, first decode the hex values into three integers,r,g, andb, convert to doubles, then convert those doubles into a different 3D colorspace in which lightness or intensity is its own element. Either HSL/HSV or YIQ/YUV (Google "color space"). Then change the intensity, and convert back. That will ensure that you get a darker version of the same hue with the same saturation (more or less--at least it will be much better than simply tweaking the RGB values). Google "RGB to HSL" and such to find code for doing the conversions. For example: https://gist.github.com/mjackson/5311256
This question already has answers here:Why do linked lists use pointers instead of storing nodes inside of nodes(11 answers)Closed5 years ago. I could not grasp the reason we create pointers of nodes instead of node structures when we try to implement linked lists as here: ``` typedef struct node { int val; struct node * next; } node_t; ``` and ``` node_t * head = NULL; head = malloc(sizeof(node_t)); if (head == NULL) { return 1; } head->val = 1; head->next = NULL; ``` here, why do we declare nodes such asheadas pointers of structures instead of direct structures>
Havingheadas a pointer allows for things like empty lists (head == NULL) or a simple way to delete elements at the front of the list, by moving theheadpointer to another (e.g. second) element in the list. Havingheadas a structure, these operations would be impossible or at least much less efficient to implement.
I was looking at sequence point operations. In the code below, the value of i is printed as 1. But I get the warning message that "Operation on i is undefined". I was thinking that though & operator is not a sequence point, but function call printf is considered as a sequence point and hence i is completely evaluated during %d. But Why the operation is undefined? ``` int i = 0; if((i++) & printf("i = %d\n",i)) { // Something } else { // some code here } ```
A function call is a sequence point, but arguments to the function are evaluated before the function call. Soi++andias an argument to printf are unsequenced.
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.Closed5 years ago.Improve this question I need to extract hex numbers fromchar*which length = 16, for ex.fa45cb15and I need to get the value of each bit How to do it in correct way? Now I'm just printingprintf("%x");
Not very hard, all you need is a loop and a cast to make sure your numbers are unsigned ``` for (int i = 0; i < 16; ++i) printf("%02X", (unsigned char)data[i]); ```
Note: I'm still pretty new to C. I'm trying to write a little C utility that takes in a hex color from stdin or an argument and a flag to dictate if the color should be darkened or lightened, and by what percentage. How should I go about doing the lightening or darkening? Thanks!
To do it right, first decode the hex values into three integers,r,g, andb, convert to doubles, then convert those doubles into a different 3D colorspace in which lightness or intensity is its own element. Either HSL/HSV or YIQ/YUV (Google "color space"). Then change the intensity, and convert back. That will ensure that you get a darker version of the same hue with the same saturation (more or less--at least it will be much better than simply tweaking the RGB values). Google "RGB to HSL" and such to find code for doing the conversions. For example: https://gist.github.com/mjackson/5311256
I was looking at sequence point operations. In the code below, the value of i is printed as 1. But I get the warning message that "Operation on i is undefined". I was thinking that though & operator is not a sequence point, but function call printf is considered as a sequence point and hence i is completely evaluated during %d. But Why the operation is undefined? ``` int i = 0; if((i++) & printf("i = %d\n",i)) { // Something } else { // some code here } ```
A function call is a sequence point, but arguments to the function are evaluated before the function call. Soi++andias an argument to printf are unsequenced.
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.Closed5 years ago.Improve this question I need to extract hex numbers fromchar*which length = 16, for ex.fa45cb15and I need to get the value of each bit How to do it in correct way? Now I'm just printingprintf("%x");
Not very hard, all you need is a loop and a cast to make sure your numbers are unsigned ``` for (int i = 0; i < 16; ++i) printf("%02X", (unsigned char)data[i]); ```
Note: I'm still pretty new to C. I'm trying to write a little C utility that takes in a hex color from stdin or an argument and a flag to dictate if the color should be darkened or lightened, and by what percentage. How should I go about doing the lightening or darkening? Thanks!
To do it right, first decode the hex values into three integers,r,g, andb, convert to doubles, then convert those doubles into a different 3D colorspace in which lightness or intensity is its own element. Either HSL/HSV or YIQ/YUV (Google "color space"). Then change the intensity, and convert back. That will ensure that you get a darker version of the same hue with the same saturation (more or less--at least it will be much better than simply tweaking the RGB values). Google "RGB to HSL" and such to find code for doing the conversions. For example: https://gist.github.com/mjackson/5311256
I'm a bit confused with modulo in c. Trying the following examples: ``` double d = 4912; int a; a = (int) d%100; printf ("%d \n", a); ``` Answer is 12. Fine, that's what I'm expecting. Now I try this: ``` double d = 49.12; d = d*100; int a; a = (int) d%100; printf ("%d \n", a); ``` Answer: 12. Again what I'm expecting. But now: ``` double d = 49.12; int a; a = (int)(d*100)%100; printf ("%d \n", a); ``` Answer: 11! That's definitly not what I expected. But I have no idea why. oO
doubleas a 64-bit floating point number cannot represent every number coded as text. In can encode exactly about 264different numbers.49.12is not one of them. Given thebinarynature of mostdouble, the closestdouble dvalue is about49.119999999999997. The result of(int)(d*100)%100is then simply 11. On another platform,the result may have been 12.
is it possible to partially update the reported properties from the device side? So far I only saw articles talking about partially updating the desired properties, like this one:https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-device-twins. If this is possible, is this doable with the azure-iot-hub-c-sdk? Thanks
Yes, it is doable to update the desired properties with azure-iot-hub-c-sdk. You can refer to the sampleiothub_client_sample_device_twin. If you run the sample after modified theconnectionString, you will get the partial changes from the Azure portal, as following:
is it possible to partially update the reported properties from the device side? So far I only saw articles talking about partially updating the desired properties, like this one:https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-device-twins. If this is possible, is this doable with the azure-iot-hub-c-sdk? Thanks
Yes, it is doable to update the desired properties with azure-iot-hub-c-sdk. You can refer to the sampleiothub_client_sample_device_twin. If you run the sample after modified theconnectionString, you will get the partial changes from the Azure portal, as following:
Below is the code I have so far. It is giving segmentation fault after a couple of iterations. Can anyone help me to figure out the problem? ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *str; // 1GB = 1073741824 bytes char *temp; long long int i; str = (char *)malloc(1073741824); strcpy(str,"a"); for(i = 1; i <= 73741824;i = i*2) { strcat(str,str); } free(str); } ```
You are callingstrcat()with the same string as both arguments, which is an error. Seethe manual page: The strings may not overlap, and the dest string must have enough space for the result.
I would like to check if the current operating system is linux or android during runtime with native C. Is it possible? Because I have to execute different code depending on the OS.
To ensure program runs on Android you can check environment variables namedANDROID_ROOTandANDROID_DATA. Usually they are present and refer to/systemand/datafolders. C:You can usegetenvfunction fromstdlib.h: ``` getenv("ANDROID_ROOT"); getenv("ANDROID_DATA"); ``` CLI: ``` $ env | grep ANDROID_ ```
Probably a really simple problem but I don't get it. I'm trying to print the value ofTUNSETIFFfrom linux/if_tun.h ``` #include <linux/if_tun.h> #include <stdio.h> int main() { printf("%d", TUNSETIFF); return 0; } ``` When I try to compile this code I get an error: ``` In file included from test.c:1:0: test.c: In function `main`: test.c:7:24: error: expected expression before `int` printf("%d", TUNSETIFF); ^ ``` I don't understand what is wrong with my code, isn't that how you print an integer? If I just doprintf("Hello")it works just fine..
You need to#include <sys/ioctl.h>. Otherwise the definition ofTUNSETIFFis not expanded fully into an integer.
cppcheck detects a resorce leak in the code below. I think it is a fals negative. If not, can you explaint to me why it is a resource leak? ``` bool fileExists(const char* filename) { FILE* fp = fopen(filename, "r"); bool result = (fp != NULL); if (result) fclose(fp); return result; // <-- (cppcheck error) Resource leak: fp } ```
Yes, it is false negative, cppcheck wrongly detects onetheoretically possiblebranch whenfpis not closed I'd personally rewrite this code as: ``` FILE* fp = fopen(filename, "r"); if (fp != NULL) { fclose(fp); return true; } return false; ```
Im learning for my upcoming exam and i wanted to ask if an Array counts blanks. e.g in the Image below: does he count like the first row?
It's an array of characters yes it counts the spaces, it should be in the 9 position the first blank/space and the first (i) should be in 10 position and etc and in the end of the array should be a /0.. p.s: null is a character also, that gets on the end of the array
cppcheck detects a resorce leak in the code below. I think it is a fals negative. If not, can you explaint to me why it is a resource leak? ``` bool fileExists(const char* filename) { FILE* fp = fopen(filename, "r"); bool result = (fp != NULL); if (result) fclose(fp); return result; // <-- (cppcheck error) Resource leak: fp } ```
Yes, it is false negative, cppcheck wrongly detects onetheoretically possiblebranch whenfpis not closed I'd personally rewrite this code as: ``` FILE* fp = fopen(filename, "r"); if (fp != NULL) { fclose(fp); return true; } return false; ```
Im learning for my upcoming exam and i wanted to ask if an Array counts blanks. e.g in the Image below: does he count like the first row?
It's an array of characters yes it counts the spaces, it should be in the 9 position the first blank/space and the first (i) should be in 10 position and etc and in the end of the array should be a /0.. p.s: null is a character also, that gets on the end of the array
Im learning for my upcoming exam and i wanted to ask if an Array counts blanks. e.g in the Image below: does he count like the first row?
It's an array of characters yes it counts the spaces, it should be in the 9 position the first blank/space and the first (i) should be in 10 position and etc and in the end of the array should be a /0.. p.s: null is a character also, that gets on the end of the array
Strange compiler behaviour? Is it a bug. With GCC on linux ``` #include <stdio.h> #define NSIM 1 int main() { printf("%d\n\n",(2 +(NSIM==1)?0:99)); return 0; } ``` gave the output 0 (NSIM=1) but ``` #include <stdio.h> #define NSIM 1 int main() { printf("%d\n\n",(2 +((NSIM==1)?0:99))); return 0; } ``` gave the output 2 Is this a bug in the compiler - to my mind they should both give 2
This is not a bug. The expression ``` 2 + (NSIM == 1) ? 0 : 99 ``` is grouped as ``` (2 + (NSIM == 1)) ? 0 : 99 ``` due to operator precedence. (The ternary conditional operator appears pretty low on the operator precedence table.) So this evaluates to0, irrespective of the value ofNSIM.
MISRA enforces the use of theUsuffix for unsigned integer constants ``` uint32_t the_answer = 0x42U; ``` I feel theUis a bit boilerplate because the line is very understandable without it. So I am wondering how much this rule is important and ifunsigned int x = 1is truely a bad example of implicit integer promotion.
You are correct, the U in this specific example is superfluous as per an exception to Rule 10.3: "A non-negative integer constant expression of essentially signed type may be assigned to an object of essentially unsigned type if its value can be represented in that type." Therefore, you are fine to assign a signed integer less than 7FFF FFFF to this unsigned 32-bit object.
While reading a file into char *, where should the null be added and why? Option1 or option2, both seem to compile. ``` char* load_file(char const* path) { char* buffer = 0; long length; FILE * f = fopen (path, "rb"); if (f) { fseek (f, 0, SEEK_END); length = ftell (f); fseek (f, 0, SEEK_SET); buffer = (char*)malloc ((length+1)*sizeof(char)); if (buffer) { fread (buffer, sizeof(char), length, f); } fclose (f); } buffer[length] = '\0'; //option1 buffer[length+1] = '\0'; //Option2 return buffer; } ```
With yourmalloccall you allocate an "array" oflength + 1characters, with indexes from0tolength(inclusive). Therefore the correct option can only be "option1".
I am trying to use SQS on aws (on a linux box) using generic C. Not using any sdk (not that there is one for C). I can not find an example I can relate to. Sorry, I don't relate to these newfangled languages. I am proficient in Cobol, fortran, pascal and C. Not python, c++, c# or java. There are "steps" on amazon site, but honestly they expect proficiency on aws and an object oriented language. I just want to create my own https get command for accessing SQS/SNS, can anyone provide a 'C' snipet that creates a complete url with the version 4 signature? Or point me in the correct direction?
Have a look athttps://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html If you're proficient with any programming language, you should be able to understand all of that code. It's just string operations and some hashing for which you'll have to use another library. There's also lots of comments to help you with the details.
I am trying to set all bits in a char to true. ``` char foo = 00000000; foo |= 11111111; for (int i = 0; i < 8; i++) { //prints out bitwise printf("%d", !!((foo << i) & 0x80)); } ``` When foo is all 0, I get 11000111. When foo == 00000110, it prints 11001111; What is going wrong here?
The number11111111is a decimal constant, not binary. Although you can use octal or hexadecimal constants, there are no binary constants (at least not standard ones). If you want a number with all bits set, just apply the bitwise complement operator~to 0: ``` unsigned char foo = ~0u; ```
I have JNI method that operates withconst struct tm myTimeInfo. At the end, I would like to return result to Java. However, I cannot directly returnDate. So far I convertstruct tmtojstringand in java back toDate, which seems odd. Is there a way how to return directlyDatefilled withstruct tm? My current solution is something like: ``` JNIEXPORT jstring JNICALL package_getTimeLineEndUTC(JNIEnv *env, jobject thiz) { const struct tm timeInfo = generateTime(); return env->NewStringUTF(asctime(&timeInfo)); } ```
Instead of returning a string, you can return along, i.e milliseconds since the epoch: ``` const struct tm timeInfo = generateTime(); return mktime(&timeInfo) * 1000; ``` Then useDate(long date)on the java side.
I'm trying to add macro to file via cmake, and when I do ``` set_source_files_properties(path_to_file PROPERTIES COMPILE_FLAGS "-Dfoo=bar" ) ``` everything is ok, macro is defined, but ``` set_source_files_properties(path_to_file PROPERTIES COMPILE_FLAGS "-Dfoo(x)=bar(x)" ) ``` I'm getting an error "/bin/sh: 1: Syntax error: "(" unexpected". Is it possible to add macro with variable via cmake file?
You should protect the commandline with quotes: ``` '-Dfoo(x)=bar(x)' ```
I am trying to use SQS on aws (on a linux box) using generic C. Not using any sdk (not that there is one for C). I can not find an example I can relate to. Sorry, I don't relate to these newfangled languages. I am proficient in Cobol, fortran, pascal and C. Not python, c++, c# or java. There are "steps" on amazon site, but honestly they expect proficiency on aws and an object oriented language. I just want to create my own https get command for accessing SQS/SNS, can anyone provide a 'C' snipet that creates a complete url with the version 4 signature? Or point me in the correct direction?
Have a look athttps://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html If you're proficient with any programming language, you should be able to understand all of that code. It's just string operations and some hashing for which you'll have to use another library. There's also lots of comments to help you with the details.
I am trying to set all bits in a char to true. ``` char foo = 00000000; foo |= 11111111; for (int i = 0; i < 8; i++) { //prints out bitwise printf("%d", !!((foo << i) & 0x80)); } ``` When foo is all 0, I get 11000111. When foo == 00000110, it prints 11001111; What is going wrong here?
The number11111111is a decimal constant, not binary. Although you can use octal or hexadecimal constants, there are no binary constants (at least not standard ones). If you want a number with all bits set, just apply the bitwise complement operator~to 0: ``` unsigned char foo = ~0u; ```
I have JNI method that operates withconst struct tm myTimeInfo. At the end, I would like to return result to Java. However, I cannot directly returnDate. So far I convertstruct tmtojstringand in java back toDate, which seems odd. Is there a way how to return directlyDatefilled withstruct tm? My current solution is something like: ``` JNIEXPORT jstring JNICALL package_getTimeLineEndUTC(JNIEnv *env, jobject thiz) { const struct tm timeInfo = generateTime(); return env->NewStringUTF(asctime(&timeInfo)); } ```
Instead of returning a string, you can return along, i.e milliseconds since the epoch: ``` const struct tm timeInfo = generateTime(); return mktime(&timeInfo) * 1000; ``` Then useDate(long date)on the java side.
I'm trying to add macro to file via cmake, and when I do ``` set_source_files_properties(path_to_file PROPERTIES COMPILE_FLAGS "-Dfoo=bar" ) ``` everything is ok, macro is defined, but ``` set_source_files_properties(path_to_file PROPERTIES COMPILE_FLAGS "-Dfoo(x)=bar(x)" ) ``` I'm getting an error "/bin/sh: 1: Syntax error: "(" unexpected". Is it possible to add macro with variable via cmake file?
You should protect the commandline with quotes: ``` '-Dfoo(x)=bar(x)' ```
I am writing some go code that exports a function like that: ``` package main import "C" //export returnString func returnString() string { // gostring := "hello world" return gostring } func main() {} ``` I build the.soand the header file by using go build-buildmode=c-shared, but when I callreturnString()in my C code, I getpanic: runtime error: cgo result has Go pointer Is there a way to to this in go 1.9?
You need to convert your go string to*C.char.C.Cstringis utility function for that. ``` package main import "C" //export returnString func returnString() *C.char { gostring := "hello world" return C.CString(gostring) } func main() {} ```
Is there a limit in nested calls of functions according to C99? Example: ``` result = fn1( fn2( fn3( ... fnN(parN1, parN2) ... ), par2), par1); ``` NOTE: this code is definitely not a good practice because hard to manage; however, this code is generated automatically from a model, so manageability issues does not apply.
There is not directly a limitation, but a compiler is only required to allow some minimum limits for various categories: From theC11 standard: 5.2.4.1 Translation limits 1 The implementation shall be able to translate and execute at least one program that contains at least one instance of every one of the following limits:18)...63 nesting levels of parenthesized expressions within a full expression...4095 characters in a logical source line18)Implementations should avoid imposing fixed translation limits whenever possible
I have the following c code: ``` int foo = 0; printf("output1: %08x\n", (~0x0) << (~0)); printf("output2: %08x", (~0x0) << (~foo)); ``` which prints out: ``` output1: ffffffff output2: 80000000 ``` Why does shifting by the same number produce a different result?
Basically your snippet is an orgy in undefined behavior. 0x0literals as well as variables of typeintaresigned, meaning they can get negative values.~0is always a negative value.Left-shifting a signed int with negative value invokes undefined behavior. (6.5.7/4)Attempting to shift more positions than there's room in the left operand invokes undefined behavior. (6.5.7/3)Attempting to shift a negative amount of bits invokes undefined behavior. (6.5.7/3) Therefore anything can happen in this program, including the whole thing crashing and burning. As a rule of thumb,neveruse signed variables together with bitwise operators.
GCC compiler provides a set ofbuiltinsto test some processor features, like availability of certain instruction sets. But, according tothisthread we also may know certain cpu features may be not enabled by OS. So the question is: do__builtin_cpu_supportsintrinsics also check if OS has enabled certain processor feature?
No. I disabled AVX on my Skylake system by addingnoxsaveto the Linux kernel boot options. When I docat /proc/cpuinfoAVX (and AVX2) no longer appear and when I run code with AVX instructions it crashes. This tells me that AVX has been disabled by the OS. However, when I compile and run the following code ``` #include <stdio.h> int main(void) { __builtin_cpu_init(); printf("%d\n", __builtin_cpu_supports ("sse")); printf("%d\n", __builtin_cpu_supports ("avx")); } ``` it returns 8 and 512. This means that__builtin_cpu_supportsdoes not check to see if AVX was disabled by the OS.
Can someone help me understand why I would be getting "warning: cast to pointer from integer of different size" for the following two lines of code? so I have a pointer to a string (char *string) and a double pointer (char **final) that needs to the store the address of the last char in string... I thought the following lines of code would work but I keep getting the error... How do I fix it? ``` char last = *string; *final = (char *)last; ```
``` (char *)last ``` lastis of typechar. Casting it to a pointer means the numeric code of the character stored inlastwill be interpreted as an address. So iflastcontainsA, then this will cause the value65to be interpreted as an address. (Assuming ASCII). The compiler is smart and indicates that this is probably not the behavior you intend.
I do not know how to get around this error. I must not be assigning the same type. Keep receiving an '(strict) incompatible pointers in =' ``` #define POOLSZ 53 typedef struct{ int eventnr; int eventfq; struct olnode *next; }olnode; olnode pool[POOLSZ]; olnode *avail void initpool() { int i; for(i = 0; i < POOLSZ-1; i++) pool[i].next = &pool[i+1]; /*This is the error line */ pool[i].next = NULL; avail = pool; } ```
This line makes a pointer tostruct olnode: ``` struct olnode *next; ``` But you don't define such struct. You only have an anonymous struct,typedefed toolnode. Fix: ``` typedef struct olnode {...} olnode; ```
I am currently writing a program in C. I have a variableideclared in my program. I have initialized it as such: ``` unsigned char i = 0x00; ``` Next, I have a while loop, and inside that while loop, I'm increasing theunsigned charby 16 and displaying it to seven digits (such as0000080). Well, This runs perfectly fine for the first 16 values, but whenever theunsigned chargets to00000f0and gets incremented again, it goes back to0000000. Why is this and how can I alter my code to fix this? Thanks in advance.
Anunsigned char, assuming 8 bit to a byte, has a maximum value of 255 (0xff). Any arithmetic operation that exceeds that is truncated modulo 256. If you want to support larger values, useunsigned intinstead.
I understand what both do, but I have a question about the behavior of pthread_join. I noticed this pattern is pretty common in C (mind the pseudocode): ``` for i in some range: thread[i] = pthread_create (...) for i in some range: pthread_join(&thread[i]...) ``` Why can't it happen at the same time? e.g: ``` for i in some range: thread[i] = pthread_create (...) pthread_join(&thread[i]...) ```
because if you do that, all threads run sequentially, sincepthread_joinwaits for thread termination. So you're losing the benefit of running the threads at the same time, simply.
For example: AAbbCC should be AACCbb Everything works on the page, but for some reason, when the function swaps the values, the value ofstrchanges (at the end of the running, the program prints the value of AAC) this is my code: ``` void capital_to_Low(char *str) { int i = 0, j = (strlen(str)) -1; while (i < j) { if (str[i] >= 'a' && str[i] <= 'z') { swap(&str[i], &str[j--]); } else i++; } puts(str); } void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } ```
Change void swap(int *a, int *b) to void swap(char *a, char *b) , because you are referring to the address of the character not integer
``` int main(void) { char c='012'; printf("%c",c); return 0; } ``` Why is 2 getting printed?
'012'is a multicharacter constant, which is aninttype, but with animplementation definedvalue. (For the avoidance of doubt,'0'is aninttype in C too.) Ifcharisunsignedthen you'll get the least significantCHAR_BITbits of thatintas the final result. Ifcharissigned, then then behaviour of the conversion of thatintto thecharwill be implementation defined. In your case, it appears that the constant value is'0' * 256 * 256 + '1' * 256 + '2', and the conversion of this tocharis effectively taking the result modulo 256.
My audio DSP algorithm processes input sound file (45 seconds of 16 kHz audio). After simulation is done,gprofprofiler tells me: Cycles: total = 6846310893 Is this enough information to calculate this algorithm's "MIPS"? Let's say my target DSP processor is "100 MIPS".How much will this algo take out of those 100? Edit:Processor executes 1 instruction per cycle.Processor runs at 600 MHz.
OK...6846310893cycles per45seconds is:152.14"MIPS", meaning my 600 MHz processor can (nearly) execute 4 of these in real-time.
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed5 years ago.Improve this question Why does it output "Segmentation fault(core dumped) When I run the following code it says Segment fault(core dumped) ``` #include <stdio.h> void swap(int *, int *); int main() { int x = 5, y = 10; swap(x, y); printf("%i\n %i\n", x, y); } void swap(int *a, int *b) { int s; s = *a; *a = *b; *b = s; } ```
The problem is in lineswap(x, y); You are passing the values and not the addresses. You should have got compiler warnings. Useswap(&x, &y);
This question already has an answer here:Undefined reference to pow( ) in C, despite including math.h [duplicate](1 answer)Closed5 years ago. I have include math.h in my .yacc file and when I am trying to use the pow function in this part of the code it is giving me the above mentioned error ``` expression2:expression2 POWER_OP expression3 {/*keeping POWER_OP at highest precedence*/ $$ = pow($1,$3);} ``` and when I tried to put 2,3 or any constant value in the same part of code it is working fine
Try adding -lm when compiling the files. example: gcc c.tab.c lex.yy.cc -lm
I have got a small async udp server -RiDE. And i can't build it with CMake. When i trying to i get errors: ``` undefined reference to 'uv_default_loop' undefined reference to 'uv_udp_init' ...(other libuv functions) ``` But when i build it with command like this: ``` gcc -std=c11 RiDE_server.h RiDE_server.cpp main.cpp -o main.x -Wall -luv ``` everything is ok. I think that the problem is in src/CMakeLists.txt file, but i can't understand how to fix it. Path to libuv headers on my machine - /usr/include. Path to libuv shared libs - /usr/lib/x86-64-linux-gnu.
Runmake VERBOSE=1. What linker command does it run? It must be missing-luv. To fix that, add something like this to yourCMakeLists.txt: ``` target_link_libraries(foo uv) ```
How can I define the type of an enum to beuint8instead ofint? ``` typedef enum { R_DIRECTION_LEFT = 1, R_DIRECTION_RIGHT = 2, R_DIRECTION_TOP = 4, R_DIRECTION_BOTTOM = 8 } R_Direction; ```
No you can't. From standard §6.4.4.3C11 standard N1570 An identifier declared as an enumeration constant has type int.
Can anyone tell me what's wrong with my dequeue function? It's always keeping the first value over and over, but otherwise seems to be working good. Sample output provided. ``` NODE *dequeue(NODE **queue) { if (*queue == NULL) { return; } NODE *pTemp = *queue; printf("[%d %d] -> ", pTemp->pid, pTemp->priority); *queue = (*queue)->next; return pTemp; } ``` Function is being called as such: ``` NODE *someQueue; //code to add values here for (i = 0; i < numberOfQueueItems; i++) { printf("\nDequeue time.\n"); printList("readyQ", someQueue); dequeue(someQueue); } ```
You are not callingdequeuecorrectly. It expects a double pointer to NODE but you pass a pointer to NODE Change ``` dequeue(someQueue); ``` to ``` dequeue(&someQueue); ```
I have a program that uses dynamic allocation for a uint8_t array; can I safely assume that its length will always be one byte?
Ifuint8_texists, thensizeof(uint8_t)must be 1.uint8_tisrequiredto have width exactly 8 and no padding bits, andCHAR_BITis required to be at least 8. Ifuint8_texists, it can't have more than one char's worth of bits without violating these requirements.
Is there a good place to lookup failure codes while debugging c programs? For example: I am getting "Abort trap: 6" while running one of my programs and I don't know what that means. Edit:This was on a mac, and I'm looking for a reference to lookup any error code that comes up, not just the example I gave.
I misunderstood the error message. SIGABRT is defined as 6, 6 does not give any information about what caused abort() to be called. The signal codes and brief descriptions are defined in <signal.h> which is located at /usr/include/sys/signal.h on my machine. More detailed descriptions can be found athttps://en.wikipedia.org/wiki/Signal_(IPC)
How can I define the type of an enum to beuint8instead ofint? ``` typedef enum { R_DIRECTION_LEFT = 1, R_DIRECTION_RIGHT = 2, R_DIRECTION_TOP = 4, R_DIRECTION_BOTTOM = 8 } R_Direction; ```
No you can't. From standard §6.4.4.3C11 standard N1570 An identifier declared as an enumeration constant has type int.
I'm writing a user define function for Vertica and don't know how to initialize a Vstring of Vertica from a C string (char *) . Thanks for any suggestion?
Following to Vertica documentation: You cannot create instances ofVStringorVNumericyourself. You can manipulate the values of existing objects of these classes that HP Vertica passes to your UDx, and extract values from them. However, only HP Vertica can instantiate these classes.
This is the code, it reads from a file and then it prints what is written in that file. I don't know why but the last string of the file is readed twice. Code ``` FILE* src = fopen(name_email_src, "r"); if (src == NULL) { printf("ERROR source file not found"); } while(fgets(buff_src, sizeof(buff_src), src) != NULL) { fputs(buff_src, stdout); } fclose(src); printf("%s", buff_src); ``` This is the output: ``` Date: Tue, 07 Feb 2017 21:32:46 +0100 (CET) From: Rental <[email protected]> To: me <[email protected]> Message-ID: message2 Subject: Paga el alquiler ya. Dear customer, you are late in your payment, please pay or LEAVE! Sincerely yours, House rental House rental ``` What can I do to solve this problem? Thank you.
printf("%s", buff_src);is printing the last line.
I use this code: ``` HANDLE handle = CreateFile( //Options// ); FILETIME time; time.dwLowDateTime = time.dwHighDateTime = 0xFF; SetFileTime(handle, &time, &time, &time); ``` When I use0xFFvalue in FILETIME struct withSetFileTime()File Explorer shows blank date in Details Mode (Ctrl+Shift+6). But if I open file properties it shows date as 02 Jan 1601. Can you explain why this date shows with0xFFvalue?
The date created viatime.dwLowDateTime = time.dwHighDateTime = 0xFF;will be 0xFF000000FF * 100 ns later since January 1, 1601 (UTC). This is about 30.4 hours, so the date may be 02 Jan 1601 (it may depend on the local timezone). (reference:FILETIME structure (Windows))
My Code: ``` #include <stdio.h> #include <stdlib.h> typedef struct{ char name[50]; char phone[11]; }contato; int main(){ contato c; int i = 0; FILE *fp = fopen("lista_contato.txt", "w"); printf("Nome: "); fflush(stdin); fgets(c.name, 50, stdin); printf("Telefone: "); fflush(stdin); fgets(c.phone, 11, stdin); fwrite(&c, 1, sizeof(contato), fp); fclose(fp); return 0; } ``` My Input for name: "Name Surname" My Input for Phone: "1234" My Output on file: "Name Surname ¿@ °@ Vw ( x ¸þa Phone " Whats Happening With this code, and how i can solve it?
You need to initialize c. In your current code, it will just contain random data. Add this line before you insert any data into c: ``` memset(&c, 0, sizeof(contato)); ```
I have been building an HTTP Server (in the C programming language), and I'm wondering what would handle a POST request sent by a client. That is, if a client sends me a POST request to a PHP page, then how would I pass the data sent by the client to the PHP page? Feel free to ask for clarification.
Something needs to parse, compile and execute the PHP page. You're not about to write your own, so your server will need to act as a proxy for the request. Solution 1: Setup a FastCGI PHP daemon. Your web server can then forward the request to PHP using the FastCGI protocol. Solution 2: Setup a web server capable of handling PHP requests. Your web server can then (indirectly) forward the request to PHP using HTTP or HTTPS. This is less work for you, but it begs the question why you're not just using that web server throughout.
I know that C compilers do structure padding by default. I also know that one can disable structure padding, though this is not recommended and even prohibited for some CPU architectures. I was wondering why structure padding is taking place and what are the advantages of it?
What are the advantages of structure padding? Variables put on machine-aligned addresses can be read or written in fewer assembly instructions — usually one. Thus, the compiler uses padding to optimize its access.
I'm trying to port the following C code to Go: ``` if (x == 0 || x-- == 0) { // Stuff } ``` This isn't legal in Go because I can't modifyxinside the check clause. What's a good way of representing this in Go without e.g. duplicating the contents of the block?
Ifx--is a typo and should be--x, then I would make the changes toxexplicit: ``` if x == 0 || x == 1 { x = 0 // Stuff } else { x-- } ``` Otherwise, your C code has a bug. Ifx == 0is false, thenx-- == 0will also be false because you're using the post-increment operator. Therefore, the code would be equivalent to: ``` if (x == 0) { // Stuff } else { x--; } ```
I have this two arrays and I want to use them in each case for printing different array on my LCD. Here is an example ``` char *ChangeSituatuion; char *MainMenu[4]={"Category 1","Category 2","Category 3","Category 4"}; char *SubMenu[2]={"Category 3","Category 4"}; //case 1 *ChangeSituatuion=MainMenu; //case 2 *ChangeSituatuion=SubMenu; LCDPutStr(ChangeSituatuion[0],1); ``` With this example above i'm taking no meaning letters on my Lcd
You have an indirection level problem. You need a pointer to one array of pointers. Your code should be: ``` char **ChangeSituatuion; char *MainMenu[4]={"Category 1","Category 2","Category 3","Category 4"}; char *SubMenu[2]={"Category 3","Category 4"}; //case 1 ChangeSituatuion=MainMenu; //case 2 ChangeSituatuion=SubMenu; LCDPutStr(ChangeSituatuion[0],1); ```
My Code: ``` #include <stdio.h> #include <stdlib.h> typedef struct{ char name[50]; char phone[11]; }contato; int main(){ contato c; int i = 0; FILE *fp = fopen("lista_contato.txt", "w"); printf("Nome: "); fflush(stdin); fgets(c.name, 50, stdin); printf("Telefone: "); fflush(stdin); fgets(c.phone, 11, stdin); fwrite(&c, 1, sizeof(contato), fp); fclose(fp); return 0; } ``` My Input for name: "Name Surname" My Input for Phone: "1234" My Output on file: "Name Surname ¿@ °@ Vw ( x ¸þa Phone " Whats Happening With this code, and how i can solve it?
You need to initialize c. In your current code, it will just contain random data. Add this line before you insert any data into c: ``` memset(&c, 0, sizeof(contato)); ```
I have been building an HTTP Server (in the C programming language), and I'm wondering what would handle a POST request sent by a client. That is, if a client sends me a POST request to a PHP page, then how would I pass the data sent by the client to the PHP page? Feel free to ask for clarification.
Something needs to parse, compile and execute the PHP page. You're not about to write your own, so your server will need to act as a proxy for the request. Solution 1: Setup a FastCGI PHP daemon. Your web server can then forward the request to PHP using the FastCGI protocol. Solution 2: Setup a web server capable of handling PHP requests. Your web server can then (indirectly) forward the request to PHP using HTTP or HTTPS. This is less work for you, but it begs the question why you're not just using that web server throughout.