question
stringlengths
25
894
answer
stringlengths
4
863
I have a simple question that I couldn't find the answer for by googling -- is it possible to escape the C language's string null terminator '\0', so that we can include it in a string?
Note that a "string" with an embedded NUL is no longer astring. You cannot safely use it as an argument to functions declared in<string.h>, for example ``` char embeddednul[] = "zero\0one\0two\0"; // embeddednul[12] = embeddednul[13] = 0 printf("len: %d\n", strlen(embeddednul)); // 4?? char tmp[1000] = {0}; strcpy(tmp, embeddednul); // copies 'z', 'e', 'r', 'o', and 0 char *p = embeddednul; while (*p) { while (*p) putchar(*p++); // prints zero putchar('\n'); // then one p++; // then two } ```
Since bounded loop are now allowed in ebpf programshttps://git.kernel.org/pub/scm/linux/kernel/git/davem/net-next.git/commit/?id=2589726d12a1b12eaaa93c7f1ea64287e383c7a5does the verifier still check in the first pass if the program control flow is a Direct Acyclic Graph?
Yes,it still does, and rejects programs with back-edges in two cases: If the program is loaded by anunprivileged user. Theenv->allow_ptr_leaksboolean indicates a privileged user.If the back-edge isperformed using a call.Only normal jumps can make bounded loops(which doesn't mean you can't do a bpf-to-bpf callinsidea bounded loop).
I have a variable length MACRO from which i need to perform an operation based on the argument that is passed. Is there a way to get the argument with index directly using__VA_ARGS__? ``` #define OPERATION5(_1) (_1) #define _GET_1ST_ARG( N, ...) (N) #define TOP_MACRO(...){\ OPERATION##(_GET_1ST_ARG(1));\ } ```
You need first expand then concatenate the identifiers with another macro passYou need to remove the braces when getting the first argument. The(can't be concatenated. ``` // CONCATenate #define CONCAT(a, b) a ## b // eXpand then CONCATenate #define XCONCAT(a, b) CONCAT(a, b) #define OPERATION5(_1) (_1) // remove `(` they can't be `##` concatenated #define GET_1ST_ARG(N, ...) N #define TOP_MACRO(...) XCONCAT(OPERATION, GET_1ST_ARG(__VA_ARGS__))(arg) // expands `OPERATIONS5(arg)` // expands to `(arg)` TOP_MACRO(5) ```
I came from python and it was easy to get the middle digit of an integer, for example, from 897 I want the 9: ``` >>> num = 897 >>> num2 = int(str(num)[1]) >>> num2 9 ``` But how i can do this on C? It's so difficult to convert into string...
Getting a single digit as anintcan be done mathematically: ``` int num = 897; int dig1 = (num / 1 ) % 10; int dig2 = (num / 10 ) % 10; int dig3 = (num / 100 ) % 10; ``` Division by one on the first line is only for illustration of the concept: you divide by n-th power of ten, starting with 100= 1.
Why is the following loop: ``` for (int i=0; string[i] != 0; i++) ``` Often written as the following: ``` for (int i=0; string[i] != '\0'; i++) ``` If they would evaluate to the same thing, why would someone use the\0in the above? Is there any advantage in that or it is the same thing?
It is the same thing. There is no particular advantage. Thestring[i] != '\0'form emphasizes that we're looking at characters. But the further simplificationfor (int i=0; string[i]; i++)would work just as well also. It's similar with pointers. You can writep != NULL, orp != 0, or justp. The first form emphasizes that we're talking about a pointer. But it's a matter of style, not correctness.
I have a header with only an unscoped enum declared: foo.h: ``` #ifndef FOO_BAR_ENUM_H #define FOO_BAR_ENUM_H typedef enum Foo { Bar, BigBar, LittleBar, MassiveBar BarCount } Foo; #endif ``` I use this header from both C and C++. Should it be guarded by an extern "C" block? Including from both compiles fine, but is there a linking difference in this usage that is valid as far as the compiler is concerned but may not be expected from a naive user?
This header is not going to generate any symbols for linkage, hence it is not necessary to guard it with anextern "C"block.
What is the meaning of-Wextrainclangcompiler flag? I was curious what does all the flags such as-Wall,-Werrormeans. I was able to find answers for others, but not-Wextra. ``` clang -Wall -Wextra -Werror ```
-Wextraflag is not specific to just the clang compiler, it is documented in theGCC Compileras well. Basically,-Wallenables all (common) warning flags but this excludes many flags. Some of these, notably-Wempty-init-stmt,-Wignored-qualifiers,-Winitializer-overrides,-Wmissing-field-initializers,-Wmissing-method-return-type,-Wnull-pointer-arithmetic,-Wsemicolon-before-method-body,-Wsign-compare,-Wunused-parameterare covered by-Wextrainstead. You can find out more about what each of these mean in thedocumentation.
To create a string that I can modify, I can do something like this: ``` // Creates a variable string via array char string2[] = "Hello"; string2[0] = 'a'; // this is ok ``` And to create a constant string that cannot be modified: ``` // Creates a constant string via a pointer char *string1 = "Hello"; string1[0] = 'a'; // This will give a bus error ``` My question then is how would one modify a constant string (for example, by casting)? And, is that considered bad practice, or is it something that is commonly done in C programming?
By definition, you cannot modify a constant. If you want to get the same effect, make a non-constant copy of the constant and modify that.
Here is a code example ``` #define S 113 double some_func1() { return S; } double some_funcN( float S ) { return S/0.1; } ``` When I am trying to compile it I am getting this error: error C2143: syntax error : missing ')' before 'constant' I am wondering if it is possible to fix it without renaming the 'S' variable?
The tokenSwill be replaced with113everyplace it appears. You have a few options to fix this: Rename the parameter tosome_funcN:double some_funcN( float n ) { return n/0.1; }Undefine the constant before the function and redefine it after. This has the disadvantage thatSis defined in multiple places, so I wouldn't recommend it:#undef S double some_funcN( float S ) { return S/0.1; } #define S 113ChangeSfrom a macro to a variable. This allows variable scoping rules to take effect so that the function parameterSmasks the definition of the variableSdeclared at file scope.const int S = 113;
``` char* str ="Hello"; ``` In the above code the literal "Hello" is stored ... in the DATA segment and it is read-only. So isn't it better to always declare it: ``` const char* str = "Hello"; ``` to avoid improper code such as: ``` *(str+1) = 't'; ```
"Hello" is stored ... in the DATA segment "DATA" or.datawould refer to the segment where initialized read/write variables with static storage duration go. String literals are not stored there, but more likely in something called.rodata, or possibly in.textalong with the code. SeeString literals: Where do they go? So isn't it better to always declare it:const char* str = "Hello"; Yes, you should alwaysconstqualify pointers to string literals. This is universally considered best practice in C (and mandatory in C++).
I get different values as output each time I run the code. When heap and stack addresses are fixed why does malloc return a different address? I expected it to start allocating from top of heap and return a fixed address each time. Similarly for stack. ``` #include <stdio.h> #include <stdlib.h> int main(){ int *ptr = malloc(128); int a; printf("%p %p\n", ptr, &a); return 1; } ```
Heap and stack addresses are not fixed. Some systems useaddress space layout randomizationto deliberately vary the addresses so that attackers will not have predictable addresses to use with exploits.
On some sites I have found thatvoidis a scalar type: https://ee.hawaii.edu/~tep/EE160/Book/chap5/section2.1.3.htmlhttp://herbert.the-little-red-haired-girl.org/en/prgmsc1/docs/part2a.pdfhttps://www.zentut.com/c-tutorial/c-data-types/ Other sites contain no information about this: https://www.sqa.org.uk/e-learning/LinkedDS01CD/page_03.htmhttps://i.stack.imgur.com/tFDt3.png Isvoida scalar type or not?
From the C18 standard (6.2.5 §21) : Arithmetic types and pointer types are collectively calledscalar types. voidis neither an arithmetic type, nor a pointer type, so it's not a scalar type. From 6.2.5 §19 : Thevoidtype comprises an empty set of values; it is an incomplete object type that cannot be completed.
With libfq and the C API, is there a way to get the nullable metadata of a column from a query? I'm just talking about the property of a column, not the NULL value from a resultset. For instance, with MySQL: mysql_fetch_field_direct() does the job. I tried with PQfmod, but without success.
Information about the table definition is not part of the result set data. You can find out if the value isNULL, but not if the column is nullable or not. A column in a result set need not be related to a certain column in a table! To get information about a column's definition, queryinformation_schema.columns. Theis_nullablecolumn will contain the information.
In my C program I can set environmental variable via..setenv However setenv only allows me to setup an environmental variable via a string. Currently in my environment I have the below setup in my bash profile... ``` export MY_PASSWORD=`java -jar decrpytpassword $ENCRYPTED_PASS` ``` where decryptpassword is a Java executable jar file which accepts encrypted password and prints out decrypted password. I want to do something similar in my C program where I will pass the encrypted password via a string and decrypt it.
One way to do this would be: Usepopento run the command and capture its output.Read a string from that output (perhaps usingfgets).Put that new string in the environment usingsetenv. P.S. If you usefgetsin step 2, you may have to add a step 2a to strip the trailing\n.
I am trying to add in a left-wise operator to replace the following: ``` unsigned long bitmask = 0b10000000000000000000000000000000; printf("%lu\n", bitmask); unsigned long bitmask2 = (1 << 31)-1; printf("%lu\n", bitmask2); ``` However, the closest I'm able to get is-1. If I try doing (1 << 31), it looks like I get an overflow or something. What would be the proper way to do this? ``` # in the python shell >>> 0b10000000000000000000000000000000 2147483648 >>> 1<<31 2147483648 >>> 0b10000000000000000000000000000000 == 1<<31 True ```
Since the type of the result of your shift isunsigned long, you should start with an unsigned long constant: ``` unsigned long bitmask2 = (1UL << 31) - 1; ```
This question already has answers here:How to change entry point of C program with gcc?(4 answers)Closed4 years ago. Can the C _start function be made to call an entry point function other than main? The reason is I want to have a preprocessor embed additional functions in every C program I compile. The embedded code might provide test functions. Or some special debug features. When I compile the program I would like to tell _start to call the my_main function instead of main. If command line argument -test is specified, my_main would call the special test functions. Otherwise, my_main calls the actual main function.
Yes itmaybe possible, however it’s all up to the compiler if that feature is supported or not. So you will have to look it up in your compiler manual.
i want to put some float numbers inside a string in C for an arduino project. but i don't have any idea that can simply do this and not take lot storage(because of using arduino with 8kb). this is my string: ``` char http_cmd[] = "GET /index.php?lat=*****&long=***** HTTP/1.0\r\n" "Host: 39c309ae.ngrok.io\r\n" "\r\n"; ``` and i want to replace that *****s with numerical variables like : ``` float latitude = 36.423156, longitude = 48.526484; ```
Using sprintf() ``` float latitude = 36.423156, longitude = 48.526484; sprintf( http_cmd, "GET /index.php?lat=%f&long=%f HTTP/1.0\r\n Host: 39c309ae.ngrok.io\r\n\r\n", latitude, longitude); ``` You can compose your own string by printing chars, integers, float... And you can decide how many digits print to the array (in this case 4 digits).
This question already has answers here:Why sizeof(array) and sizeof(&array[0]) gives different results?(8 answers)Closed4 years ago. Here is the code: ``` #include <stdio.h> int main() { int arr[] = {10, 20, 30, 40, 50, 60}; int *ptr = arr; printf("Size of arr[] %d\n", sizeof(arr)); printf("Size of ptr %d", sizeof(ptr)); return 0; } ``` What is the difference between the twoprintfstatements?
Take a look at the wikipedia article on howsizeof works on arrays. Essentially, it is returning the bytes required to store the entire array. In this case you have 6 ints, so this turns intosizeof(int) * 6=4 * 6=24 However, the secondsizeofis getting the size of an int pointer. Your 64-bit machine has64/8=8byte pointers. Note that while pointers and arrays are usually considered the "same" in C, this is one of the areas where the behavior differs.
If a parent and child process communicate via a pipe, what would happen if a parent reads from a pipe after a child process has written to it and died?
When the child dies, its end of the pipe is automatically closed. The parent will read EOF after reading everything that the child wrote before it died, just as if the client calledclose()explicitly. Note that the parent can only read data that has actually been written to the pipe. If the child process is performing buffered output, as is the default when usingstdio, all the data the application has written might not be in the pipe when it dies. Stdio buffers are automatically flushed when the process callsexit(), but if it dies due to a signal this will not be called.
If a child calls exec it terminates and a new process is created with the same pid. Would the wait() function wait for the child to terminate or the grandchild?
If a child calls exec it terminates and a new process is created with the same pid. No, not quite. execdoes not create a new process -- it overwrites a single process (the old process) with a new program. So there's no new child (no "grandchild"), and no new pid. So if the parent callswait, it won't return until theexec'ed program does. (In fact,execdoesn't have much of an external effect, that the parent could detect, at all.)
If a child calls exec it terminates and a new process is created with the same pid. Would the wait() function wait for the child to terminate or the grandchild?
If a child calls exec it terminates and a new process is created with the same pid. No, not quite. execdoes not create a new process -- it overwrites a single process (the old process) with a new program. So there's no new child (no "grandchild"), and no new pid. So if the parent callswait, it won't return until theexec'ed program does. (In fact,execdoesn't have much of an external effect, that the parent could detect, at all.)
This question already has answers here:for loop - statement with no effect(5 answers)Closed4 years ago. for loop runs infinitely and it prints 1 infinitely when I run the below code. ``` #include<stdio.h> #include<conio.h> void main(){ int i,n; scanf("%d", &n); for(i=1;i<=n;i+2){ printf("%d",i); } getch(); } ``` If the input of n= 10 Actual Output: ``` 11111111111111111111111111111111111111111111111111....... ``` Expected Output: ``` 13579 ``` I want to know why 1 is printed infinitely.
i+2does not changei, you wanti += 2ori = i + 2
I'm using MPLAB 5.25 with XC8 (2.10) to compile a program for a PIC18F42K47. I want to print right aligned to a buffer, but the output is always aligned left. Here is my Code: ``` uint8_t Str_1[10] = {0}; uint8_t Str_2[10] = {0}; uint8_t Str_3[10] = {0}; sprintf(Str_1, "%3.2f", 12.345); // -> "12.35" sprintf(Str_2, "%04.2f", 2.345); // -> "2.35" sprintf(Str_3, "% 3.1f", -123.4); // -> "-123.4" ```
The format specifier has awidthargument left of the decimal point. This number describes the minimaltotalnumber of characters, not the number of characters before the decimal point. ``` sprintf(Str_1, "%8.3f", 12.345); // -> " 12.345" ```
I want to make a new application with the GTK3 API. I want to use the old GTK API described in the textbook from my lecturer. The old API isgtk_text_freeze. I have read the Gtk documentation on the Gnome website, and I find that the API has been deprecated, but it does not explain the replacement of the API. So. Do you know a replacement for that API?
GtkText was deprecated ~18 years ago ... I wonder when the lecture material was last updated? The typical way to prevent update flicker is to callg_object_freeze_notify()on your data source (like a GtkTextBuffer), then do the updates you are going to do, then callg_object_thaw_notify (). This isn't really a "replacement" for gtk_text_freeze() since what it did was stupid: you don't want to stop redrawing the widget, you just want the new data to appear atomically.
I am writing a program and I get the following error message: error: stray ‘\344’ in program What does this means? Here is the program: ``` int lotto, zahl, i; double produktlotto, produktzähl, binominalkoffizient, differenz; i=1, lotto=0, zahl=0, produktlotto=1, produktzahl=1; double produktdiffierenz ```
German umlaute likeä, ö, ü, ßare not supported in C / C++. Always and only use characters of the ASCII-Table in your code! Removing the umlaut will resolve your error!
I want to insert string to the array until I type "ok". Why I am getting just "ok" and original array at the output? ``` int main(void) { char b[20]; char* str[10] = { "1","2" }; int i = 2; while (1) { gets(b); if (strcmp(b, "ok") == 0) break; str[i] = b; i++; } for (int j = 0; j < i; j++) printf("%s ", str[j]); return 0; } ```
You need to allocate a string on each iteration: ``` int main(void) { char* b; char* str[10] = { "1","2" }; int i = 2; while (1) { b = malloc(20); gets(b); if (strcmp(b, "ok") == 0) break; str[i] = b; i++; } for (int j = 0; j < i; j++) printf("%s ", str[j]); // free allocated strings while (i > 2) free(str[--i]); return 0; } ```
I'm fairly new to C, hence could someone please help me understand the below struct declaration? ``` extern struct server_module* module_open (const char* module_path); ``` Per my understanding,module_openis pointer to thestruct server_module, however, didn't understand the last part of the statement i.e.(const char* module_path)
extern struct server_module* module_open (const char* module_path);declaresmodule_opento be a function taking a parameter namedmodule_pathof typeconst char *and returning astruct server-module *.
I'm looking for an example of eBPF to write a seccomp filter, but I can't find none. Could someone tell me if is possible to use eBPF to write seccomp filter?
Seccomp does not work with eBPF at the moment (only cBPF). There wasa discussionnot long ago on that topic on the Linux networking mailing list. The eBPF maintainer is against adding eBPF support to seccomp.
In GDB want to print values of all pointers in an array on hitting a breakpoint. There may be array elements with value as 0x0. Ex: ``` arr[] = {0x0, 0x5cb04, 0x5510, 0x0, 0x5c84} (gdb) info b Num Type Disp Enb Address What 1 breakpoint keep y 0x1234 in fun1 at file1.c:200 p arr p *arr[0] p *arr[1] p *arr[2] p *arr[3] c ``` But GDB fails to print values of *arr[1], *arr[2], *arr[3], coz *arr[0] hits the error"Cannot access memory at address 0x0" . Is there any solution or workaround to this problem?
Thegdb print commandcan use any validexpression, so you could do something like : ``` p (arr[0]) ? *arr[0] : "null" ```
Is it possible to write: ``` #define FIRST_DEF 1 #define SECOND_DEF 2 #ifndef ALREADY_DEFINED #define MY_MACRO FIRST_DEF #define ALREADY_DEFINED #else #define MY_MACRO SECOND_DEF #endif ``` So that MY_MACRO does not have the same value when not used the first time? So that writting: ``` int a = MY_MACRO; int b = MY_MACRO; ``` expands to: ``` int a = 1; int b = 2; ``` If not, is there a way to do this? (I know that this example is silly but it is just to make the question clearer.)
For your example, you can use the pre-defined macro__COUNTER__which will get incremented everytime it is used. Note that it is a non-standard compiler extension, but both GCC and MSVC support it.
What is the difference between: ``` typedef struct{ uint8 index; uint8 data[256]; }list_t; list_t myList; ``` and ``` typedef struct list_t{ uint8 index; uint8 data[256]; }list_t; list_t myList; ``` I am using the first approach but I saw the second one on an answer. I just want to define type and define the variable with that type separately.
The difference is useful for self-referencing data structures. ``` typedef struct { int value; Example1 *ptr; // error here: the type Example1 is not known yet } Example1; typedef struct Example2 { int value; struct Example2 *ptr; // OK: the type struct Example2 is known } Example2; ``` Note that the name afterstructis not necessarily the same as the one used fortypedef.
In GDB want to print values of all pointers in an array on hitting a breakpoint. There may be array elements with value as 0x0. Ex: ``` arr[] = {0x0, 0x5cb04, 0x5510, 0x0, 0x5c84} (gdb) info b Num Type Disp Enb Address What 1 breakpoint keep y 0x1234 in fun1 at file1.c:200 p arr p *arr[0] p *arr[1] p *arr[2] p *arr[3] c ``` But GDB fails to print values of *arr[1], *arr[2], *arr[3], coz *arr[0] hits the error"Cannot access memory at address 0x0" . Is there any solution or workaround to this problem?
Thegdb print commandcan use any validexpression, so you could do something like : ``` p (arr[0]) ? *arr[0] : "null" ```
Is it possible to write: ``` #define FIRST_DEF 1 #define SECOND_DEF 2 #ifndef ALREADY_DEFINED #define MY_MACRO FIRST_DEF #define ALREADY_DEFINED #else #define MY_MACRO SECOND_DEF #endif ``` So that MY_MACRO does not have the same value when not used the first time? So that writting: ``` int a = MY_MACRO; int b = MY_MACRO; ``` expands to: ``` int a = 1; int b = 2; ``` If not, is there a way to do this? (I know that this example is silly but it is just to make the question clearer.)
For your example, you can use the pre-defined macro__COUNTER__which will get incremented everytime it is used. Note that it is a non-standard compiler extension, but both GCC and MSVC support it.
What is the difference between: ``` typedef struct{ uint8 index; uint8 data[256]; }list_t; list_t myList; ``` and ``` typedef struct list_t{ uint8 index; uint8 data[256]; }list_t; list_t myList; ``` I am using the first approach but I saw the second one on an answer. I just want to define type and define the variable with that type separately.
The difference is useful for self-referencing data structures. ``` typedef struct { int value; Example1 *ptr; // error here: the type Example1 is not known yet } Example1; typedef struct Example2 { int value; struct Example2 *ptr; // OK: the type struct Example2 is known } Example2; ``` Note that the name afterstructis not necessarily the same as the one used fortypedef.
I have the classic ``` #define SOME_CONSTANT value ``` Is there a way to get the string"SOME_CONSTANT"like the C#nameof(field)? EDIT I have to parse a file looking for some keyword: ``` #define KEY_A 1 #define KEY_B 2 int foo(char *s) { if (strcmp(s, nameof(KEY_A)) == 0) return KEY_A; else if (strcmp(s, nameof(KEY_B)) == 0) return KEY_B; else return -1; } ``` if i callfoo("KEY_A")it should return 1
Since no-one else has posted the answer... @palmis, I think this is the solution that you were seeking. ``` #define NAMEOF(x) (#x) ```
I am defining some macro -#definetemporary inside code, which I have#undefafter being used. Is it not allowed to#undefMACRO? ``` void c_cmd(unsinged char *com) { int abc = com[0]; int res = 0; switch(abc) { case 1: #define ssCmd com[2] /* SRT or STP*/ res = abc + ssCmd; /* part of some functionality */ #undef ssCmd break; default: break; } } ``` Observed warning: use of '#undef' is discouraged: 'ssCmd' [MISRA 2012 Rule 20.5, advisory]
Yes, MISRA Rule 20.5 says that#undefshould not be used. It's an advisory rule. Rationale:The use of#undefcan make it unclear which macros exist at a particular point within a translation unit.
I'm looking to break up binary into blocks or 8 digits. Is there a way to do the following in C without doing a second print line? ``` printf("%d%c", number>>(i-1) & 1, (i%8==0) ? ' ' : ''); ``` Or is it not possible to do the "empty char" and I should add a second line to check for that?
There's no such thing as an empty char. You can use%swith strings. ``` printf("%d%s", number>>(i-1) & 1, (i%8==0) ? " " : ""); ```
I am trying to read the last n-amount of digits from a text file without using the stdio.h function calls. I am unsure on how to do this as I am unable to use fseek without using stdio.h and I am not familiar with system calls. Any help would be appreciated. ``` #include <unistd.h> #include <sys/types.h> #include<sys/stat.h> #include <fcntl.h> int main() { int fd; char buf[200]; fd = open("logfile.txt", O_RDONLY); if (fd == -1){ fprintf(stderr, "Couldn't open the file.\n"); exit(1); } read(fd, buf, 200); close(fd); } ```
You can uselseek. Here's the prototype: ``` off_t lseek(int fd, off_t offset, int whence); ``` Here's how you can integrate it into your code: ``` lseek(fd, -200, SEEK_END); read(fd, buf, 200); ```
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed4 years ago.Improve this question I currently learning the C programming language and I am not sure of what the width in a float is? I have changed the precision of the float already and it added0after the.and when I changed the value of the width it just added blank spaces behind ``` new_price = price + increase; printf("New price is %4.2f", new_price); return 0; ```
The4in"%4.2f"is thewidth. It directsprintf()to add spaces per: If the converted value has fewer characters than the field width, it is padded with spaces (by default) on the left ...
I have a struct to represent an AST, and I'm on an embedded device, I have no malloc, everything should be either on stack or global. So my struct; ``` /* AST Structre */ typedef struct ast { uint8_t type; /* This is the token value in grammar.h */ /* Value of the token */ union { double number; char literal; } value; struct ast *left; /* left hand side of the node */ struct ast *right; /* right hand side of the node */ } ast_t; ``` My question is whats the best way to use recursive structs without malloc.
Simply create an array and initialize/assign as needed. ``` ast_t fred[] = { { 1, {2.0}, NULL, &fred[1]}, { 3, {4.0}, &fred[0], NULL } }; ``` Call theast_tfunctionsfoo(fred);. Be sure to not callfree(fred).
For a predefined function where are the declaration and definition stored? And is the declaration stored in libraries? If so, then why it is named library function?
This is an imprecise question. The best answers we can give are: The declaration of standard library functions can best be thought of as being stored in their header files.Depending on how you want to think about it, the definition of standard library files is either in the source files for those libraries (which may be invisible to you, a trade secret of your compiler vendor), or in the library files themselves (.a,.so,.lib, or.dll).These days, knowledge of standard library functions is typically built in to the compiler, also. For example, if I write the old classicint main() { printf("Hello, world!\n"); }, but without any#includedirectives, my compiler says, "warning: implicitly declaring library function 'printf'" and "include the header <stdio.h>".
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed4 years ago.Improve this question I currently learning the C programming language and I am not sure of what the width in a float is? I have changed the precision of the float already and it added0after the.and when I changed the value of the width it just added blank spaces behind ``` new_price = price + increase; printf("New price is %4.2f", new_price); return 0; ```
The4in"%4.2f"is thewidth. It directsprintf()to add spaces per: If the converted value has fewer characters than the field width, it is padded with spaces (by default) on the left ...
I have a struct to represent an AST, and I'm on an embedded device, I have no malloc, everything should be either on stack or global. So my struct; ``` /* AST Structre */ typedef struct ast { uint8_t type; /* This is the token value in grammar.h */ /* Value of the token */ union { double number; char literal; } value; struct ast *left; /* left hand side of the node */ struct ast *right; /* right hand side of the node */ } ast_t; ``` My question is whats the best way to use recursive structs without malloc.
Simply create an array and initialize/assign as needed. ``` ast_t fred[] = { { 1, {2.0}, NULL, &fred[1]}, { 3, {4.0}, &fred[0], NULL } }; ``` Call theast_tfunctionsfoo(fred);. Be sure to not callfree(fred).
For a predefined function where are the declaration and definition stored? And is the declaration stored in libraries? If so, then why it is named library function?
This is an imprecise question. The best answers we can give are: The declaration of standard library functions can best be thought of as being stored in their header files.Depending on how you want to think about it, the definition of standard library files is either in the source files for those libraries (which may be invisible to you, a trade secret of your compiler vendor), or in the library files themselves (.a,.so,.lib, or.dll).These days, knowledge of standard library functions is typically built in to the compiler, also. For example, if I write the old classicint main() { printf("Hello, world!\n"); }, but without any#includedirectives, my compiler says, "warning: implicitly declaring library function 'printf'" and "include the header <stdio.h>".
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed4 years ago.Improve this question I currently learning the C programming language and I am not sure of what the width in a float is? I have changed the precision of the float already and it added0after the.and when I changed the value of the width it just added blank spaces behind ``` new_price = price + increase; printf("New price is %4.2f", new_price); return 0; ```
The4in"%4.2f"is thewidth. It directsprintf()to add spaces per: If the converted value has fewer characters than the field width, it is padded with spaces (by default) on the left ...
I have a struct to represent an AST, and I'm on an embedded device, I have no malloc, everything should be either on stack or global. So my struct; ``` /* AST Structre */ typedef struct ast { uint8_t type; /* This is the token value in grammar.h */ /* Value of the token */ union { double number; char literal; } value; struct ast *left; /* left hand side of the node */ struct ast *right; /* right hand side of the node */ } ast_t; ``` My question is whats the best way to use recursive structs without malloc.
Simply create an array and initialize/assign as needed. ``` ast_t fred[] = { { 1, {2.0}, NULL, &fred[1]}, { 3, {4.0}, &fred[0], NULL } }; ``` Call theast_tfunctionsfoo(fred);. Be sure to not callfree(fred).
For a predefined function where are the declaration and definition stored? And is the declaration stored in libraries? If so, then why it is named library function?
This is an imprecise question. The best answers we can give are: The declaration of standard library functions can best be thought of as being stored in their header files.Depending on how you want to think about it, the definition of standard library files is either in the source files for those libraries (which may be invisible to you, a trade secret of your compiler vendor), or in the library files themselves (.a,.so,.lib, or.dll).These days, knowledge of standard library functions is typically built in to the compiler, also. For example, if I write the old classicint main() { printf("Hello, world!\n"); }, but without any#includedirectives, my compiler says, "warning: implicitly declaring library function 'printf'" and "include the header <stdio.h>".
Suppose I have the following which allows the entering in of text: ``` printf("Enter in your text\n"); while ((c=getchar()) != EOF) { putchar(c); if (last_char) // the last character before the user presses enter. do_something(); } ``` Is there a way for me to detect if the character is the last one in the text input (without getting out of the loop)? Or is that not possible the current organization of things above?
Something list this? ``` printf("Enter in your text\n"); int c,last_char; do { c = getchar(); if (c == '\n') { // it's the last char... do something with last_char printf("\nThe last char was: %c\n", last_char); } last_char = c; } while (c != EOF); ```
I'm trying to usesscanfto convert a single character from a string into its corresponding hex value. ``` #include <stdio.h> int main () { char *str = "DEADBEEF"; int num; sscanf(str[2],"%x",&num); printf("%x",num); } ``` When I try to compile, I get a warning becausesscanfis looking for achar *rather than a singlechar. I could use the ampersand to get the address of the character (i.e.&str[2]) but that would read the rest of the string until it encounters a\0.
Solved bylurkerin acomment: Usingsscanf(&str[2], "%1x", &num);you can read a single character rather than as large of an integer assscanfcan read
I am reading a text file, which gives me 4 arguments from every line. suppose it's arg1, arg2,arg3,arg4. This while loops reads every line in the file and gives 4 arguments from every line till !feof. So, every time we get 4 arguments, I need to store it in a 2D array.... also how can I access it later? I defined an array calledWall[500][4](500 is just the large number that I took and 4 is the argument which we get each time). thenwall[counter1][counter2] = {{arg1,arg2,arg3,arg4}}; c1++; c2++; ``` double wall[500][4]; wall[counter1][counter2] = {{arg1,arg2,arg3,arg4}}; counter1++ counter2++; ``` error: expected expression before ‘{’ tokenwall[counter1][counter2] = {{arg1,arg2,arg3,arg4}};
You can simply add values like that: ``` double wall[500][4]; wall[counter1][0] = arg1; wall[counter1][1] = arg2; wall[counter1][2] = arg3; wall[counter1][3] = arg4; counter1++; ```
If acharis a small integer, why can it contain symbols?
charis a single byte integer, which means at least 256 possibilities (assuming the compiler follows the c standard). The lower 128 (number 0-127 inclusive) include almost all "symbols" you see printed. Here's a list:https://www.asciitable.com/ This often does not include more complicated characters, commonly called "multi-byte characters" which consist of more then 8 bits, such as emojis and eastern Asian word-characters. Different systems have different ways of handling these, but very few use thechartype in C for more then one byte characters. As a general rule, treat achar/byte like it is exactly 8 bits. Though some systems may allowcharto be bigger, that's not always the case. Use the platform-specific type for multi-byte characters if you want to use them.
I am calling C functions in a 3rd party library, which return complex numbers using a custom type: ``` typedef struct { double dat[2]; } complex_num; ``` Here, dat[0] is the real part and dat[1] is the imaginary part. I want to safely and portably cast these to the Ccomplex doubletype to use optimized math operations like add/multiply etc. Suppose I have a function returningcomplex_num: ``` complex_num dostuff(...); ``` My question is, can I safely do the following: ``` complex double a = (complex double) dostuff(...); ``` Are there any issues with array padding/alignments which would screw up the above cast?
Write yourself a conversion function: ``` complex double MyCast(complex_num x) { return CMPLX(x.dat[0], x.dat[1]); } ``` CMPLXis a standard macro, defined in<complex.h>. Apple LLVM 10.0.1 with clang-1001.0.46.4 and GCC 9.1 optimize this use ofCMPLXto no operation, at least in one scenario I tested.
If acharis a small integer, why can it contain symbols?
charis a single byte integer, which means at least 256 possibilities (assuming the compiler follows the c standard). The lower 128 (number 0-127 inclusive) include almost all "symbols" you see printed. Here's a list:https://www.asciitable.com/ This often does not include more complicated characters, commonly called "multi-byte characters" which consist of more then 8 bits, such as emojis and eastern Asian word-characters. Different systems have different ways of handling these, but very few use thechartype in C for more then one byte characters. As a general rule, treat achar/byte like it is exactly 8 bits. Though some systems may allowcharto be bigger, that's not always the case. Use the platform-specific type for multi-byte characters if you want to use them.
I am calling C functions in a 3rd party library, which return complex numbers using a custom type: ``` typedef struct { double dat[2]; } complex_num; ``` Here, dat[0] is the real part and dat[1] is the imaginary part. I want to safely and portably cast these to the Ccomplex doubletype to use optimized math operations like add/multiply etc. Suppose I have a function returningcomplex_num: ``` complex_num dostuff(...); ``` My question is, can I safely do the following: ``` complex double a = (complex double) dostuff(...); ``` Are there any issues with array padding/alignments which would screw up the above cast?
Write yourself a conversion function: ``` complex double MyCast(complex_num x) { return CMPLX(x.dat[0], x.dat[1]); } ``` CMPLXis a standard macro, defined in<complex.h>. Apple LLVM 10.0.1 with clang-1001.0.46.4 and GCC 9.1 optimize this use ofCMPLXto no operation, at least in one scenario I tested.
I have Simulink Embedded Coder output model code. One of header file includes; ``` #ifndef rtmGetU #define rtmGetU(rtm) ((rtm)->ModelData.inputs) #endif ``` After saw the code block in the header, I tried to generate my own Simulink model embedded code but the output not include thertmGetUdefine. I wonder what is the purpose of thertmGetUdefine and how can I generate thertmGetUcode for my own model.
rtmGetUis a macro for conveniently getting the data that is being fed into anyInports in the model that the code is generated from. It will only be in the generated code if your model has any Inports (at the highest level of the model.)
I have the following macro: ``` #define oslock_TryAcquire(pLock) { \ INITIALIZED_ASSERT(pLock) \ acquire(pLock)} ``` While compiling I get : ``` error: expected expression before ‘{’ token #define oslock_TryAcquire(pLock ) { \ ``` Upd:^ I get the "follow-up" error : ``` note: in expansion of macro ‘oslock_TryAcquire’ if(!oslock_TryAcquire(&pLock)){ ^~~~~~~~~~~~~~~~~~~~~~ ``` I can`t understand what is a problem? Will be glsd to get advices
Macros are kind of a glorified text replacement. Your call ``` if(!oslock_TryAcquire(&pLock)) ``` expands to ``` if(!{INITIALIZED_ASSERT(&pLock) acquire(&pLock)}) ``` which is nonsense syntax in several different ways. Use a function instead of a macro.
When printing the values of reading input from the user, the numbers underflowing and overflowing, and I don't understand why. So I am going through the ansi C standard to just pick up c as a language, and I do not understand why this is underflowing and overflowing the first two values. ``` int c; int nl, bl, tab= 0; while ((c = getchar())!= EOF){ if (c == '\n'){ ++nl; } if (c == ' '){ ++bl; } if (c == '\t'){ ++tab; } printf("%d\t %d\t %d\n", nl, bl, tab); } ```
This here int nl, bl, tab= 0; Setstabto0, but doesn't initializenlandblin any way. Thus it's undefined behavior when they are increased later. Try this instead: ``` int nl = 0, bl = 0, tab = 0; ```
How do i connect to Tor via TCP in C or Rust, without having the Tor browser installed, in my windows pc?
Both of the Txtorcon and Stem libraries require a Tor binary already installed though. It is possible to use the Tor included with the Tor Browser Bundle, connecting on port 9150 (with control port of 9151). Better yet though, you can download the"Expert Bundle"to get the Tor binary without any browser.The expert bundle connects to the Tor network and allows you to make SOCKS5 connections and control port connections. You can control everything it does via the config file or in real time through a 'Tor controller' on the control port.You can download it fromDownload|Mirror 1
This question already has answers here:Why is return 0 optional?(4 answers)Closed4 years ago. What is the use ofreturn(0)in C? I have written programs which work fine without using it. Please explain it to me in a simplified manner, since I'm a beginner in C. If the answer is complex it might confuse me even more... ``` #include <stdio.h> #include <stdlib.h> int main() { float km, meter, feet, inch, cm; printf("Enter the distance(must be in km: \n"); scanf("%f", &km); cm = 100000*km; inch = 39370.1*km; meter = 1000*km; printf("The distance between the cities in cm is %f \n", cm); printf("The distance between the cities in inches is %f \n", inch); printf("The distance between the cities in meters is %f \n", meter); } ```
This is to say if the program success or failed . You can also usereturn EXIT_SUCCESS;orreturn EXIT_FAILURE; You can check the return like this :
This is an extract of the officialATMEGA328p data sheetpage 261: As the documentation say ``` Vin * 1024 ADC = ---------- Vref ``` What I don't understand is an analog pin can provide us 10bits. That's mean a value between 0x0 and 0x3ff (1023) So I don't understand why the documentation sayVin * 1024and not 1023. Because for me 0v = 0 and 5v = 1023?
0 counts as a valid reading. 1..1023 is 1023 steps and plus 0 that makes 1024. 0x000 represents analog ground, and 0x3FF represents the selected reference voltage minus one LSB. In reality, ADCs are not perfect as results can have more than 1 count of error and it really does not matter much if 1023 or 1024 is used. In theory using 1024 is more accurate.
This question already has answers here:Why is return 0 optional?(4 answers)Closed4 years ago. What is the use ofreturn(0)in C? I have written programs which work fine without using it. Please explain it to me in a simplified manner, since I'm a beginner in C. If the answer is complex it might confuse me even more... ``` #include <stdio.h> #include <stdlib.h> int main() { float km, meter, feet, inch, cm; printf("Enter the distance(must be in km: \n"); scanf("%f", &km); cm = 100000*km; inch = 39370.1*km; meter = 1000*km; printf("The distance between the cities in cm is %f \n", cm); printf("The distance between the cities in inches is %f \n", inch); printf("The distance between the cities in meters is %f \n", meter); } ```
This is to say if the program success or failed . You can also usereturn EXIT_SUCCESS;orreturn EXIT_FAILURE; You can check the return like this :
This is an extract of the officialATMEGA328p data sheetpage 261: As the documentation say ``` Vin * 1024 ADC = ---------- Vref ``` What I don't understand is an analog pin can provide us 10bits. That's mean a value between 0x0 and 0x3ff (1023) So I don't understand why the documentation sayVin * 1024and not 1023. Because for me 0v = 0 and 5v = 1023?
0 counts as a valid reading. 1..1023 is 1023 steps and plus 0 that makes 1024. 0x000 represents analog ground, and 0x3FF represents the selected reference voltage minus one LSB. In reality, ADCs are not perfect as results can have more than 1 count of error and it really does not matter much if 1023 or 1024 is used. In theory using 1024 is more accurate.
This is an extract of the officialATMEGA328p data sheetpage 261: As the documentation say ``` Vin * 1024 ADC = ---------- Vref ``` What I don't understand is an analog pin can provide us 10bits. That's mean a value between 0x0 and 0x3ff (1023) So I don't understand why the documentation sayVin * 1024and not 1023. Because for me 0v = 0 and 5v = 1023?
0 counts as a valid reading. 1..1023 is 1023 steps and plus 0 that makes 1024. 0x000 represents analog ground, and 0x3FF represents the selected reference voltage minus one LSB. In reality, ADCs are not perfect as results can have more than 1 count of error and it really does not matter much if 1023 or 1024 is used. In theory using 1024 is more accurate.
I'm trying to do some simple linked list practices to familiarize myself with C. I currently have the following makefile. ``` CC=gcc CFLAGS=-Wall app: linked_list.o app.c $(CC) $(CFLAGS) linked_list.o app.c -o app node.o: node.h $(CC) $(CFLAGS) -c node.c linked_list.o: linked_list.h $(CC) $(CFLAGS) -c linked_list.h -o app ``` When I run it I get this: gcc: error: linked_list.o: No such file or directory I've tried reordering node.o and linked_list.o, but nothing worked.
You need to compile the.cfile, not.h; and get rid of-o app. ``` linked_list.o: linked_list.c linked_list.h $(CC) $(CFLAGS) -c linked_list.c ``` Make sure to list both the.cand.hfiles as dependencies, both here and withnode.o: ``` node.o: node.c node.h $(CC) $(CFLAGS) -c node.c ```
I have this really large if statement and it does not look pleasing to the eye as well as not being as efficient as possible. I'm making a program that (depending on the users input) runs a certain block of code, for example if the user inputs'a'the program runs a code that adds something to a file etc. By the way this is in a do-while statement(I don't know if this is relevant though). ``` else if(ansr != 'a' && ansr != 'A' && ansr != 'r' && ansr != 'R' && ansr != 's' && ansr != 'S' && ansr != 'e' && ansr != 'E') { printf("Invalid input!\n"); } ``` As you can see this is a really long if statement and I would like it to be shorter. Thank you
Um, what an example, whatever. Why don't you usestrchr?strchrreturns the pointer to a character in a string (if found), NULL otherwise. ``` else if (strchr("aArRsSeE", ansr) == NULL) { printf("Invalid input!\n"); } ```
I need some help with a part of my Programm. I want to call a functionEXACTLY every x seconds. The problem with the most soultions is, that the time to call the sleep() or w/e function stacks over time. An example: If I want to call a function every second with sleep(1), it takes 1 second + a very smallx(time to call the sleep() function). So it takes 1,xseconds. Not 1,0 second. Over a long period of time thex stacks to a "huge amount" of time. I want a code snippet which executes something EXACTLY every second so that I get exact timestamps without any additional delay. I think it's part of the real-time-programming problem. Is there some working code out there for that? Please help me out with that. :) FloKL
``` int X = 10; int t1 = (int)time(NULL); while(1==1){ // execute your process ... // calculate next tick t1 = t1 + X; sleep(t1 - (int)time(NULL)); } ```
Trying to print float number in hexadecimal format: ``` int main() { float a = 1.1; printf("%f %X\n", a, a); } ``` For some reason printf returns this: ``` 1.100000 A878DAC8 // hex number is random every time ``` It should be 3F8CCCCD. Why does it have such behavior?
The explanation for the observed behavior is given in Govind Parmar's answer. Note that you might get the behavior you expect with this modified program, assuming 32-bit ints and floats: ``` #include <stdio.h> #include <string.h> int main() { int i; float a = 1.1; memcpy(&i, &a, sizeof(i)); printf("%f %X\n", a, i); return 0; } ``` Output:1.100000 3F8CCCCD
The documentation is: In C, the "main" function is treated the same as every function, it has a return type (and in some cases accepts inputs via parameters). The only difference is that the main function is "called" by the operating system when the user runs the program. Thus the main function is always the first code executed when a program starts. But when I run ``` int main() { printf("%d", square(3)); return 0; } int square(int n) { int sq = n * n; return sq; } ``` the program prints 9. So does the main() function get executed only after all the other functions or is it special in a different way?
The order is this: OS callsmain()main()callssquare(3).square(3)calculates the result9and returns it.main()callsprintf("%d", 9)printf()prints9on the terminal and returns the number of characters printed (1).main()returns 0 to the OS.
Is this valid C99 code? (I guess I'm asking whether it's portable) ``` void test(void){ return; } void (*fp)(void) = test; if (fp == test){ <--- This line printf("Success\n"); } ``` I gather only pointers of the same type can be compared with one another, so maybe my question is whether function names like 'test' are just pointer aliases? Or maybe someone can tell me what my question is better than I can :)
The code is valid ANSI C. Actually what happens is, a function name such astestin your code, is automatically converted to a pointer to function. You could changetestto&test, the result is the same.
I'm working with char arrays in C. I'm setting the size in a previous step. When I print it out it clearly shows the num_digits as 1. But then when I put it in to set the size of a char array to make it a char array of size num_digits, its setting the size of the array as 6. In the next step when I print strlen(number_array), it prints 6. Printing it out I get something with a lot of question marks. Does anyone know why this is happening? ``` int num_digits = get_num_digits(number); printf("Num digits are %d\n", num_digits); char number_array[num_digits]; printf("String len of array: %d\n", strlen(number_array)); ```
You need to null terminate your array. ``` char number_array[num_digits + 1]; number_array[num_digits] = '\0'; ``` Without this null terminator, C has no way of know when you've reached the end of the array.
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in thehelp center.Closed4 years ago.Improve this question I am trying to print char * name; I have tried that ``` fprintf(stderr,"%c",* name) ``` But it doesn't seem to work. My reasoning was that since name is a character pointer I could use * to get the value for the pointer. It gives the error error: format specifies type 'char *' but the argument has type 'char'
Here you are ``` #include <stdio.h> int main(void) { char *name = "TriposG"; fprintf( stderr, "%s", name ); return 0; } ``` As for this statement ``` fprintf( stderr, "%c", *name); ``` then it outputs the first character of the string pointed to by the pointername.
I have a very light Linux OS that does not have any compiler on it. How can I install gcc or g++ on it? The target hardware is an armv7-a processor. Can I compile gcc on my x86 system and then install it on my armv7 Linux??
Yes, you can compile your code on your x86 device and then export it to your arm device. But for this, you need a special compiler. This process is called "cross-compilation", where you compile a code for a special target device on an other device. For arm devices, the one I used was the "arm-linux-gnueabihf-gcc" compiler. Once installed, you can use it just like your casual gcc compiler. For example, on linux, it would be something like this : $ arm-linux-gnueabihf-gcc -o your_program your_program.c You then export the compiled output to your device, and it should work.
I'm writing a C program where I use a header to declare some functions and define several constants. When I use these constants in my code, I get the errorSymbol 'FOO' could not be resolved. I have no problems with the declared functions. I am using Eclipse Neon. I have already verified that the path to the directory containing the header files is added to the Include Path. And I have also restarted Eclipse. header.h ``` #ifndef __header_h_ #define __header_h_ #define FOO 0x00 #define BAR 0x01 void do_stuff(int x); #endif ``` main.c ``` #include <stdio.h> #include "header.h" int main() { do_stuff(FOO); return 0; } ``` ERROR: Symbol 'FOO' could not be resolved What am I missing here?
Right Click on the ProjectIndex > Freshen All Filesand thenIndex > Rebuildfixed the problem
I am learning C and use VS 2019 community edition. While learning C I do not want to use any C++ features accidentally, like declaring the for variable inside the for. E.g. right now this code compiles: ``` for (int i = 0; i < 100; ++i) { ... } ``` But it is not C, it is C++ and I wish the compiler to tell me that. Is it possible?
Yes, Visual Studio enforces C compiler by file extension. If it meets .c, then it switches to using of C compiler. There is no option to say VS C compiler which C standard should be used. VS mostly conforms to C99, and doesn't fully support the latest C11. It is due to the fact that VS compiler is C++ compiler, and C programming language support is in the shadow. Here is the better answerIs there any option to switch between C99 and C11 C standards in Visual Studio?
I want to register my Application (its a Gtk Application) to receive a signal when the user presses for example the "Next Song" Button, while it is not focused, so the User can change the playback while the Application remains in the background. I have no idea how to do this - will I need to include a specific Library for doing this on Ubuntu 18.04? Just to clarify: I am talking about System-Wide Hotkeys that applications can somehow intercept.
There isn't really a generic mechanism for this in Wayland (the security issues should be pretty obvious); for X, see theXGrabKeyfunction. For multimedia keys, there is a D-Bus interface you can use at org.gnome.SettingsDaemon.MediaKeys. For an example of how to use it, take a look atplugins/nmkeys/rb-mmkeys-plugin.c in Rhythmbox.
I'm writing GTK application with C. I wanted to add sound after clicking the button. I wanted to do it with as little effort as possible so i used the Bell sign from ascii (7), so it looks like this: ``` void infButtonClick() { char d = (char)7; printf("%c\n", d); //Rest of the code } ``` It's working fine except one situation. The application is added to Startup Applications and when it starts this way the bell sound doesn't work. Other sounds in the application (videos played with libvlc) works fine. So where is the problem here? What should I change to make a bell sign work after automatic start up?
As you are using GTK, the easiest way to produce a beep is withgtk_widget_error_bell(). Seedocumentation
I'm writing GTK application with C. I wanted to add sound after clicking the button. I wanted to do it with as little effort as possible so i used the Bell sign from ascii (7), so it looks like this: ``` void infButtonClick() { char d = (char)7; printf("%c\n", d); //Rest of the code } ``` It's working fine except one situation. The application is added to Startup Applications and when it starts this way the bell sound doesn't work. Other sounds in the application (videos played with libvlc) works fine. So where is the problem here? What should I change to make a bell sign work after automatic start up?
As you are using GTK, the easiest way to produce a beep is withgtk_widget_error_bell(). Seedocumentation
``` typedef struct class { ... }Class; typedef struct node { Class data; struct node *next; }Node; Node* newNode() { Node* temp = (Node*)malloc(sizeof(Node)); temp -> data = malloc(sizeof(Class)); temp -> next = NULL; return temp; } ``` The compiler says there is a problem with the line:temp -> data = malloc(sizeof(Class));, specifically "incompatible types in assignment". What am I doing wrong?
You're saying thatdatais aClassbut you're trying to assign it aClass*.
Why here p->p1 is 1 rather than 0? I thought p is pointer to struct s2, and s2.p1=0, so p->p1 should be 0 too? ``` #include <stdio.h> #include <stdlib.h> struct S1 { int p1,p2; }; struct S2 { int p1; struct S1 s1; int p2; }; int main(void) { int s=0; struct S2 s2 = {1, 2, 3, 4}; struct S2 *p; p=(struct S2 *)malloc(sizeof(struct S2)); *p = s2; s2.p1 = 0; s=p->p1 + s2.p1 + p->p2 + p->s1.p2; free(p); printf("%d", s); return 0; } ``` I expected the output of 7, but the actual output is 8.
pisn't actually pointing tos2!. You've copieds2into the address allocated atp. If you wantpto point tos2, don'tmallocit. Rather, simply saystruct S2 *p = &s2;.
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.Closed4 years ago.Improve this question I need to check if installed Python version is 32 bit or 64 bit using my C program running in Windows 10, not in my Python program. How can I check the Python architecture using C code?
``` char *cmd = "python -c \"import sys,platform ;exit(platform.architecture()[0]==\"32bit\")\"" int ret = system(cmd); ``` ret will be 1 for 32 bit and 0 for 64
I searched thoroughly but could not find the solution to this: Assumingsizeof(int) = 4, we define: ``` int a[10] = {0}; ``` What is the output of the following:1.sizeof(&a)2.sizeof(*a)3.sizeof(a) I know thatsizeof(a)is equal tosizeof(int) * 10 = 40.I also understand that*ais actually a the first element in the array, thereforesizeof(*a)is actually size of theintwhich resides in there, i.e.4. However, after running the code, I do not understand why size of&ais8. I know that the'&'operator returns the address of the variablea, but why thesizeofthe address is8?
The size of the address depends on your architecture and is not directly related to the size of anintitself. So it’s 8 in your case, which seems pretty normal (64 bits).
``` typedef struct class { ... }Class; typedef struct node { Class data; struct node *next; }Node; Node* newNode() { Node* temp = (Node*)malloc(sizeof(Node)); temp -> data = malloc(sizeof(Class)); temp -> next = NULL; return temp; } ``` The compiler says there is a problem with the line:temp -> data = malloc(sizeof(Class));, specifically "incompatible types in assignment". What am I doing wrong?
You're saying thatdatais aClassbut you're trying to assign it aClass*.
Why here p->p1 is 1 rather than 0? I thought p is pointer to struct s2, and s2.p1=0, so p->p1 should be 0 too? ``` #include <stdio.h> #include <stdlib.h> struct S1 { int p1,p2; }; struct S2 { int p1; struct S1 s1; int p2; }; int main(void) { int s=0; struct S2 s2 = {1, 2, 3, 4}; struct S2 *p; p=(struct S2 *)malloc(sizeof(struct S2)); *p = s2; s2.p1 = 0; s=p->p1 + s2.p1 + p->p2 + p->s1.p2; free(p); printf("%d", s); return 0; } ``` I expected the output of 7, but the actual output is 8.
pisn't actually pointing tos2!. You've copieds2into the address allocated atp. If you wantpto point tos2, don'tmallocit. Rather, simply saystruct S2 *p = &s2;.
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.Closed4 years ago.Improve this question I need to check if installed Python version is 32 bit or 64 bit using my C program running in Windows 10, not in my Python program. How can I check the Python architecture using C code?
``` char *cmd = "python -c \"import sys,platform ;exit(platform.architecture()[0]==\"32bit\")\"" int ret = system(cmd); ``` ret will be 1 for 32 bit and 0 for 64
I'm trying to pass a Go function to a C function. Something like: ``` stm := C.struct_tray_menu{ .... fn: // definition of method .... } C.menu_cb(stm); ``` and pass that into a C function: ``` static void menu_cb(struct tray_menu *item) { (void)item; printf("menu: clicked on %s\n", item->text); } ``` I'd just like to know how to define something like C.function.
the main problem is misunderstanding of definition of go in c. so final code is look like ``` //export callOnMeGo func callOnMeGo(in int) int { fmt.Printf("Go.callOnMeGo(): called with arg = %d\n", in) return in+ 1 } func main() { C.some_c_func((C.callback_fcn)(unsafe.Pointer(C.callOnMeGo_cgo))) //dont forget to use (funcDefinedInGO_cgo) for with postfix _cgo ... ```
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.Closed4 years ago.Improve this question As far as I know, it is almost true that any code that can be represented in the LLVM intermediate language, can also be represented in C, with two important exceptions: Exceptions. (No pun intended.)Signed integer arithmetic with well-defined behavior on overflow. Is there anything else that can be represented in LLVM but not in C?
In addition to exception handling, otherbig featuresaregarbage collectionand out-of-the-boxcoroutines. Going to a lower level, there aretrampoline intrinsics,patch points for JITs, and direct support forObj-C ARC Runtime intrinsics. C is Turing complete, so all of these things can be introduced to C with libraries and so on, but I put them as they are part of the LLVM language.
I wrote an algorithm that sorts elements in an array. Now I'm trying to solve it by taking elements from input but the compiler gives me this error -> "Core Dump (Segmentation fault)" ``` int array[100]; int num; printf("How many elements do you want to insert? --> "); scanf("%d", num); for(int i=0; i<num; i++){ printf("Insert the element --> "); scanf("%d", &array[i]); } for(int i=0; i<num; i++){ for (int j=i+1; j<num; j++){ if (array[i] > array[j]){ int tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } } for(int i=0; i<num; i++){ printf("%d\n", array[i]); } ```
Right here: ``` scanf("%d", num); ``` You need to pass a pointer to anint. This should be: ``` scanf("%d", &num); ```
i write a program in atmel studio for my avr atmega 32 ic. By keypad enter a number between 0 to999. I want to display it on lcd. My problem is: lcd take only char and string.i store the entered number in a int variable. How can i convert it to string or char. I writted this function; Y is entered number by keypad that is int: ``` char str; itoa(y,str,10); alcd_putc(str); ``` Bu it dosent work. Help me thanks.
Usealcd_putsfunction like following: ``` char str[5]; //< Use a array of char itoa(y,str,10); alcd_puts(str); ```
I need to install headers from curl source so I can use a function added recently. Source is downloaded and compiled What to do with files?
Cheap way: Copy the headers to where you need them. Professional way: From the patched sources build the (patched) dev-package using your OS/distro's package manager tools and install it. Misread the question. To include the curl headers and to link againstliccurlinstall the related dev-package using your distro's package manager. For Debian based systems this were: aptitudeaptgetdpkg... Please note that there might be several dev-package using different authentication/encryption libraries. libcurl4-gnutls-devlibcurl4-openssl-dev... You need to decide which one you prefer.
On Linux. Hi. I'm sure there are many factors involved where the OS simply garbage-dumps memory allocated with memset() without calling free(), but I was wondering if anyone has a good estimation on this? That's really all I want to know. There is a functionality in linux called KSM that saves memory space by combining matching data. My question revolves around detecting if KSM is working or not by checking the write time of the data. I have already successfully tested this on a machine while running everything in one program. Now I want to upload to memory, close the program, then open another program and test for memory duplication. Thanks! -Taylor
memset does not allocate memory, malloc doesthe memory is not freed until a free call or the process terminatesthere is no abstract machine in C, that the design principle of the language
I know that in C the compiler is not allowed to reorder struct fields and that this is important to the memory layout and alignment of the struct. I am a beginner in Rust, and since it seems that for the most part raw pointers are hidden (I know you can still use them) if rustc is allowed to reorder the fields from their declared order in a struct.
From therust reference struct.md: The memory layout of astructis undefined by default to allow for compiler optimizations like field reordering, but it can be fixed with thereprattribute. In either case, fields may be given in any order in a corresponding struct expression; the resultingstructvalue will always have the same memory layout.
I wrote an algorithm that sorts elements in an array. Now I'm trying to solve it by taking elements from input but the compiler gives me this error -> "Core Dump (Segmentation fault)" ``` int array[100]; int num; printf("How many elements do you want to insert? --> "); scanf("%d", num); for(int i=0; i<num; i++){ printf("Insert the element --> "); scanf("%d", &array[i]); } for(int i=0; i<num; i++){ for (int j=i+1; j<num; j++){ if (array[i] > array[j]){ int tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } } for(int i=0; i<num; i++){ printf("%d\n", array[i]); } ```
Right here: ``` scanf("%d", num); ``` You need to pass a pointer to anint. This should be: ``` scanf("%d", &num); ```
i write a program in atmel studio for my avr atmega 32 ic. By keypad enter a number between 0 to999. I want to display it on lcd. My problem is: lcd take only char and string.i store the entered number in a int variable. How can i convert it to string or char. I writted this function; Y is entered number by keypad that is int: ``` char str; itoa(y,str,10); alcd_putc(str); ``` Bu it dosent work. Help me thanks.
Usealcd_putsfunction like following: ``` char str[5]; //< Use a array of char itoa(y,str,10); alcd_puts(str); ```
I need to install headers from curl source so I can use a function added recently. Source is downloaded and compiled What to do with files?
Cheap way: Copy the headers to where you need them. Professional way: From the patched sources build the (patched) dev-package using your OS/distro's package manager tools and install it. Misread the question. To include the curl headers and to link againstliccurlinstall the related dev-package using your distro's package manager. For Debian based systems this were: aptitudeaptgetdpkg... Please note that there might be several dev-package using different authentication/encryption libraries. libcurl4-gnutls-devlibcurl4-openssl-dev... You need to decide which one you prefer.
On Linux. Hi. I'm sure there are many factors involved where the OS simply garbage-dumps memory allocated with memset() without calling free(), but I was wondering if anyone has a good estimation on this? That's really all I want to know. There is a functionality in linux called KSM that saves memory space by combining matching data. My question revolves around detecting if KSM is working or not by checking the write time of the data. I have already successfully tested this on a machine while running everything in one program. Now I want to upload to memory, close the program, then open another program and test for memory duplication. Thanks! -Taylor
memset does not allocate memory, malloc doesthe memory is not freed until a free call or the process terminatesthere is no abstract machine in C, that the design principle of the language
I know that in C the compiler is not allowed to reorder struct fields and that this is important to the memory layout and alignment of the struct. I am a beginner in Rust, and since it seems that for the most part raw pointers are hidden (I know you can still use them) if rustc is allowed to reorder the fields from their declared order in a struct.
From therust reference struct.md: The memory layout of astructis undefined by default to allow for compiler optimizations like field reordering, but it can be fixed with thereprattribute. In either case, fields may be given in any order in a corresponding struct expression; the resultingstructvalue will always have the same memory layout.
Given the following C code snippet: ``` printf("value: %lf\n", (double) ceil(((double) 100) / ((double) 2))); ``` When compiling this code with Visual Studio 2010 C compiler in64 bitand running it afterward, it gives the expected result: ``` value: 50.000000 ``` However, when compiling the same code with Visual Studio 2010 C compiler this time in32 bitand running it afterward, it gives an unexpected result: ``` value: 1028.000000 ``` Any hints why this unexpected value?
As mentioned above, you forgot to#include <math.h>and that leads to undefined behavior I believe if you turn on all warnings you'll get the root cause right away
I am compiling my application code on Solaris 5.11, Code is written in C.In the application code I used "fdio" related code. The Solaris box do not have that . How to get the sys/fdio package. ``` #include <stdio.h> #include <sys/fdio.h> int main() { printf("Hello World"); } ``` "test1.c", line 2: cannot find include file:
The file is no longer available in Solaris 11.Here is a copythat will help you compile your code. Drop it in/usr/include/sysIt is opensource so there should be a few copies out there.
I'm try to use system("echo 1 > /sys/class/afile") to set a file to 1. If I use it on console it works well, but if I run my C program it shows me: ``` sh: echo: I/O error ``` I already try to set it with following code: ``` char i[1]; i[0]=1; int fd1 = open("/sys/class/afile",O_CREAT | O_WRONLY); int ret = write(fd1,i,strlen(i)); if(ret > 0) printf("Ok\n"); else printf("nOk\n"); close(fd1); ``` The result is "Ok" but the file didn't change.
strlen(i)yields undefined behavior becauseiis not a string; the array lacks room for null termination. Also,i[0]=1;does not put a'1'character in the array, but rather puts a byte with value 1, which is a "^Acharacter". Instead trywrite(fd, "1", 1)- no need for any variables orstrlen.
When finding the space complexity of a given code sample does the return type of a function affects the space complexity? Assume that size ofintis2 bytesand size offloatis4 bytes. What is the space complexity for the following code sample? ``` int area(int height, float width) { return height * width; } ```
Auxiliary Spaceis the extra space or temporary space used by an algorithm. Space Complexityof an algorithm is total space taken by the algorithm with respect to the input size. Space complexity includes both Auxiliary space and space used by input. So, the answer is yes. The return type is also taken into account while considering space complexity.