question
stringlengths
25
894
answer
stringlengths
4
863
This question already has answers here:What is special about numbers starting with zero?(4 answers)Closed4 years ago. Can you explain it? Why it given 56 value as output? ``` #include <stdio.h> #include <conio.h> void main() { int x = 070; printf("%d", x); getch(); } ```
Any integer literal (integer constant) starting with0is anoctal representation. QuotingC11, chapter §6.4.4.1,Integer constants octal-constant:0octal-constantoctal-digit and octal-digit: one of0 1 2 3 4 5 6 7 and, as per chapter §7.21.6.1, for%dformat specifier withprintf(), (emphasis mine) d,iTheintargument is converted to signeddecimal[...] Thereby,octal 70 == decimal 56.
When should I use locks using freertos on something like cortex-m3? It seems to be clear using multicore systems but what about single core? For example I have two tasks. In first I increment variable namedcounter. Second task saves current value of that variable when some event occurs. Should I use locks here? May first task corrupt value which second task is saving?
Yes, you should use locks to protect access to the shared resource. You can't be sure that the sequence generated by the compiler to read the shared variable is atomic, so it might be unsafe. If you want to be a bit more hard-core, possibly gaining performance, you can use various ways to actually ensure that the variablecanbe accessed atomically. See comment.
I runbayesoptwith python bindings. So I have abayesopt.sothat I import from python (a C-extension). When I run it, it core dumps. I want to load this core dump in gdb to see what the issue is. How can I do this? Or get information on it? I tried to load gdb on it, but of course it asks for a binary which I don't have since it's a.so.
You want to run gdb on python, ie:gdb -ex r --args python myscript.py. There's some helpful tips in the python wiki:https://wiki.python.org/moin/DebuggingWithGdb
I have wrote a program inKeilforstm32F4discoverymicrocontrollerand i want to run this C program inMatlab simulink. For this I am trying to use legacy_code function in Matlab. But there are many parameters which I cannot add like SFunctionName,OutputFcnSpec,StartFcnSpec,HeaderFiles,SourceFiles,HostLibFiles,TargetLibFiles,IncPaths,SrcPaths,LibPaths. It would be really helpful if anyone guide me how to find these parameters from keil project/program
Most of those are just obvious as its name suggests, SFunctionName is the function name you want to run by the simulator, HeaderFiles is the header that contains the declaration of the functions etc. There is an example in the docs for providing specifications for legacy functions: http://mathworks.com/help/rtw/examples/lookup-tables.html
How can I scroll my Tree View control to the top? For example we have some tree with a lot of elements: ``` Root element |-- item 1 |-- item 2 |-- ..... |-- item 1567 ``` Tree View control can display only 5 node at the same time. As result, when I press Expand button, it expand all items and shows me only the last 5 nodes. I want so that after expanding it returns view to the first 5 nodes. I tried to use this macros to return caret back to the root, but they take no effect: ``` TreeView_Select(hTreeView, hRoot, TVGN_CARET); TreeView_SelectSetFirstVisible(hTreeView, hRoot); ```
I assume you want to use Windows API (and the macros). You can ensure an item is visible with TreeView_EnsureVisible. If you do not have the root item you can get it with TreeView_GetRoot.
This question already has answers here:Why are floating point numbers inaccurate?(5 answers)Closed7 years ago. i started learningc. Today, while i am working on a program, i found an interesting thing and i made another small program (similar to my issue) to check it. ``` #include<stdio.h> int main(void) { float num1=867.0; float num2=.6921; printf("sum = %.4f \n",num1+num2); return 0; } ``` if i run the above program, i am getting867.6921as the answer. but if i changed the.4%fto%fthe answer is changing tosum = 867.692078. why's the change in the output? Also, is there any way that i can get the answer without using the.4%f?
but if i changed the .4%f to %f the answer is changing to sum = 867.692078 printfrounds the result to that many digits after the floating point you specified, the default is.6. While rounding, it uses the currentfloating point rounding mode, the default is round to the nearest.
Can anyone tell me why this is not working? ``` { int age; int birthYear; char name; printf("Type in your birth year: \n"); scanf("%d", birthYear); age = 2016 - birthYear; printf("You are %d years old.\n", age); } ```
You need to provide the address of yourinttoscanf(): ``` scanf("%d", &birthYear); ``` Additional explanation:If you don't put the&you will pass an unitialized int toscanf(), andscanf()will interpret this as a pointer. The input would then not be stored in the variable (which remains unititalised). Worse: this might end-up in memory corruption.
At some point in my code, I want to read a name for a file that I will be creating (and/or editing) and I've come up with the following: ``` FILE *fp; char filename[15]; fgets(filename, 15, stdin); fp = fopen(filename, "a"); fprintf(fp, "some stuff goes here"); fclose(fp); ``` Even though that does compile and run, it does not create (or open, if I manually create it) the file specified byfilename.What would you suggest?
fgets()stores the newline character read fromstdinafter reading a line of input. You need to strip it manually, e.g. ``` size_t len = strlen(filename); if (len > 0 && filename[len - 1] == '\n') filename[len - 1] = '\0'; ``` You should also check thatfopen()doesn't returnNULL, which it will do if it was unable to open the file. I think usingfprintfwith aNULLfile pointer is undefined behaviour.
I have a pointer*pthat points to astruct S.Shas various fields. Is it possible to assign structureSto the structure pointed to by*pusing only one assignment?OR,do I need to assign the fields, one by one?
This example assigns a struct using a pointer and one statement. ``` int main(void) { struct Foo { char a; int b; double c; } *foo, *bar; foo->b = 10; bar = foo; /* now bar->b=10 as well */ } ```
I am tracking ball with camera in my android phone and send x,y position,radius of ball (x,y position is a pixel in screen android phone ) to my stm32f board via bluetooth. I assemble my phone and stm32f1 kit in a mobile robot. Now i would like my robot move to ball with a fixed distance. Ex: I set distance 10cm. When i move ball forward, my robot forward to ball and always keep 10cm from robot to ball
Here is some pseudo code to get you started: ``` while (TRUE) do get x, y position of ball get x, y position of self calculate distance between self and ball (hint: use Pythagoras) if (distance < 10 cm) move away from ball else if (distance < 10 cm) move towards ball end ``` Now all you have to do is code this up in C.
I recently come across some asymptotic notations and when this question arise which is 50 n logn and by popular rule to get the Big-OH notation is to simply drop the constants and also the lower order terms.But also 50n logn is also BIG-OH of n^5. So why the Big-oh notation is better to consider O(nlogn) rather than O(n^5).. When the input size is changed as 0 to 50 in wolfram the resultant graph is here
You are completely right when you say that50.n.log(n) = O(n^5). There is no problem with that mathematically. We can find a constantC = 1such that for allnabove a certain value10we have ``` |50.n.log(n)| < C.|n^5| ``` See wikipedia for theformal definition There is no doubt about that. If we prefer to say that50.n.log(n) = O(n.log(n))is because we often want to know what is theslowest growing functionwhich dominates the complexity of the algorithm. This is commonly used to compare algorithm complexity.
I'm trying to capture a command line argument and store it as a string however i get a compiler error when I'm trying to convert it to an int as : The error is: initialization makes integer from pointer without a cast [enabled by default] char test = argv[1]; ``` #include <stdio.h> int main(int argc, char** argv) { char test = argv[1]; printf("%c\n", test); return 0; } ```
argv[1]is holding a string and you are trying to store it in character variable what you need is a character pointer ``` char *test = argv[1]; ``` and print it ``` printf("%s\n", test); ```
This piece of code is acting a bit strange to my taste. Please, anyone care to explain why? And how to force '\n' to be interpreted as a special char? ``` beco@raposa:~/tmp/user/foo/bar$ ./interpretastring.x "2nd\nstr" 1st str 2nd\nstr beco@raposa:~/tmp/user/foo/bar$ cat interpretastring.c #include <stdio.h> int main(int argc, char **argv) { char *s="1st\nstr"; printf("%s\n", s); printf("%s\n", argv[1]); return 0; } ``` Bottom line, the intention is that the 2nd string to be printed in two lines, just like the first. This program is a simplification. The real program has problems reading from a file usingfgets(not a S.O. argument toargvlike here), but I think solving here will also solve there.
It seems the shell doesn't recognize and convert the "escape sequence". Use a shell software that supports\nescape sequence.
How to read a binary file with different format of length? for example there are a specific value after 3200 bytes of binary file which formated in 4 bytes, 2 bytes, 2 bytes, and 1 bytes. I tried to read using ``` fread(&buffer, 1, 1, file); ``` then contenate the 4 bytes char in buffer variable - into one char - then convert it to integer but it doesn't work. Only show like if it was one byte length.
First you seek to the position you want to read: ``` fseek(file, 3200, SEEK_SET); ``` Then read the 4 bytes out of the file to the integer you want: ``` int n; fread(&n, 4, 1, file); ``` This works if the endian of the file and your system are the same. Otherwise you convert the number to the endian of you system. E.g. ``` // if the file is big endian: m = be32toh(n); // if the file is little endian: m = le32toh(n); ```
I want to be able to activate a C program anywhere in the terminal without having to type the path to it. So instead of: ``` [some_text]:~ [username]$ ./[insert_c_executable] ``` or: ``` [some_text]:~ [username]$ Documents/Folder1/Folder2/.../[insert_c_executable] ``` That I can do something like this, like the programslsorpwd: ``` [some_text]:~ [username]$ [some_cool_app_name] ``` I've seen a useful answer at the following link:https://askubuntu.com/questions/229589/how-to-make-a-file-e-g-a-sh-script-executable-so-it-can-be-ran-from-termina/229592#229592?newreg=549425fc915d44d19a1e9be81f0172b7 However, neither .bashrc nor bash_profile are available on my home directory (on a Mac with OS X). I can't comment on that question since I don't have enough reputation. Any help would be greatly appreciated!
mv path/to/your/executable_file /usr/local/bin/your_desied_command Example mv composer.phar /usr/local/bin/composer
Why iscap_tdefined as_cap_struct *? What was the reasoning for obfuscating the pointer type and having libcap functions take/returncap_twhen normal libc usage suggests they would take/return a explicit pointer type?
Obfuscated pointers (actually"opaque") are used to force applications to use the documented functions for a library rather than bypass those functions and manipulate its data directly. Doing that lets the developers (of the library) concentrate on making the functions work rather than being distracted by handling data inconsistencies. Further reading: What is an opaque value?Opaque C structs: how should they be declared?Why use an opaque “handle” that requires casting in a public API rather than a typesafe struct pointer?
The memory address of each element of an array are displayed as ``` int first[4], n=4; for(int i=0;i<n;i++){ cout<<"first#" <<i<<" "<<&first[i]<<endl; } ``` I want to ask how to output the address of each element allocated using malloc? ``` int *first = (int *) calloc(n, sizeof(int)); ```
Your code could be used exactly the same way to output themallocallocated memory. Or you could do the the pointer way like below : ``` int *array; array=malloc(4*sizeof(int); for(int i=0;i<4;i++) printf("Address %d : %p\n",i,(array+i)); ``` What difference would you think it makes, if the memory is allocated automatically or manually(as in malloc)?
Is there any way to mock static global variable to use in test function? Or any workaround for that? Below example of such situation: ``` static zsock_t *publish_logs = NULL; int btak_log_message_reactor(zloop_t *loop, zsock_t *reader, void *arg) { struct btak_log_message *message; size_t message_size; if(zsock_recv(reader, "b", &message, &message_size) == 0) { push_log_message(message); if(publish_logs) publish_log_message(message, publish_logs); free(message); } return 0; } ```
We often forget about the linker. We can use a different object file to mock an interface. This mock-obj would contain a different definition of your global. But current unit test frameworks only work on code level... So some build-fu will be needed to add mock objects to the test build.
for example, I have a stringchar str[40]="ABCD(ak47)"then I want to get the part inside the blankets "ak47" from the string What should I do? Here's my code and it doesn't work:( ``` char *result = strstr(str, ")"); int endpos = str - result; int x = 0; for (int i = 5; i < endpos; i++) { copy[x] = str[i]; x++; } ``` By the way, I realise sometimes people usechar *strinstead. In case of using char ptr, How can we getstr[i]?
Try doingresult = strchr(str,'(');Nowresultpoints to(in the stringstrCopy characters fromresult+1until you get)or\0If the read character is)nul terminate the string.
I know that when comparing a char pointer with some char value you need to prefix the pointer with*, but I have found in some code a comparison like: ``` char* c; // ... while (*c != ']' && *c != '\0') // search for some character { c++; } if (c == '\0') { return -1; // error } ``` So, my question is: is this a bug or a special case? Shouldn't there beif (*c == '\0')there?
You are right. ``` c == '\0' ``` checks if the pointer itself equals 0, not the character where the pointer points to.
Sample code to check ``` #include<stdio.h> int main(void) { const int i = 1; printf("Variable i is %s\n", __builtin_constant_p(i) ? "a const variable" : "not a const variable"); return 0; } ``` Output : ``` Variable i is not a const variable ``` Is__builtin_constant_p()not the right API to determine whether a variable is of typeconstor not?
You can use Generic selection (since C11): ``` #include <stdio.h> #define __is_constant_int(X) _Generic((&X), \ const int *: "a const int", \ int *: "a non-const int") int main(void) { const int i = 1; printf("Variable i is %s\n", __is_constant_int(i)); return 0; } ```
The memory address of each element of an array are displayed as ``` int first[4], n=4; for(int i=0;i<n;i++){ cout<<"first#" <<i<<" "<<&first[i]<<endl; } ``` I want to ask how to output the address of each element allocated using malloc? ``` int *first = (int *) calloc(n, sizeof(int)); ```
Your code could be used exactly the same way to output themallocallocated memory. Or you could do the the pointer way like below : ``` int *array; array=malloc(4*sizeof(int); for(int i=0;i<4;i++) printf("Address %d : %p\n",i,(array+i)); ``` What difference would you think it makes, if the memory is allocated automatically or manually(as in malloc)?
Is there any way to mock static global variable to use in test function? Or any workaround for that? Below example of such situation: ``` static zsock_t *publish_logs = NULL; int btak_log_message_reactor(zloop_t *loop, zsock_t *reader, void *arg) { struct btak_log_message *message; size_t message_size; if(zsock_recv(reader, "b", &message, &message_size) == 0) { push_log_message(message); if(publish_logs) publish_log_message(message, publish_logs); free(message); } return 0; } ```
We often forget about the linker. We can use a different object file to mock an interface. This mock-obj would contain a different definition of your global. But current unit test frameworks only work on code level... So some build-fu will be needed to add mock objects to the test build.
for example, I have a stringchar str[40]="ABCD(ak47)"then I want to get the part inside the blankets "ak47" from the string What should I do? Here's my code and it doesn't work:( ``` char *result = strstr(str, ")"); int endpos = str - result; int x = 0; for (int i = 5; i < endpos; i++) { copy[x] = str[i]; x++; } ``` By the way, I realise sometimes people usechar *strinstead. In case of using char ptr, How can we getstr[i]?
Try doingresult = strchr(str,'(');Nowresultpoints to(in the stringstrCopy characters fromresult+1until you get)or\0If the read character is)nul terminate the string.
I know that when comparing a char pointer with some char value you need to prefix the pointer with*, but I have found in some code a comparison like: ``` char* c; // ... while (*c != ']' && *c != '\0') // search for some character { c++; } if (c == '\0') { return -1; // error } ``` So, my question is: is this a bug or a special case? Shouldn't there beif (*c == '\0')there?
You are right. ``` c == '\0' ``` checks if the pointer itself equals 0, not the character where the pointer points to.
Sample code to check ``` #include<stdio.h> int main(void) { const int i = 1; printf("Variable i is %s\n", __builtin_constant_p(i) ? "a const variable" : "not a const variable"); return 0; } ``` Output : ``` Variable i is not a const variable ``` Is__builtin_constant_p()not the right API to determine whether a variable is of typeconstor not?
You can use Generic selection (since C11): ``` #include <stdio.h> #define __is_constant_int(X) _Generic((&X), \ const int *: "a const int", \ int *: "a non-const int") int main(void) { const int i = 1; printf("Variable i is %s\n", __is_constant_int(i)); return 0; } ```
I need to determine x from the expression root(y). "Y" has a range to its separated value with maximum 10^1000. I solved it in the normal way and I saw the right result. But when Y is very large, the program outputs the wrong answer. ``` #include<stdio.h> #include<math.h> int main() { long long int x,y; scanf("%lld",&y); x=sqrt(y); printf("%lld",x); return 0; } ```
Use some bignum library, for exampleGMP
I'm trying to build a structure that is similar to a device tree. Basically, i want to get a driver that is built to work with a device tree, to work the same way without it. I want to build the wrapper and the structure that contain all the information a device tree has, and pass it onto the driver. Anyone has any idea how i can do this or a good place to read abut it? i looked for it but couldn't find anything or any example of something similar on how to do this. Best regards and thank you for your help
It's already been done in the kernel recently and called unified device property API, in particularly it supports same properties come from DeviceTree, ACPI, or built-in in the platform code. More information about API you may find in the sourcesinclude/linux/property.h,drivers/base/property.c. The one of the examples is rfkill_gpio driver, i.e.net/rfkill/rfkill-gpio.c[consumer],arch/arm/mach-tegra/board-paz00.c[provider].
Is this the correct way to generate a random number from (-1, 36)?: ``` #include <stdio.h> #include <stdlib.h> #define RAND_MAX 36 int main() { int num = (-1) + (36 + 1) * (rand()/(RAND_MAX+1)); printf("%d\n", num); return 0; } ```
Do you know how to get random number in the range zero toN(whereNis whatever max number you want in the range)? Then you know how to generate number in the range-NtoNas well. Simply generate a number in the range0to2*Nand subtractN. Update: To generate a number in the range-1to36, then you should generate from0to37and subtract1. The principle is the same in both cases though.
I am trying to use PC-Lint on windows for exercising static code analysis on C files. I installed the software and ran the configuration setup forgcc compilerwhere I got the following files in the config directory: ``` co-gcc.h, co-gcc.lnt, env-ecl-console.lnt, filea.cpp, fileb.cpp, LIN.BAT, lset.bat, options.lnt, std.lnt, std_a.lnt ``` However when I try to run the test sample by typing>lin filea filebfrom the config directory, I get the following error: ``` co-gcc.lnt 37 Error 307: Can't open indirect file 'gcc-include-path.lnt' ``` How do we get the gcc-include-path.lnt file?
Error got solved by creatinglint_cmac.h, lint_cppmac.h, gcc-include-path.lnt, and size-options.lntfiles using the makefileco-gcc.maklocated inPC-lint9.00h\lntfolder.
I need to accept an array of integers from the command line, such as: ./test 2 9 -5 17 Currently I have: ``` int main(int argc, int *argv[]) ``` And then loops to find the two numbers within this array that create the maximum value possible starting with argv[1]. Obviously this does not work. Do I need it to be: ``` int main(int argc, char *argv[]) ``` and then parse this? I am not sure how to covert characters to integers in C. Thanks,
Use strtol() to convert each argv[i] (for i starting at 1) to a long int.
``` void insert(list **l, int x) { list *p; p = malloc(sizeof(list)); p->item = x; p->next = *l; *l=p; } ``` Why did we use double pointer? Could we have done the same thing using single pointer? I saw this example in the book "The Algorithm Design Manual" page 69 2nd Edition. List is basically node, just for refernce.
Could we have done the same thing using single pointer? You could have done that using a single pointer with a minor update. Return the pointer that was allocated and make sure that the function call is changed appropriately. ``` list* insert(list *l, int x) { // list = *p // What was that? That is not valid code. list* p = malloc(sizeof(list)); p->item = x; p->next = l; return p; } ``` and use it as ``` list* l = NULL; l = insert(l, 10); ```
I've installed Clion and MinGW, however in setting for Clion I get a message saying that C Compiler is not found. As shown here: Although I believe I've installed all variations of thegccpackage as shown: It also appears I'm missinggcc.exe: Anyone know what I'm missing and how to correct this error?
I found the solution. It appears that it wasn't actually downloading and extracting the exe properly. To fix it I clicked on the general tab for the package I wanted in the package manager, then had to type the Package URL into my browser (can't copy it for some reason). That downloaded the folders, so I just extracted them and put them into their respective directories and Clion now detects the compiler! The link for my version washttps://sourceforge.net/projects/mingw/files/MinGW/Base/gcc/Version4/gcc-4.9.3-1/gcc-core-4.9.3-1-mingw32-bin.tar.xz/download?use_mirror=iweb
I am having a hard time understanding how this code is working . I always thought before using pointer to a structure , it should be defined. In the below example why compiler doesn't complain about struct LL* Next ? ``` typedef struct LL { int value; **struct LL* Next;** }Node; Node* temp; ```
In your code, ``` struct LL* Next; ``` is allowed as a member inside thestruct LLdefinition itself and does not throw any error, because, at that point, compiler need not know about the definition of the structure itself. It just needs to allocate a pointer to the structure, and so it can. Later, while using a variable of thestructtype, you have to allocate memory for the pointee and assign that memory to the pointer before any further usage.
I need to accept an array of integers from the command line, such as: ./test 2 9 -5 17 Currently I have: ``` int main(int argc, int *argv[]) ``` And then loops to find the two numbers within this array that create the maximum value possible starting with argv[1]. Obviously this does not work. Do I need it to be: ``` int main(int argc, char *argv[]) ``` and then parse this? I am not sure how to covert characters to integers in C. Thanks,
Use strtol() to convert each argv[i] (for i starting at 1) to a long int.
``` void insert(list **l, int x) { list *p; p = malloc(sizeof(list)); p->item = x; p->next = *l; *l=p; } ``` Why did we use double pointer? Could we have done the same thing using single pointer? I saw this example in the book "The Algorithm Design Manual" page 69 2nd Edition. List is basically node, just for refernce.
Could we have done the same thing using single pointer? You could have done that using a single pointer with a minor update. Return the pointer that was allocated and make sure that the function call is changed appropriately. ``` list* insert(list *l, int x) { // list = *p // What was that? That is not valid code. list* p = malloc(sizeof(list)); p->item = x; p->next = l; return p; } ``` and use it as ``` list* l = NULL; l = insert(l, 10); ```
I've installed Clion and MinGW, however in setting for Clion I get a message saying that C Compiler is not found. As shown here: Although I believe I've installed all variations of thegccpackage as shown: It also appears I'm missinggcc.exe: Anyone know what I'm missing and how to correct this error?
I found the solution. It appears that it wasn't actually downloading and extracting the exe properly. To fix it I clicked on the general tab for the package I wanted in the package manager, then had to type the Package URL into my browser (can't copy it for some reason). That downloaded the folders, so I just extracted them and put them into their respective directories and Clion now detects the compiler! The link for my version washttps://sourceforge.net/projects/mingw/files/MinGW/Base/gcc/Version4/gcc-4.9.3-1/gcc-core-4.9.3-1-mingw32-bin.tar.xz/download?use_mirror=iweb
I am having a hard time understanding how this code is working . I always thought before using pointer to a structure , it should be defined. In the below example why compiler doesn't complain about struct LL* Next ? ``` typedef struct LL { int value; **struct LL* Next;** }Node; Node* temp; ```
In your code, ``` struct LL* Next; ``` is allowed as a member inside thestruct LLdefinition itself and does not throw any error, because, at that point, compiler need not know about the definition of the structure itself. It just needs to allocate a pointer to the structure, and so it can. Later, while using a variable of thestructtype, you have to allocate memory for the pointee and assign that memory to the pointer before any further usage.
Are these declarations different or do the produce the same result? ``` char * const *argv; ``` and ``` const char **argv; ``` Is there a difference or are both pointer to a pointer? The background is that I was writing a C commandline shell and used this struct for a command: ``` struct command { char * const *argv; }; ``` The above struct was used to callexec. Now when I looked at another question then the struct was different: Connecting n commands with pipes in a shell? In that question the struct to achieve the same is different.
They are totally different: char *const *argv;declares "a pointer toconstpointer to char"; const char **argv;declares "a pointer to pointer toconstchar"; Also,char **const argv;declares "aconstpointer to pointer to char". To understand these declarations, try reading them "inside out":http://c-faq.com/decl/cdecl1.html
As show in the following code, what is the difference between 0 and CVMX_FAU_REG_64_ADDR(0) in the cvmx_fau_reg_64_t? ``` #define CVMX_FAU_REG_64_ADDR(x) ((x <<3) + CVMX_FAU_REG_64_START) typedef enum { CVMX_FAU_REG_64_START = 0, CVMX_FAU_REG_64_END = CVMX_FAU_REG_64_ADDR(0), } cvmx_fau_reg_64_t; ```
In the code as written, both values == 0. There is no difference in the actual value.
If I have, ``` matrix1[4][4] = { 'a','b','c','d', 'e','f','g','h', 'i','j','k','l', 'm','n','o','p'} string1[50] = "text" ``` how do you go about adding a character from the matrix into the string? like if I wanted "g" added to "text" to make like string2 = textg strcat doesn't take these parameters. Can I do something like making a separate char string2 = matrix1[2][3] and append that to string1? But what if i want more than 1 char like g and k to make textgk.
Assign it directly ``` text[4] = matrix [2][3]; text [5] = '\0'; ``` Or you can do something like this. ``` void appendChar(char * pString, char c) { int len = strlen (pString); pString[len] = c; pString [len +1] = '\0'; } appendChar (string1, matrix [2][3]); ``` Of course this function assumes pString points to a buffer big enough to hold the character to be appended.
I am reading from text file hex, but I want to split it to two digits? ``` #include <studio.h> #include <stdlib.h> #include <math.h> #include <string.h> void main() { char hexa[100]; FILE *fp = fopen ("data2.txt", "r+"); fscanf(fp, "%s", hexa); printf("\n first data = %s \n", hexa); printf("\n first digit= %s \n", hexa[1]); printf("\n second digit= %s \n", hexa[2]); fclose(fp); } ``` I read from the file successfully, but the result is: ``` first data = 16 segmentation fault ```
hexa[1]andhexa[2]are characters, but you're printing them as though they were strings, that is, character arrays. Since they're in the range 0-255, and this range of memory is inaccessible, you get a crash. Do this: ``` printf("\n first digit= %c \n", hexa[1]); ``` and so on.
I am trying to print running processes on a linux system, but I am getting a segmentation fault when trying to do so. Here is my code: ``` FILE *ps; char line[256]; char * command = "ps"; ps = fopen(command, "r"); if(ps == NULL){ perror("Error"); } while(fgets(line, sizeof(line), ps)){ printf("%s", line); } fclose(ps); ``` The odd thing is that when I use the same code but replace "ps" with "/proc/meminfo" or other files, it will correctly output. Thanks in advance for the help.
Try to usepopenand pclose for running command rather than fopen and fclose ``` char line[256]; FILE *ps = popen("ps", "r"); if(ps == NULL){ perror("Error"); } while(fgets(line, sizeof(line), ps)){ printf("%s", line); } pclose(ps); ```
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.Closed7 years ago.Improve this question Is a C compiler obligated to place a static const variable in memory or is it allowed to use it as immediate instruction operand when referenced?
No, it isn't as long as you do not tell it to otherwise. It can very well use the constant as literal (immediate) values in assembler instructions. Telling otherwisecould be declaring the constvolatile(Telling the compiler: "We don't change it, but somebody else could")declaring and/or using i.e. dereferencing a pointer to theconstwhich is not explicitelyconst
I am fairly new to C. What i meant by question is, i have several C files where i have my error print say ``` if(sd_counter == 0) { kprintf("No directory exists!\n"); } ``` in different file i have several same kind of messages displayed. what i need is to store these errors in maybe header file and call it on my c files as ``` kprintf("%s/\n",err1); kprintf("%s/\n",err2); ``` so that i dont need to write whole sentence in each file.
In C, you can store values invariablesand refer to them by name. Example: messages.h: ``` extern const char msg1[]; extern const char msg2[]; ``` messages.c: ``` #include "messages.h" const char msg1[] = "Hello"; const char msg2[] = "World"; ``` main.c: ``` #include <stdio.h> #include "messages.h" int main(void) { puts(msg1); puts(msg2); } ```
This question already has answers here:Return value of "==" operator in C(4 answers)Closed7 years ago. Whats the meaning of equivalence operators(==) within function parameters in c language like the following instruction? binder_transaction(proc, thread, &tr, cmd == BC_REPLY);
cmd == BC_REPLYas an argument of functionbinder_transactionis basically aintvalue passed to the function. This is equivalent to1 ``` int b = (cmd == BC_REPL); // Will return either 0 or 1 binder_transaction(proc, thread, &tr, b); ```
When I document a function with Doxygen I can do this: ``` /*! * @brief does something * @param a first parameter * * Longer description */ void foo(int a) { /* */ } ``` But is there way I can document struct members this way: ``` /*! * @brief a struct * @??? a first struct member * @??? b second struct member * * Longer description */ struct a { int a, int b, }; ``` The reason is, I want to avoid having to document my struct members with inline comments, if possible.
``` /*! * @struct str_a * @brief my a struct * @details Longer description * * @var str_a::a * @brief first struct member * @details detailed first struct member * @var str_a::b * @brief brf second struct member * @details detailed second struct member * */ struct str_a { int a; int b; }; ```
This question already has answers here:Why does my output only print if there is another print after it?(3 answers)Closed7 years ago. I’m trying to convert arguments passed on the command line tointusingatoi, but it is taking forever no matter whether the string is small or big. Any ideas? ``` int main(int argc, char *argv[]) { int id; int v[5]; id=atoi(argv[2]); v[0]=atoi(argv[3]); v[1]=atoi(argv[4]); v[2]=atoi(argv[5]); v[3]=atoi(argv[6]); v[4]=atoi(argv[7]); //conversion must be taking forever; this is never printed printf("%d %d %d %d %d %d", id,v[0],v[1],v[2],v[3],v[4]); return 0; } ```
I suspect you areSuffering from Buffering. Change yourprintfline to ``` printf("%d %d %d %d %d %d\n", id,v[0],v[1],v[2],v[3],v[4]); ``` Note the added newline,\n.
I have an 8 bit register and I want to change bits 4,5 and 6 without altering the other bits. Those bit can take values from000to111(regardless their previous state). Is there a method to change them in one step or must I change them individually?
You need a mask to put the requested bits in aknown state, 0 is the more convenient as per my programming habits, then set the bits that you want to 1 with an or operation and write back: ``` #define mask 0x70 // 01110000b bit 4, 5 & 6 set reg = (reg & ~mask) | (newVal & mask); ``` We use the inverted mask to set to 0 the bits to change and the unchanged mask to set to 0 the bits that we don't want to interfere from the new value.If you are sure that the unwanted bits of the new value are always 0 you can simplify: ``` #define mask 0x8f // 10001111b bit 4, 5 & 6 reset reg = (reg & mask) | newVal; //newVal must have always bits 7, 3, 2, 1 & 0 reset. ```
Everybody knows that you have tofree()pointers, when you usemalloc()because the memory is allocated in the heap, which is not kept account of by the process. But why don't I have to usefree()when assigning a pointer without a heap: ``` char* text0 = calloc(20, sizeof (char)); strncpy(text0, "Hello World", 20); // Remember to use `free()`! char* text1 = "Goodbye World!"; // No need for `free()`? ``` Isn'ttext1also a pointer on the stack pointing to the memory allocated on the heap? Why is there no need for free()?
The string constant"Goodbye World!"is placed in a global, read-only section of memory at program startup. It isnotallocated on the heap. Same goes for"Hello World". So after the assignment,text1points to this static string. Since the string does not exist on the heap, there's no need to call free.
Rule 13.6 states that : The operand of the sizeof() operator should not contain anyexpression which has potential side affects.I am at a loss to determine how an operatorwith side effects will affect the outcome of sizeof() operator.Can anybody explain with this example ? ``` void f(int32_t n) { size_t s; s = sizeof(int32_t[n]); //Compliant s = sizeof(int32_t[n++]); //Non Compliant } ``` Or can anybody give an example of a more understandable example and explain with that ?
The expression that is input to thesizeofoperator is not evaluated. Only the type of the expression is deduced and used as input to thesizeofoperator. Which means that, in the case that is non compliant to MISRA,n++,nwill notbe incremented. As this is somewhat counter-intuitive, MISRA recommends not to use expressions with side effects to avoid errors.
I am trying to read memory information into a string in c, and I'm having a bit of trouble. Here is what I currently have. ``` FILE * fpipe; long length; char * command = "free"; fpipe = (FILE*) popen(command, "r"))); fseek(fpipe, 0, SEEK_END); length = ftell(fpipe); fseek(fpipe, 0, SEEK_SET); bufer = (char*) malloc(length); char line[128]; if(fpipe) { while(fgets(line, sizeof line, fpipe)) { strcat(buffer, line); } } ``` I am able to print line, but not add it to buffer. Thanks in advance for the help.
A slight modification to my previous comment, and the problem with your code now that we can see it: If you have a pipe, you can only seekforward, not backwards. Once you seeked to the end, you can no longer go back and all the data is lost. Instead you need to dynamically allocate andreallocatethe buffer each iteration.
This question already has answers here:Return value of "==" operator in C(4 answers)Closed7 years ago. Whats the meaning of equivalence operators(==) within function parameters in c language like the following instruction? binder_transaction(proc, thread, &tr, cmd == BC_REPLY);
cmd == BC_REPLYas an argument of functionbinder_transactionis basically aintvalue passed to the function. This is equivalent to1 ``` int b = (cmd == BC_REPL); // Will return either 0 or 1 binder_transaction(proc, thread, &tr, b); ```
When I document a function with Doxygen I can do this: ``` /*! * @brief does something * @param a first parameter * * Longer description */ void foo(int a) { /* */ } ``` But is there way I can document struct members this way: ``` /*! * @brief a struct * @??? a first struct member * @??? b second struct member * * Longer description */ struct a { int a, int b, }; ``` The reason is, I want to avoid having to document my struct members with inline comments, if possible.
``` /*! * @struct str_a * @brief my a struct * @details Longer description * * @var str_a::a * @brief first struct member * @details detailed first struct member * @var str_a::b * @brief brf second struct member * @details detailed second struct member * */ struct str_a { int a; int b; }; ```
This question already has answers here:Why does my output only print if there is another print after it?(3 answers)Closed7 years ago. I’m trying to convert arguments passed on the command line tointusingatoi, but it is taking forever no matter whether the string is small or big. Any ideas? ``` int main(int argc, char *argv[]) { int id; int v[5]; id=atoi(argv[2]); v[0]=atoi(argv[3]); v[1]=atoi(argv[4]); v[2]=atoi(argv[5]); v[3]=atoi(argv[6]); v[4]=atoi(argv[7]); //conversion must be taking forever; this is never printed printf("%d %d %d %d %d %d", id,v[0],v[1],v[2],v[3],v[4]); return 0; } ```
I suspect you areSuffering from Buffering. Change yourprintfline to ``` printf("%d %d %d %d %d %d\n", id,v[0],v[1],v[2],v[3],v[4]); ``` Note the added newline,\n.
I have an 8 bit register and I want to change bits 4,5 and 6 without altering the other bits. Those bit can take values from000to111(regardless their previous state). Is there a method to change them in one step or must I change them individually?
You need a mask to put the requested bits in aknown state, 0 is the more convenient as per my programming habits, then set the bits that you want to 1 with an or operation and write back: ``` #define mask 0x70 // 01110000b bit 4, 5 & 6 set reg = (reg & ~mask) | (newVal & mask); ``` We use the inverted mask to set to 0 the bits to change and the unchanged mask to set to 0 the bits that we don't want to interfere from the new value.If you are sure that the unwanted bits of the new value are always 0 you can simplify: ``` #define mask 0x8f // 10001111b bit 4, 5 & 6 reset reg = (reg & mask) | newVal; //newVal must have always bits 7, 3, 2, 1 & 0 reset. ```
Everybody knows that you have tofree()pointers, when you usemalloc()because the memory is allocated in the heap, which is not kept account of by the process. But why don't I have to usefree()when assigning a pointer without a heap: ``` char* text0 = calloc(20, sizeof (char)); strncpy(text0, "Hello World", 20); // Remember to use `free()`! char* text1 = "Goodbye World!"; // No need for `free()`? ``` Isn'ttext1also a pointer on the stack pointing to the memory allocated on the heap? Why is there no need for free()?
The string constant"Goodbye World!"is placed in a global, read-only section of memory at program startup. It isnotallocated on the heap. Same goes for"Hello World". So after the assignment,text1points to this static string. Since the string does not exist on the heap, there's no need to call free.
Rule 13.6 states that : The operand of the sizeof() operator should not contain anyexpression which has potential side affects.I am at a loss to determine how an operatorwith side effects will affect the outcome of sizeof() operator.Can anybody explain with this example ? ``` void f(int32_t n) { size_t s; s = sizeof(int32_t[n]); //Compliant s = sizeof(int32_t[n++]); //Non Compliant } ``` Or can anybody give an example of a more understandable example and explain with that ?
The expression that is input to thesizeofoperator is not evaluated. Only the type of the expression is deduced and used as input to thesizeofoperator. Which means that, in the case that is non compliant to MISRA,n++,nwill notbe incremented. As this is somewhat counter-intuitive, MISRA recommends not to use expressions with side effects to avoid errors.
I am trying to read memory information into a string in c, and I'm having a bit of trouble. Here is what I currently have. ``` FILE * fpipe; long length; char * command = "free"; fpipe = (FILE*) popen(command, "r"))); fseek(fpipe, 0, SEEK_END); length = ftell(fpipe); fseek(fpipe, 0, SEEK_SET); bufer = (char*) malloc(length); char line[128]; if(fpipe) { while(fgets(line, sizeof line, fpipe)) { strcat(buffer, line); } } ``` I am able to print line, but not add it to buffer. Thanks in advance for the help.
A slight modification to my previous comment, and the problem with your code now that we can see it: If you have a pipe, you can only seekforward, not backwards. Once you seeked to the end, you can no longer go back and all the data is lost. Instead you need to dynamically allocate andreallocatethe buffer each iteration.
Everybody knows that you have tofree()pointers, when you usemalloc()because the memory is allocated in the heap, which is not kept account of by the process. But why don't I have to usefree()when assigning a pointer without a heap: ``` char* text0 = calloc(20, sizeof (char)); strncpy(text0, "Hello World", 20); // Remember to use `free()`! char* text1 = "Goodbye World!"; // No need for `free()`? ``` Isn'ttext1also a pointer on the stack pointing to the memory allocated on the heap? Why is there no need for free()?
The string constant"Goodbye World!"is placed in a global, read-only section of memory at program startup. It isnotallocated on the heap. Same goes for"Hello World". So after the assignment,text1points to this static string. Since the string does not exist on the heap, there's no need to call free.
Rule 13.6 states that : The operand of the sizeof() operator should not contain anyexpression which has potential side affects.I am at a loss to determine how an operatorwith side effects will affect the outcome of sizeof() operator.Can anybody explain with this example ? ``` void f(int32_t n) { size_t s; s = sizeof(int32_t[n]); //Compliant s = sizeof(int32_t[n++]); //Non Compliant } ``` Or can anybody give an example of a more understandable example and explain with that ?
The expression that is input to thesizeofoperator is not evaluated. Only the type of the expression is deduced and used as input to thesizeofoperator. Which means that, in the case that is non compliant to MISRA,n++,nwill notbe incremented. As this is somewhat counter-intuitive, MISRA recommends not to use expressions with side effects to avoid errors.
I am trying to read memory information into a string in c, and I'm having a bit of trouble. Here is what I currently have. ``` FILE * fpipe; long length; char * command = "free"; fpipe = (FILE*) popen(command, "r"))); fseek(fpipe, 0, SEEK_END); length = ftell(fpipe); fseek(fpipe, 0, SEEK_SET); bufer = (char*) malloc(length); char line[128]; if(fpipe) { while(fgets(line, sizeof line, fpipe)) { strcat(buffer, line); } } ``` I am able to print line, but not add it to buffer. Thanks in advance for the help.
A slight modification to my previous comment, and the problem with your code now that we can see it: If you have a pipe, you can only seekforward, not backwards. Once you seeked to the end, you can no longer go back and all the data is lost. Instead you need to dynamically allocate andreallocatethe buffer each iteration.
The problem is essentially this: ``` DateTime timenow = RTC.now(); Serial.println(timenow.unixtime()); double unixd = timenow.unixtime()/1.234; Serial.println(unixd,4); ``` Outputs the following: ``` //unixtime - 1460128448 //unixd - 1183248384.0000 ``` When it should output: ``` //unixtime - 1460128448 //unixd - 1183248337.1150 ``` I have tried casting the variable differently like adding (float) or (double) or whatever, but nothing seems to work. Any ideas?
The number1183248337without a decimal requires 31 bits. Adouble/floaton an AVR is 32 bits. You are simply using a number that is too large for the type. You could used fixed width arithmetic usinguint64_t. Represent your number as an integer (11832483371150 instead of 1183248337.1150) then divide/subtract to extract the parts for printing.
Take theFILEtype defined instdio.hfor example: Is there any way to get the information about its fields(name, size, offset, etc) without taking a look at the header? Sometimes it'll be convenient to have such a function/macro to check the components of a struct.
No. There's no meta data associated with data structures in C, all of that is lost when compiling. And it's perfectly possible, sinceFILEis opaque, that no public header actually has the definition. It could just betypedef struct __FILE FILE;in the library header, and then all the details be kept on the inside, possibly in code you don't even have the source to.
"expression must have pointer to object type" error despite of not using pointers at all in the program. error occurs in line ``` #include<stdio.h> int main() { int j = 0, key, i=0; char l = 'r', al = {"abcdefghijklmnopqrstuvwxyz"}; while (l != al[j]) j++; key = j - i; return 0; } ```
Not using pointers is the problem. You get this becausealmust either be a pointer type or an array type, and not a single character.
Is there in C/C++ standart constant that reflects how many bits are there in one byte (8)? Something like CHAR_BIT but for byte.
According to the C standard, acharis one byte. ThereforeCHAR_BITis the number of bits in a byte. The C standard says thatCHAR_BITis"number of bits for smallest object that is not a bit-field (byte)".
I am currently developping an embedded application, and the problem is that I have reached a point where the whole app is actually too heavy for the RAM. So I am asking myself this question: Would my compiled program be lighter if I refractored some the files into one big file? Thanks.
No, not in general. The source-code organisation doesn't impact the memory use. It might be possible to refactor the program to use less memory, if you for instance have pieces of functionality that both use significant amounts but never run in parallel, but that's equally doable in a single file. It just requires making the sharing explicit.
This question already has an answer here:C's printf and fprintf(stdout,) are not printing(1 answer)Closed7 years ago. Just see the below program, ``` #include <stdio.h> int main() { printf("hai"); while(1); } ``` The above code is not printing hai and its just waitinG. But if I add ``` printf("hai\n"); ``` its working. Can I know what happening internally?
Writingprintf("hai\n");instead will cause, due to the newline character, the output buffer to beflushed, so you'll see the output before entering the infinite loop. There are other ways of flushing the output buffer, but appending the newline character is particularly simple. Technically the behaviour of a tight loop likewhile(1);isundefinedin C, but that is unlikely to be the cause of your problem.
I have a text like this. And I want to show it in doxygen documentation as it is. What type of command should I use.
You can use verbatim, endverbatim. http://www.doxygen.nl/manual/commands.html#cmdverbatim
I need my code to be fully up to ANSI standards like using this command line in Unix System: ``` gcc -ansi -Wall -pedantic code.c -o code... ``` How can I (manually) compile my code with those standards or is there any settings in Eclipse that can achieve this standard? Thank you very much!
Go to Project\Properties\C/C++ Build\Settings Then find: 'Miscellaneous' and check 'Support ANSI Programs', 'Warnings' and check 'Pedantic', 'Pedantic warnings as error', 'All warnings', 'Debugging' and choose preferred debug standards, 'Optimisations' then select any level.
Is there a way to check if a variable has been initialized or not in C? Consider the following example, ``` int main(){ int a = 3, b = 7, c; if ( a > b ) c = a-b; // Now, how can I check if the variable "c" has some value or not // I don't want check like this, // if ( isalpha(c) ) or if ( isdigit(c) ) // or anything similar to like that } ``` In other words, does C has some function likedefinedinPerl. InPerl, I can simply doif (defined c)that would check if the variable is defined or not, and it'd return False for above example. How can I achieve the same in C?
C does not have this ability. You have two main options: A sentinel value For example, if you know that the value ofcwill never be negative, then initialize it to-1, and test that for that. Add another variable Create another variablebool we_set_c_to_something = false;and then set it totruewhen you write toc.
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.Closed7 years ago.Improve this question I want to print out each integer of an int individually using a for loop. I am doing this because I want to print things in between some of the single ints. So if the number was 4564, I want to print out 4 5 6 4. Is there a quick way to do this? I know how to do it in java but I am new to C and am not sure.
Something like this shall help ``` while(num!=0) { printf("%d", num%10); //your last digit, you can store it in an array of characters as well num = num/10 ; } ``` Note: you've got to reverse the order while using the digits
I'm trying to create a make file for my program and I keep getting this error ``` error: typedef redefinition with different types ('unsigned short' vs '__darwin_size_t' (aka 'unsigned long')) /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/sys/_types/_rsize_t.h:30:32: note: previous definition is here typedef __darwin_size_t rsize_t; ^ ``` I have an unsigned short in my header file namedtypedef unsigned short rsize_t;but I do not have anything namedtypedef __darwin_size_t rsize_t;in any of my files, can someone explain to me what's happening here?
typedef __darwin_size_t rsize_t;is part of one of your operating system's header files.Youaren't trying to definersize_ttwice - you are defining it once, and so is the OS. Rename yourrsize_tto something else.
Im trying to create a 2d array for multiple data types but it seems to not be accepting the char data type. Why is this? ``` struct { union { int ival; float fval; char cval[50]; } val; } as[120][4]; as[0][1].val.cval = "Testtttt"; ***This does not work*** as[1][1].val.ival = 3; ***This works*** ```
You are inc, thus you should usestring.hwhen it comes to string handling! Change this: ``` as[0][1].val.cval = "Testtttt"; ``` to this: ``` strcpy(as[0][1].val.cval, "Testtttt"); ``` by usingstrcpy(), instead of the assignment operator (this would work inc++, not inc). Of course, alternative functions exist, such asstrncpy()*andmemcpy(). Moreover, since C string handling seems new to you, youmustread aboutnull terminated strings in C. *Credits to @fukanchik who reminded me that
If you useprintfsuch as: ``` printf("Time as a basic string = %s", ctime(&seconds)); ``` The output would be: ``` Wed, 28 Oct 2009 11:35:37 ``` How do I store this output thatctimegenerates so that: ``` char result[80] = ctime(&seconds); ``` Whatever I try just doesn't seem to work.
You want to usectime_rinstead ofctime. ``` char result[80]; ctime_r(&seconds, result); ```
I am trying to create a C++ wrapper (adding object orientation) around a C library (of which I am the author, i.e. I can apply changes there if needed). The C library defines some structs that make use ofsize_tas defined inlinux/types.hsince it interfaces with the kernel. I am now trying to include the header of the C library (that defines the struct) in the sources of my attempt at a C++ library. However, if I do so, the compiler tells me that size_tdoes not name a type What is the correct way to get access tosize_tfromlinux/types.hinC++? P.S.: The header file contains a#ifdef _cplusplus extern "C" { #endifblock
Don't include kernel headers in userspace. As stated in the C and C++ standards,size_tis defined in<stddef.h>(and for C++,<cstddef>definesstd::size_t).
I have defined a struct as follows: ``` struct Display7 { U8 a : 1; U8 b : 1; U8 c : 1; U8 d : 1; U8 e : 1; U8 f : 1; U8 g : 1; }Display7; ``` If I disable Strict ANSI C check in Keil IDE, there is no errors. If enable Strict ANSI C, I get the error "non standard type for a bit field". What is causing the problem? If I make each struct element as U32,then ANSI C doesn't complain.
Standard is clear about it: 6.7.2.1 Structure and union specifiers: 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. It is implementation-defined whether atomic types are permitted.
In C, what is the best way to ignore the commas when usingscanfon a number like 1,000,000?
I would say the best way is tonotusescanffor this. At least not using any number formats. Instead read it as a string, then remove the commas, and finallyconvert to a number.
I'm trying to understand a while loop. I realize the basics of how ternary operators work, but have only used them in loo of if statements, not in a while loop.This piece of code is really throwing me off. What would be the equivalent to this statement if it was not shortened? ``` int runOnce=0; while(runOnce=runOnce?((token=strtok(NULL," "))!=NULL):((token=strtok(strCopy," "))!=NULL)) { .... ```
This is a bit clearer in my opinion. ``` token = strtok (strCopy," "); while (token!=NULL) { /* do stuff */ token = strtok (NULL," "); } ```
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.Closed7 years ago.Improve this question I have small problem with my home task. I have to create a method that sums an array, but with specific, given step. I did something like this: ``` int sum_step(int t[], int size, int step) { int i; int sum = 0; for(i=0; i < size; i+step) { sum += t[i]; } return sum; } ``` and console returns warning: ``` warning: expression result unused [-Wunused-value] i + step; ~ ^ ~~~~ ``` Someone knows what is wrong? Thank in advance!
In followingforstatement the third expressioni+stepdoes nothing. ``` for (i = 0; i < size; i + step) ``` You probably wantito be incremented bystepafter each iteration so you should write this: ``` for (i = 0; i < size; i += step) ```
I have the following code: ``` if (destIndex < destLen && srcIndex < srcLen) dest[destIndex++] = src[srcIndex++]; ``` This code runs fine. If I remove the if, then the code crashes. If I then run the following code ``` if (destIndex < destLen && srcIndex < srcLen) dest[destIndex++] = src[srcIndex++]; else fprintf(stderr, "Buffer Overrun\n"); ``` Then I never get the print out "Buffer Overrun" SO, how to debug this? The seg fault only happens with optimizations turned on (no debug mode)
You have UB somewhere. 'Works in debug, but not release', or the other way round, is a massive undefined behaviour flag. Check all your parameters with your debugger:)
I am trying to code up a "generic" mergeSort in C: ``` void mergeSort(void *arr, int begin, int end,int size, int (*comp)(void *, void *)); ``` But since you need a holder/temp array, it becomes a bit tricky. I am not sure how to assign values to that array, since I created it as a void * array: ``` int mid = (begin + end) / 2; int len = end - begin + 1; void *pom = malloc(len*size); ``` But I can't assign values to that array, is there a way around it? ``` i = begin, j = mid + 1, k = 0; while (i <= mid && j <= end) **pom[k++]** = ((*comp)((char*)arr + i*size, (char *)arr + j*size) <= 0) ? arr[i] : arr[j]; while (i <= mid) **pom[k++]** = arr[i++]; while (j <= end) **pom[k++]** = arr[j++]; ``` the bold lines give off an error.
Yes, you need to copysizebytes. So**pom[k++]** = arr[i++];becomesmemcpy(pom + size*(k++), arr+size*(i++), size);and similar for all the others.
I'm trying to understand a while loop. I realize the basics of how ternary operators work, but have only used them in loo of if statements, not in a while loop.This piece of code is really throwing me off. What would be the equivalent to this statement if it was not shortened? ``` int runOnce=0; while(runOnce=runOnce?((token=strtok(NULL," "))!=NULL):((token=strtok(strCopy," "))!=NULL)) { .... ```
This is a bit clearer in my opinion. ``` token = strtok (strCopy," "); while (token!=NULL) { /* do stuff */ token = strtok (NULL," "); } ```
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.Closed7 years ago.Improve this question I have small problem with my home task. I have to create a method that sums an array, but with specific, given step. I did something like this: ``` int sum_step(int t[], int size, int step) { int i; int sum = 0; for(i=0; i < size; i+step) { sum += t[i]; } return sum; } ``` and console returns warning: ``` warning: expression result unused [-Wunused-value] i + step; ~ ^ ~~~~ ``` Someone knows what is wrong? Thank in advance!
In followingforstatement the third expressioni+stepdoes nothing. ``` for (i = 0; i < size; i + step) ``` You probably wantito be incremented bystepafter each iteration so you should write this: ``` for (i = 0; i < size; i += step) ```
I have the following code: ``` if (destIndex < destLen && srcIndex < srcLen) dest[destIndex++] = src[srcIndex++]; ``` This code runs fine. If I remove the if, then the code crashes. If I then run the following code ``` if (destIndex < destLen && srcIndex < srcLen) dest[destIndex++] = src[srcIndex++]; else fprintf(stderr, "Buffer Overrun\n"); ``` Then I never get the print out "Buffer Overrun" SO, how to debug this? The seg fault only happens with optimizations turned on (no debug mode)
You have UB somewhere. 'Works in debug, but not release', or the other way round, is a massive undefined behaviour flag. Check all your parameters with your debugger:)
I am trying to code up a "generic" mergeSort in C: ``` void mergeSort(void *arr, int begin, int end,int size, int (*comp)(void *, void *)); ``` But since you need a holder/temp array, it becomes a bit tricky. I am not sure how to assign values to that array, since I created it as a void * array: ``` int mid = (begin + end) / 2; int len = end - begin + 1; void *pom = malloc(len*size); ``` But I can't assign values to that array, is there a way around it? ``` i = begin, j = mid + 1, k = 0; while (i <= mid && j <= end) **pom[k++]** = ((*comp)((char*)arr + i*size, (char *)arr + j*size) <= 0) ? arr[i] : arr[j]; while (i <= mid) **pom[k++]** = arr[i++]; while (j <= end) **pom[k++]** = arr[j++]; ``` the bold lines give off an error.
Yes, you need to copysizebytes. So**pom[k++]** = arr[i++];becomesmemcpy(pom + size*(k++), arr+size*(i++), size);and similar for all the others.
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.Closed7 years ago.Improve this question ``` #include<stdio.h> #include<conio.h> void main() { int a,b,c; printf("\n Enter any three numbers"); scanf("%d%d%d", &a,&b,&c); if(a > b){ if(a > c){ printf("\n The greatest number is =%d",a); } } else if(b > a) { if(b > c) { printf("\n The greatest number is =%d",b); } } else { printf("\nThe greatest number=%d",c); } getch(); } ``` When the third number is greatest, there is no output on the screen. I tried using F7 and got to know that the line with 'else' statement is being skipped. What to do since I need to use nested if only.
Nothing abnormal here: your else statement corresponds to the case a==b ;)
I am able to put my stm32L1xDiscovery board in STOP mode with RTC running. according to the datasheet this should draw about 1.3 µA. But my application draws 3.3 µA. I noticed I did not put the FLASH in a low power mode during sleep. But when I did this, nothing changed. This is what I use to go into STOP mode: ``` SCB->SCR |= ((uint32_t)SCB_SCR_SLEEPDEEP); RCC->APB1ENR |= RCC_APB1Periph_PWR; PWR->CR |= ((uint32_t)(PWR_CR_LPSDSR|PWR_CR_ULP)); // ULP seems to have no effect on power consumption RCC->APB1ENR &= ~RCC_APB1Periph_PWR; FLASH->ACR |= SLEEP_PD; // seems to have no effect at all on power consumption __WFI(); ``` Any idea what I am missing here?
If you use discovery board your measurement may be not clear because a lot of other components consumpt some energy. It's may be protection diode, driver of 3.3V line or second MCU with ST-LINK/V2 embedded debug tool.
Let us suppose we have two arrays A[] and B[]. Each array contains n distinct integers which are not sorted. We need to find kth ranked element in the union of the 2 arrays in the most efficient way possible. (Please dont post answers about merging the arrays and then sorting them to return kth index in the merged array)
You can use theselection algorithmto find the Kth item, in O(N) time, where N is the sum of the sizes of the arrays. Obviously, you treat the two arrays as a single large array.
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.Closed7 years ago.Improve this question can you please help me to understand this while loop: ``` while (!(a % b)) { a = a / b; higher = b; } ``` I dont get the point with the (!(a % b)
while (!(a % b))is equivalent to ``` while ((a % b) == 0) ``` Which meansifais a multiple ofbthen execute the body else come out of the loop.
I'm curious as to why when say I traverse a linked list iteratively I must dowhile (list != NULL)instead ofwhile (!list). I thought NULL equated to zero or false. From comments: My program seems to always crash when I attempt awhile (!list)but never the former. Each node contains a void pointer to a piece of data and a pointer to the next node.
while (list != NULL)is not the same aswhile (!list). They are opposites! Of course your program crashes, it tries to de-reference aNULLpointer. while (list != NULL)is the same aswhile (list).
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed7 years ago.Improve this question I am expectingato be 5, making the comparison expression evaluate totrueand thus print: A = 5, B = 3, C = 6 ``` main() { int i,a,b=3,c=6,s; for(i=1;i<=1000;i++){ if(a*a+b*b==c*c){ printf("A = %d B = %d C = %d\n",a,b,c); } a = i; } } ```
Where is a initialized? I am seeing i being set, as well as b and c, but I'm not seeing any assignment to a. The solution is to assign the current value of i to a: a=i prior to the if statement. You are assigning the value after the fact. Alternatively, evaluate i, not a.
I am trying to build by gcc a simple C code using thread_create. To use thread_create(), which library should be "#include"d? Should I send also specific flags to the gcc?
You can usepthread_createincluded in<pthread.h>, for more information, see the manpage ofpthread_create, if you're on Linux you can typeman pthread_createin your terminal.
I'm making pkcs11 module for web app. It's remote storage for certificates and it provides API for signing data. API for signing looks like this: sign(int CertificateId, char* Password, void* data, int lenght) In pkcs11 module, the whole storage is represented by one single token. In the C_Initialize section, I authenticate to the server. I find objects with another API call and everything is fine. The problem is, when I call C_SignInit or C_Sign function, I dont know how to get secondary password for my object. Can anyone help me?
In PKCS#11 all objects are protected with a User PIN. They don't have their own PINs. So there's no standard way to ask for a different PIN for the particular object.
For the moment, my C codebases compile relatively quickly. However, I would like to utilise aninformedapproach to reducing the number of times a given header is re-processed. I guess that being able to see reference counts would help me to do so. How would I do that?
Both CLang and GCC support the-Hoption. It will dump into the console each header file included. Then, you can easily read these lines and analyze them to detect compiler bottlenecks. Fromman gcc: -HPrint the name of each header file used, in addition to other normal activities. Each name is indented to show how deep in the#includestack it is.Precompiled header files are also printed, even if they are found to be invalid; an invalid precompiled header file is printed with...xand a valid one with...!.
I want to set the last three bit of a byte to a specific vaue. What’s the best way to archive this goal? I can think of at least two solutions… Let’s assume I have the following Byte: 1101 0110 and want to set the three last bits to 011. Solution 1: ``` 1101 0110 &1111 1000 //and with mask to clear last three bits |0000 0011 //add the target bits ``` Solution 2: ``` 1101 0110 >> 3 //shift right to remove last three 0001 1010 << 3 //shift left to clear last three |0000 0011 //add target bits ``` Is there a better/shorter/more efficient way?
The best way is to say ``` b = (b & ~7u) | 3 ``` because3=0...011and7u=0..111in binary, and the complement of7uis~7u=11...1000, so the operation does what you want. It first clears the last three bits (by doingb & ~7u) and then sets the first and the second bits (by doing bitwise-OR with3).
When I try tomalloc()astruct bstreenode, my compiler is reporting an error: invalid conversion from 'void*' to 'bstree*' Here is my code: ``` struct bstree { int key; char *value; struct bstree *left; struct bstree *right; }; struct bstree *bstree_create(int key, char *value) { struct bstree *node; node = malloc(sizeof (*node)); if (node != NULL) { node->key = key; node->value = value; node->left = NULL; node->right = NULL; } return node; } ```
In C++ there is no implicit conversion from typevoid *to pointer of other type. You have to specify explicit casting. For example ``` node = ( struct bstree * )malloc(sizeof (*node)); ``` or ``` node = static_cast<struct bstree *>( malloc(sizeof (*node)) ); ``` Also in C++ you should use operatornewinstead of the C functionmalloc.
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed7 years ago.Improve this question I am expectingato be 5, making the comparison expression evaluate totrueand thus print: A = 5, B = 3, C = 6 ``` main() { int i,a,b=3,c=6,s; for(i=1;i<=1000;i++){ if(a*a+b*b==c*c){ printf("A = %d B = %d C = %d\n",a,b,c); } a = i; } } ```
Where is a initialized? I am seeing i being set, as well as b and c, but I'm not seeing any assignment to a. The solution is to assign the current value of i to a: a=i prior to the if statement. You are assigning the value after the fact. Alternatively, evaluate i, not a.
I am trying to build by gcc a simple C code using thread_create. To use thread_create(), which library should be "#include"d? Should I send also specific flags to the gcc?
You can usepthread_createincluded in<pthread.h>, for more information, see the manpage ofpthread_create, if you're on Linux you can typeman pthread_createin your terminal.
I'm making pkcs11 module for web app. It's remote storage for certificates and it provides API for signing data. API for signing looks like this: sign(int CertificateId, char* Password, void* data, int lenght) In pkcs11 module, the whole storage is represented by one single token. In the C_Initialize section, I authenticate to the server. I find objects with another API call and everything is fine. The problem is, when I call C_SignInit or C_Sign function, I dont know how to get secondary password for my object. Can anyone help me?
In PKCS#11 all objects are protected with a User PIN. They don't have their own PINs. So there's no standard way to ask for a different PIN for the particular object.