question
stringlengths
25
894
answer
stringlengths
4
863
I am currently reading the manpages abouttime.h. I got this far: ``` time_t now = time(0); struct tm * local = localtime(&now); ``` Now I can work with the time, as far as good, but I do not find the information if its my duty tofree()the variablelocalor not.
Quoting theman page The four functionsasctime(),ctime(),gmtime()andlocaltime()return a pointer to static dataand hence are not thread-safe. [...] So, you need notfree()the returned pointer.
I want to know when anUPDATEquery reports 0 rows matches. I'm usinglibmysql. Here's the code I'm using: ``` char query[300] = {0}; snprintf(query, 300, "UPDATE `my_table` SET name='%s' WHERE id=%d", name, id); if (mysql_query(db, query)) { printf("Error!\n"); } ``` Essentially what I need to know is w...
Checkmysql_affected_rows. This will return number of modified rows by the last query. However, it may return just the rows actually modified. If you want to return matched row, you have to specifyCLIENT_FOUND_ROWSinmysql_real_connect. Check the same page for details.
I have a small Linux project written in C is it possible to analyze it with a SonarQube?
According tohttps://en.wikipedia.org/wiki/SonarQube, it support c/c++, and is cross-platform, so you can do it I think.
I came accross this statement: ``` time_t time = x / 1000LL; ``` So what does thisLLactually mean?
Copy-pasted fromthis question, which seems to be the exact same one with theULLsuffix : From thegccmanual:ISO C99 supports data types for integers that are at least 64 bits wide, and as an extension GCC supports them in C90 mode and in C++. Simply writelong long intfor a signed integer, orunsigned long long i...
``` #include <stdio.h> int main() { char a[8]; printf("%d\n",a) ; return 0; } ``` For the above code the output was this :- 2686744 What is the reason behind this output? I found that the output doesn't depend on the content of the array, but on the size of the array.I just want the expla...
``` char a[8]; printf("%d\n",a); ``` This code has undefined behavior. The array expressionais implicitly converted to achar*value, equivalent to&a[0]. That value is then passed toprintf-- but since the%dformat requires anintargument, the behavior is undefined. Ifintandchar*happen to have the same size, and if ...
Say I have this string:"this","is a, string" I want to be able to check if a comma is inside a pair of quotation marks. The first comma is not, whereas the second comma is. How could I achieve this in C?
The way I would do it is : initialize a boolean variable named likequotesOpento a falsy valuego char by char through the string until you find\0, and toggle the boolean if the char is"when you encounter a comma, check the state of your boolean to know if it is in quotes or not
Is there a simple lexer/parser for C language or a subset of it which is based on Flex/Bison? I have found some open source parsers for C (TCC, LCC, ...) but none of them are based on bison.
There is aC11 grammarfor YACC (a predecessor of Bison), it should work with Bison (maybe some tweaks will be needed). GCC used to be based on Bison a long ago. GCC 3.4 source code contains afilewith C grammar.
I am using codeblock in Windows 10 for C programs. I was writing this below program but instead of giving 12 it gives 24 as output. I have also checked it using online compiler but still it giving the same output. ``` #include<stdio.h> int main() { int num[]={5,7,9,0,1,7}; printf("%d",sizeof(num)); return 0; ...
but instead of giving 12 it gives 24 as output Not sure why you would expect the output to be12. You are probably assumingsizeof(int)to be2which is not necessarily true on all platforms. sizeof(int)is platform dependent andsizeof(int)is4on your platform. Hence, the output is24. Note: To print asize_t(which is whats...
I'm trying to get the list of nodes in a cluster using only the C API. More or less what the following shell command returns, but from C API ``` rabbitmqctl cluster_status -n rabbit@<remote hostname> ``` I'd like to avoid callingrabbitmqctlfrom the C withsystem()orpopoen()or whatever as I want to avoid having a dep...
Getting RabbitMQ cluster status is not something from AMQP standard and it's not something thatrabbitmq-csupports, at least at this time. There isManagement Pluginthat provides RabbitMQ HTTP API, which is the closest thing you want. Have a look onRabbitMQ HTTP API client for Rubyreadme file, which covers getting clus...
Is it allowed to use same name structure with different definitions in 2 different c files in the same project. For eg. File1.c ``` typedef struct { unsigned int unVar; } abc; ``` File2.c ``` typedef struct { int var; } abc; ``` abc is used in both the files. When i compile these file as par...
6.7.2.1 Structure and union specifiersThe presence of a struct-declaration-list in a struct-or-union-specifier declares a new type, within a translation unit. Types are defined only within a translation unit, a .c file in this case. There is no problem with defining two types with the same name in two different tran...
I have a defined raw data in my header file (which is generated automatically), like this: ``` #defined RAW_DATA 0x11, 0x20, 0x55, 0x00, x044 ``` The aim is to check a specific parameter of RAW_DATA in compilation time and if it is wrong throw an #error. For instance, During the compilation, the preprocessor should...
``` #define RAW_DATA 0x11, 0x20, 0x55, 0x00, x044 #define X_GET_SECOND_PAR(par) GET_SECOND_PAR(par) #define GET_SECOND_PAR(p1,p2,p3,p4,p5) p2 #if X_GET_SECOND_PAR(RAW_DATA) != 0x20 #error "2nd parameter shall be 0x20" #endif ``` For specific parameter checking. It's not elegant.
I am currently reading the manpages abouttime.h. I got this far: ``` time_t now = time(0); struct tm * local = localtime(&now); ``` Now I can work with the time, as far as good, but I do not find the information if its my duty tofree()the variablelocalor not.
Quoting theman page The four functionsasctime(),ctime(),gmtime()andlocaltime()return a pointer to static dataand hence are not thread-safe. [...] So, you need notfree()the returned pointer.
I want to know when anUPDATEquery reports 0 rows matches. I'm usinglibmysql. Here's the code I'm using: ``` char query[300] = {0}; snprintf(query, 300, "UPDATE `my_table` SET name='%s' WHERE id=%d", name, id); if (mysql_query(db, query)) { printf("Error!\n"); } ``` Essentially what I need to know is w...
Checkmysql_affected_rows. This will return number of modified rows by the last query. However, it may return just the rows actually modified. If you want to return matched row, you have to specifyCLIENT_FOUND_ROWSinmysql_real_connect. Check the same page for details.
I have a small Linux project written in C is it possible to analyze it with a SonarQube?
According tohttps://en.wikipedia.org/wiki/SonarQube, it support c/c++, and is cross-platform, so you can do it I think.
I am doing vectorization using AVX intrinsics, I want to fill constant floats like1.0into vector__m256. So that in one register I got a vector{1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}Does anyone knows how to do it? It is similar to this questionconstant float with SIMD But I am using AVX not SSE
The simplest method is to use_mm256_set1_ps: ``` __m256 v = _mm256_set1_ps(1.0f); ```
This question already has answers here:C comma operator(4 answers)Closed7 years ago. ``` int a=3,1; int b=(5,4); ``` I am a beginner in c and I noticed in a book this type of initialization . what does thisinitialisationmean?
int b = (5,4)will first evaluate 5 then 4. The last thing that is evaluated will be assigned to the variable. For example ``` int b = (5,4,3,2,1) ``` in this case the value of b will be 1.
I have so many includes like this in my application ``` #include "../../libs/helper.hpp" ``` I am glad to remove there../../libs/from every include. Is there any way to fix this problem so I can call the library this way? ``` #include "helper.hpp" ``` one possible way is to use-Iswitch in make file. But the proble...
-iquotedirAdd the directorydirto the head of the list of directories to be searched for header files only for the case of#include "file"; they are not searched for#include <file>, otherwise just like-I. https://gcc.gnu.org/onlinedocs/gcc-5.3.0/gcc/Directory-Options.html#Directory-Options
``` #include <unistd.h> #include <string.h> #include <stdio.h> #include <stdlib.h> uid_t ruid=-1, euid=-1, suid=-1; int main() { FILE *fh = fopen("file.txt", "r"); char c; while ((c = fgetc(fh)) != EOF) { printf("%c", c); } return 0; ``` } So guys I have to open this file using c fopen command but I have to...
You simply specify the path..... fopen("/path/to/file.txt", "r")
Working with a double, I can set ``` double x = 216/22 //Output's 9.818181... ``` However, when I try: ``` double x = (216/22) //Outputs 9.00000... double x = ((double)216/22) //Outputs 9.0000... double x = (216/(double)22) //Outputs 9.818181... ``` Why does (216/22) return 9 and not 9.8181.....
Why does (216/22) return 9 and not 9.8181...? Because both 216 and 22 areint- and the result is an int. (216.0/22)would return double as expected.
If I have: ``` #include <stdio.h> int main(int argc, char *argv[]) { int length = strlen(argv[1]); ``` and argv[1] one is just a word, for example, "hello", how can I index through it backwards and print out letter by letter? I tried using strrev, but apparently this isn't in linux and rather than include the ...
how can I index through it backwards and print out letter by letter ``` int i; for (i = strlen( argv[1] ) - 1 ; i >= 0; i--){ printf("%c", argv[1][i]); } ``` Also, of course you need to#include <string.h>for string-related functions likestrlen.
I saw a call when reading PX4 code, ``` open(ACCEL_BASE_DEVICE_PATH "0", O_RDONLY) ``` where ,#define ACCEL_BASE_DEVICE_PATH "/dev/accel" so,open("/dev/accel" "0", O_RDONLY) is this even possible ?"/dev/accel" "0" I'm expecting there may be pre processing macro ... But that will hard to find..
Consecutive string literals are concatenated by pre-processor. It is legal. "/dev/accel" "0"results in"/dev/accel0". Note that space is irrelevant here (but more readable), it would be the same with"/dev/accel""0". Note also that, in c++11, because of User-defined literals (UDL), space may be required sometime as f...
This question already has answers here:C comma operator(4 answers)Closed7 years ago. ``` int a=3,1; int b=(5,4); ``` I am a beginner in c and I noticed in a book this type of initialization . what does thisinitialisationmean?
int b = (5,4)will first evaluate 5 then 4. The last thing that is evaluated will be assigned to the variable. For example ``` int b = (5,4,3,2,1) ``` in this case the value of b will be 1.
I have so many includes like this in my application ``` #include "../../libs/helper.hpp" ``` I am glad to remove there../../libs/from every include. Is there any way to fix this problem so I can call the library this way? ``` #include "helper.hpp" ``` one possible way is to use-Iswitch in make file. But the proble...
-iquotedirAdd the directorydirto the head of the list of directories to be searched for header files only for the case of#include "file"; they are not searched for#include <file>, otherwise just like-I. https://gcc.gnu.org/onlinedocs/gcc-5.3.0/gcc/Directory-Options.html#Directory-Options
``` #include <unistd.h> #include <string.h> #include <stdio.h> #include <stdlib.h> uid_t ruid=-1, euid=-1, suid=-1; int main() { FILE *fh = fopen("file.txt", "r"); char c; while ((c = fgetc(fh)) != EOF) { printf("%c", c); } return 0; ``` } So guys I have to open this file using c fopen command but I have to...
You simply specify the path..... fopen("/path/to/file.txt", "r")
Working with a double, I can set ``` double x = 216/22 //Output's 9.818181... ``` However, when I try: ``` double x = (216/22) //Outputs 9.00000... double x = ((double)216/22) //Outputs 9.0000... double x = (216/(double)22) //Outputs 9.818181... ``` Why does (216/22) return 9 and not 9.8181.....
Why does (216/22) return 9 and not 9.8181...? Because both 216 and 22 areint- and the result is an int. (216.0/22)would return double as expected.
If I have: ``` #include <stdio.h> int main(int argc, char *argv[]) { int length = strlen(argv[1]); ``` and argv[1] one is just a word, for example, "hello", how can I index through it backwards and print out letter by letter? I tried using strrev, but apparently this isn't in linux and rather than include the ...
how can I index through it backwards and print out letter by letter ``` int i; for (i = strlen( argv[1] ) - 1 ; i >= 0; i--){ printf("%c", argv[1][i]); } ``` Also, of course you need to#include <string.h>for string-related functions likestrlen.
I saw a call when reading PX4 code, ``` open(ACCEL_BASE_DEVICE_PATH "0", O_RDONLY) ``` where ,#define ACCEL_BASE_DEVICE_PATH "/dev/accel" so,open("/dev/accel" "0", O_RDONLY) is this even possible ?"/dev/accel" "0" I'm expecting there may be pre processing macro ... But that will hard to find..
Consecutive string literals are concatenated by pre-processor. It is legal. "/dev/accel" "0"results in"/dev/accel0". Note that space is irrelevant here (but more readable), it would be the same with"/dev/accel""0". Note also that, in c++11, because of User-defined literals (UDL), space may be required sometime as f...
I can't seem to google this because everything turns up as C++ or C# (Side note: any easy way to search for C specific?). All I'm trying to figure out is how to accept a console string input in such a way that I know it's length so I can return it in reverse order by indexing backwards through it with a for loop. I've...
Read withfgets().Cope with a possible trailing\n.Find lengthprint in reverse.char buf[100]; if (fgets(buf, sizeof buf, stdin) == NULL) Handle_EOF(); buf[strcspn(buf, "\n")] = '\0'; // lop off potential trailing \n size_t len = strlen(buf); while (len) { putc(buf[--len], stdout); }
I can't seem to google this because everything turns up as C++ or C# (Side note: any easy way to search for C specific?). All I'm trying to figure out is how to accept a console string input in such a way that I know it's length so I can return it in reverse order by indexing backwards through it with a for loop. I've...
Read withfgets().Cope with a possible trailing\n.Find lengthprint in reverse.char buf[100]; if (fgets(buf, sizeof buf, stdin) == NULL) Handle_EOF(); buf[strcspn(buf, "\n")] = '\0'; // lop off potential trailing \n size_t len = strlen(buf); while (len) { putc(buf[--len], stdout); }
I need to pass integer to kernel module, calculate sin there and return result. First of all, kernel has built-in sinfixp_t fixp_sin(unsigned int degrees)function, that returns fixed-point number (that can be negative). So, my question is: if i pass integer using ioctl to kernel module, calculate sin, how i can retu...
I need to pass integer to kernel module, calculate sin there and return result. Instead of passing integer value toioctl(), structure can be passed. This structure can have inputs and output data fields. There is no need to mess withioctl()return values. Sample ioctl() with passing struct to char driverhttps://git...
This question already has answers here:How does concatenation of two string literals work?(4 answers)Closed7 years ago. I encountered the following type of string literal in an open source library, which I have not seen before. It turns out thataandbare the same. I'm confused why the syntax ofais correct? Does C prep...
Fromsection 5.1.1.2.6 of the C99 standard: Adjacent string literal tokens are concatenated. So your assumption is correct. Anyplace you see string literals consecutively, the compiler implicitly concatenates them.
In our code base I found something similar to ``` static char foo[4] = "0"; ``` Since the string is smaller than the array, is this still well-defined?Hypothetically, what if I had ``` static char bar[4] = "01234"; ``` I assume the array would be initialized to "0123". But is this guaranteed by the standard or als...
Since the string is smaller than the array, is this still well-defined? Yes, ``` static char foo[4] = "0"; ``` is well defined.foowill contain'0','\0','\0'and'\0'. The snippet ``` static char bar[4] = "01234"; ``` is constraint violation. While ``` static char bar[4] = "0123"; ``` is well defined untilbaris no...
I need to include ZIMPL in a CMake project. In the source code the ZIMPL headers are included like this ``` #include zimpl/bool.h ``` The actual path within ZIMPL iszimpl/src/bool.h. How can I tell CMake (or the C linker) to look inzimpl/src/whenever it encounters azimpl/include? I would prefer to avoid creating sym...
You cannot#includefiles using relative path different from actual one. The simples way to do with your case is to copy original headers into locations, which has needed path suffixes. It can be done with CMake viafile(COPY)orconfigure_file(.. COPY_ONLY): ``` file(COPY <source_include_dir>/zimpl/src/bool.h DESTIN...
I was looking into a code snippet and saw below statement. How will below statement evaluated? ``` x= 5|(high == 1 ? y : high == 0 ? z:0); ```
The expression ``` x= 5|(high == 1 ? y : high == 0 ? z:0); ``` is evaluated as ``` x= 5|( high == 1 ? y : (high == 0 ? z:0) ); ``` It has similar effect as that of ``` if(high == 1) x = 5|y; else if(high == 0) x = 5|z; else x = 5|0; ```
I have a function with something like ``` FILE *file1 = fopen("testing.txt", "r"); ``` I can't modify this line. However, if I make a file named "testing.txt" in, say/tmp, would I be able to make the function load the file from/tmpinstead of it's own directory. (Maybe by modifying thePATHvariable?)
If the program doesn't change its own working directory, you couldcdinto/tmpand simply run the program from there. ``` $ cd /tmp $ /absolute/path/to/my_program ```
I have a function with something like ``` FILE *file1 = fopen("testing.txt", "r"); ``` I can't modify this line. However, if I make a file named "testing.txt" in, say/tmp, would I be able to make the function load the file from/tmpinstead of it's own directory. (Maybe by modifying thePATHvariable?)
If the program doesn't change its own working directory, you couldcdinto/tmpand simply run the program from there. ``` $ cd /tmp $ /absolute/path/to/my_program ```
I am doing an exercise where I need to write Unicode on the terminal, using onlywrite()in<unistd.h>. I can't use : putcharsetlocaleprintf (in fact the exercise is reproducingprintffunction) Any "low level" advice on how to perform that?
As Chris wrote in the comments, you need a terminal (e.g. like xterm on Linux) that understands the Unicode and then you just write them. So by default xterm understands UTF8 and is set to a codepage such that this code will give you a UTF8 Smiley Face (☺). ``` #include <stdio.h> #include <unistd.h> char happy[] = {...
I am trying to combine three bit operations in one line of C. For a 8 bit char, I have to set bits 2, 4, 6; clear bits 1, 3, 7 and toggle bit 0 and 5 all in one line code of C. I could do these in three line but I cannot combine these. Below is what I have done so far: ``` x= x & 0xD5; x = x | 0x51; x = x ^ 0x84; ``...
It's simply this ``` x = (((x & 0xD5) | 0x51) ^ 0x84) ``` Your first try is wrong, because the values ofxare not updated so all the operations work on the same value, besides oring the values is not equivalent to assigning the result of the operation tox. The second, is wrong because or operator precedence, so you ...
This is best asked with a code example: ``` typedef struct { ... // Fields take up many bytes (>= 32 bytes) } some_struct; void alternative_1(some_struct arg); void alternative_2(const some_struct *arg); ``` Assuming that both function alternatives are implemented inside an already compiled binary (and therefor...
Obviously yes: When callingalternative_1, the whole struct data is pushed onto the stack prior to branching to the function (which may be quite a lot). Whereasalternative_2only has a single pointer to the struct pushed onto the stack. There is also a big difference when operating on the struct: In the case ofalter...
p is pointer on a array ``` int array[] = {1,2,3,4,5}; int *p = array; ``` And when i want to printf the array entries: is this the same and why: *(p++)*p++ Hope you can help me!
++ has a higher precedence (meaning it binds to p tighter) than * therefore*p++is equivalent to*(p++). Something similar to this is the difference between*p[]and(*p)[].[]has a higher precedence than*therefore*p[]is equivalent to*(p[])which makes alist a pointersbut something like(*p)[]explicitly says to do whats in t...
This is the error I'm getting: ``` c:17:15: error: expected expression before ‘=’ token suma + = mat[N][M]; ``` And this is my code: ``` #include<stdio.h> #define N 3 #define M 3 int mat[N][M]i,j,k,l,m,n; int vector[N]; int suma; int main (void){ for(i=0;i<N;i++){ for(j=0;j<M;j++){ pr...
``` += != + = ``` Meaning: just write:suma += mat[N][M];............................................^ no space. For the sake of completeness I will add what Sourav mentioned: You need to reseti(i=0) after the firstforloop, to avoid accessing out of bounds memory and causing undefined behavior.
I get the following error : Error:Neither MinGW nor Cygwin is selected Do you have idea for resolve this issue?
To elaborate on the answer provided by "uta" you need either MinGW or Cygwin in order to compile your code. MinGW can be obtained from here:MinGW Or Cygwin from here:Cygwin For simplicity I will describe MinGW. Install MinGW then navigate like so in CLion: File -> Settings -> Build, Execution, Deployment -> Toolcha...
I was shifting around the 'C' standard and I came across this: $6.7.9.5: If the declaration of an identifier has block scope, and the identifier has externalor internal linkage, the declaration shall have no initializer for the identifier. So my question is on the title. I would also like some examples if possi...
``` static int i; // internal linkage void f() { extern int i; // block-scope declaration; refers to i in global scope // still internal linkage - see 6.2.2/4 } ```
I have to use some char16-wide strings for uefi programming. How can I initialize them easily? CHAR8 is easy: ``` CHAR8 *Str = "yehaw\0"; ``` CHAR16 meanwhile is hard working that way, therefore I chose this initialization: ``` CHAR16 *Str; Str = AllocatePool(6*2); //AllocatePool allocates bytewise Str = ('y','e','...
If you have the c standard library and are using a conformant C/C++ compiler, typically prefixing a string with L works for declared strings.As in : ``` CHAR16 *Str = L"yehaw"; ``` works. However, why not use the ubiquitously accepted type of ``` wchar_t ``` ?
I have this structure : ``` typedef struct s_hashmap { t_hashmap_elem **array_elements; size_t array_size; void *(*get)(struct s_hashmap **, void *); void (*add)(struct s_hashmap **, t_hashmap_elem *); } t_hashmap; ``` Can I access to...
No you can not. There are no methods of user-defined types in C. You have to pass a pointer (or pointer to pointer depending on the parameter declaration) to an object of the structure if you want to change it.
I am doing some logic tasks in C and while I evaluate by hand some of the results are different than the ones printed by CodeBlocks. What is the decimal value of following expressions taking previously executed instructions into account? Here're the numbers (I do not understand output of lines signed with "<<<<<<<<"...
``` k|7&12; ==> 27|7&12 ==> 27|4 ==> 31 (discarded value) fp=10/20; ==> fp=0 ==> 0 (fp is now 0.0) fp=(float)10/20; ==> fp=10.0f/20 ==> fp=0.5f (fp is 0.5) ```
I'm trying to read in an integer using getchar(). This is the code I'm using: ``` while (thisChar = getchar() != '\n') { n = n * 10 + thisChar - '0'; } ``` int nis initialized to zero andthisCharis declared as anint For single digit input, n is returning as -47 which means the character value forstart of headin...
It's missing parentheses: ``` int thisChar; while ((thisChar = getchar()) != '\n') { n = n * 10 + thisChar - '0'; } ``` Without these additional parentheses, you always assign tothisCharthe value of the comparisongetchar() != '\n', i.e. always1or0... Note that you should also handleEOF: ``` int thisChar = getc...
In the following code ``` int main(){ int a=3; printf("%d %d %d",++a,a,a++); return 0; } ``` As specified, From C99 appendix C:, The following are the sequence points described in 5.1.2.3: The call to a function, after the arguments have been evaluated (6.5.2.2).The end of the first operand of the ...
Because thecommain the function call isnotthecomma operatorbut aseparator. So it doesn't introduce any sequence point(s).
I'm trying to run my program in valgrind 3.10.0, but it seems to hang inset_address_range_perms(). The last output I get is ``` --69447:1:aspacem allocated thread stack at 0x803c7c000 size 1064960 --69447:1:syswrap- run_a_thread_NORETURN(tid=2): pre-thread_wrapper --69447:1:syswrap- thread_wrapper(tid=2): entry ``` ...
The first thing to try is to use gdb+vgdb and connect to your program which is hanging: in another window, start gdb and then in gdb, do target remote | vgdb You can then use various gdb commands to see what is happening e.g. info threads; threads apply all bt full; .... Seehttp://www.valgrind...
I was shifting around the 'C' standard and I came across this: $6.7.9.5: If the declaration of an identifier has block scope, and the identifier has externalor internal linkage, the declaration shall have no initializer for the identifier. So my question is on the title. I would also like some examples if possi...
``` static int i; // internal linkage void f() { extern int i; // block-scope declaration; refers to i in global scope // still internal linkage - see 6.2.2/4 } ```
I have to use some char16-wide strings for uefi programming. How can I initialize them easily? CHAR8 is easy: ``` CHAR8 *Str = "yehaw\0"; ``` CHAR16 meanwhile is hard working that way, therefore I chose this initialization: ``` CHAR16 *Str; Str = AllocatePool(6*2); //AllocatePool allocates bytewise Str = ('y','e','...
If you have the c standard library and are using a conformant C/C++ compiler, typically prefixing a string with L works for declared strings.As in : ``` CHAR16 *Str = L"yehaw"; ``` works. However, why not use the ubiquitously accepted type of ``` wchar_t ``` ?
I have this structure : ``` typedef struct s_hashmap { t_hashmap_elem **array_elements; size_t array_size; void *(*get)(struct s_hashmap **, void *); void (*add)(struct s_hashmap **, t_hashmap_elem *); } t_hashmap; ``` Can I access to...
No you can not. There are no methods of user-defined types in C. You have to pass a pointer (or pointer to pointer depending on the parameter declaration) to an object of the structure if you want to change it.
I am doing some logic tasks in C and while I evaluate by hand some of the results are different than the ones printed by CodeBlocks. What is the decimal value of following expressions taking previously executed instructions into account? Here're the numbers (I do not understand output of lines signed with "<<<<<<<<"...
``` k|7&12; ==> 27|7&12 ==> 27|4 ==> 31 (discarded value) fp=10/20; ==> fp=0 ==> 0 (fp is now 0.0) fp=(float)10/20; ==> fp=10.0f/20 ==> fp=0.5f (fp is 0.5) ```
I'm trying to read in an integer using getchar(). This is the code I'm using: ``` while (thisChar = getchar() != '\n') { n = n * 10 + thisChar - '0'; } ``` int nis initialized to zero andthisCharis declared as anint For single digit input, n is returning as -47 which means the character value forstart of headin...
It's missing parentheses: ``` int thisChar; while ((thisChar = getchar()) != '\n') { n = n * 10 + thisChar - '0'; } ``` Without these additional parentheses, you always assign tothisCharthe value of the comparisongetchar() != '\n', i.e. always1or0... Note that you should also handleEOF: ``` int thisChar = getc...
In the following code ``` int main(){ int a=3; printf("%d %d %d",++a,a,a++); return 0; } ``` As specified, From C99 appendix C:, The following are the sequence points described in 5.1.2.3: The call to a function, after the arguments have been evaluated (6.5.2.2).The end of the first operand of the ...
Because thecommain the function call isnotthecomma operatorbut aseparator. So it doesn't introduce any sequence point(s).
I'm trying to run my program in valgrind 3.10.0, but it seems to hang inset_address_range_perms(). The last output I get is ``` --69447:1:aspacem allocated thread stack at 0x803c7c000 size 1064960 --69447:1:syswrap- run_a_thread_NORETURN(tid=2): pre-thread_wrapper --69447:1:syswrap- thread_wrapper(tid=2): entry ``` ...
The first thing to try is to use gdb+vgdb and connect to your program which is hanging: in another window, start gdb and then in gdb, do target remote | vgdb You can then use various gdb commands to see what is happening e.g. info threads; threads apply all bt full; .... Seehttp://www.valgrind...
I am working on an cufft implementation and can't find any reference to the cufftcomplex functions. I found cucomplex.h through google, though, but that doesn't help me. Specifically i want to know, how to read out the imaginary part and the real part of the cufftcomplex struct.
The typescufftComplexandcuComplexare actually same. It is documented in thecuFFT documentation. Incufft.hyou will find the typedef: ``` typedef cuComplex cufftComplex; ``` IncuComplex.hyou will find thatcuComplexis indeed afloat2, i.e. you can read out the real value withc.xand the imaginary value withc.y. Or better...
I have two arrays of char: a,b. How can i create with a loop "for" the new array vet, which is the union of the two alternating array a, b? ``` #include <stdio.h> int main(void) { char a[] = "BNSIO"; char b[] = "EISM\a"; char vet[sizeof(a) + sizeof(b)]; for (int i = 0; i < (sizeof(a) + sizeof(b)); i+...
You can try this: ``` for (int i = 0,j=0,k=0; k < (sizeof(a) + sizeof(b) -2);) { if(i+1<sizeof(a)) { vet[k] = a[i]; i++;k++; } if(j+1<sizeof(b)) { vet[k] = b[j]; j++;k++; } } for (int i = 0; i < (sizeof(a) + sizeof(b)-2); i++){ printf("%c", vet[i]); ...
This question already has answers here:What is the behavior of printing NULL with printf's %s specifier?(4 answers)Closed7 years ago. ``` #include<stdio.h> #include<string.h> int main() { char *ptr = NULL; printf("%s", ptr);//The output is null // printf("%s\n", ptr); //addition of **\n** give segmenta...
printf("%s", ptr); Hereprintfexpects a valid pointer, which points to null terminated string, you can't pass NULL to it. If you do so, you will trigger undefined behaviour, and can't reason about output of the program. PS. I have found an answer which might have slightly more details about the thing you might be int...
I would like to set the pointers*nameand*agein Student struct to NULL. Im not sure how this could be done from the main(). ``` typedef struct Student Student; typedef struct Student{ char *name; int *age; } Student; ``` I would like to set the pointers mentioned above to NULL in my main. My declaration of ...
You can do it for example the following way ``` Student Tom = { NULL, NULL }; ``` or ``` Student Tom = { .name = NULL, .age = NULL }; ``` or ``` Student Tom; Tom.name = NULL; Tom.age = NULL; ```
I have two arrays of char: a,b. How can i create with a loop "for" the new array vet, which is the union of the two alternating array a, b? ``` #include <stdio.h> int main(void) { char a[] = "BNSIO"; char b[] = "EISM\a"; char vet[sizeof(a) + sizeof(b)]; for (int i = 0; i < (sizeof(a) + sizeof(b)); i+...
You can try this: ``` for (int i = 0,j=0,k=0; k < (sizeof(a) + sizeof(b) -2);) { if(i+1<sizeof(a)) { vet[k] = a[i]; i++;k++; } if(j+1<sizeof(b)) { vet[k] = b[j]; j++;k++; } } for (int i = 0; i < (sizeof(a) + sizeof(b)-2); i++){ printf("%c", vet[i]); ...
This question already has answers here:What is the behavior of printing NULL with printf's %s specifier?(4 answers)Closed7 years ago. ``` #include<stdio.h> #include<string.h> int main() { char *ptr = NULL; printf("%s", ptr);//The output is null // printf("%s\n", ptr); //addition of **\n** give segmenta...
printf("%s", ptr); Hereprintfexpects a valid pointer, which points to null terminated string, you can't pass NULL to it. If you do so, you will trigger undefined behaviour, and can't reason about output of the program. PS. I have found an answer which might have slightly more details about the thing you might be int...
I would like to set the pointers*nameand*agein Student struct to NULL. Im not sure how this could be done from the main(). ``` typedef struct Student Student; typedef struct Student{ char *name; int *age; } Student; ``` I would like to set the pointers mentioned above to NULL in my main. My declaration of ...
You can do it for example the following way ``` Student Tom = { NULL, NULL }; ``` or ``` Student Tom = { .name = NULL, .age = NULL }; ``` or ``` Student Tom; Tom.name = NULL; Tom.age = NULL; ```
ok, so i'm trying to compile my code using makefile, i've got only 2 .c file and 1 .h file, i used "sqrt()" function from math.h (only in main), here is my makefile: ``` a.out: GBST.o main.o gcc GBST.o main.o GBST.o: GBST.c GBST.h gcc -c GBST.c main.o: main.c gcc -c main.c -lm ``` still, ...
You need to use-lmin the link line, not in the compile line. ``` a.out: GBST.o main.o gcc GBST.o main.o -lm # ^^^^ Need it here GBST.o: GBST.c GBST.h gcc -c GBST.c main.o: main.c gcc -c main.c # ^^^^ Don't need it here ```
Regular expression in C. Can I declare a pointer likevoid *{a,b}which meansvoid *a, *b; Is it possible, are regex expressions a standard in ANSI C
C does not have support for regular expressions in the code itself. Libraries exist to perform regular expressions on text, but not on the code. Variable declarations must be done separately. For pointers in particular, a*next to a declared variable applies only to that variable. For example: ``` int *a, b, *c; `...
I tried using all these flagsldliandluwithsscanfbut none worked. The following gets4294967295no matter what number i put inbuf: ``` long unsigned data; char buf[40] = "data 2349872764943587"; if (sscanf (buf, "data %lu", &data) == 1) { printf ("%s\n", buf); printf ("data:\t%lu\n", data); } ``` Output: ``` ...
OP'sunsigned longappears to be a 32-bit and so cannot represent the 51-bit2349872764943587. If stuck using a compiler that lacks 64-bit integers, code could usedouble, which typically handles 53-bit whole number values without loss of precision. ``` double data; char buf[40] = "data 2349872764943587"; if (sscanf (b...
How to useCopyFilefor copying specific type of files from one folder to a backup file (backup.bkp) Example: ``` C:\HHH abc.jpeg def.txt ghi.jpeg ``` I want to copy only jpeg files to thebackup.bkpfile I tried the below syntax but it is not working, ``` CopyFile( _T("C:\\HHH\*.jpeg"),_T("C:\\Backup.bak", FAL...
CopyFile doesn't accept wild cards or copy multiple files. It can copy a single file from one fully specified place to another. To achieve what you want you need to enumerate over the directory usingFindFirstFile/FindNextFileand copy the files one by one using CopyFile. These functions take wildcards or you can ask f...
I know if I am inputting a string into a pointer variable I would malloc that based on the size of the input received. But what if I am using a pointer variable for the use instrchr? For example if I want the pointer to point to the the character "z" in a string. ``` char *pointer; pointer=strchr(string,'z'); ``` ...
You don't have to allocate any memory here . Strchr function returns a pointer to the first occurence of a char in a string if it exists. If a given string deos not contain a char then a null will be returned. You need to allocate memory only if you want to create something new, that has not been created yet. In this...
I'm writing a C program usingnftw()to walk a filesystem and retrieve file modification times for each file. nftw()calls a supplied function pointer and provides astruct statas an argument. man stat(2)states that the time modification fields are: ``` struct timespec st_atim; /* time of last access */ struct timespe...
Typically one of the man pages describes what these structures contain. If you tell us your platform I can give further details. Otherwise, open up the header/usr/include/time.hto see whatstruct timespecis defined as.
I tried using all these flagsldliandluwithsscanfbut none worked. The following gets4294967295no matter what number i put inbuf: ``` long unsigned data; char buf[40] = "data 2349872764943587"; if (sscanf (buf, "data %lu", &data) == 1) { printf ("%s\n", buf); printf ("data:\t%lu\n", data); } ``` Output: ``` ...
OP'sunsigned longappears to be a 32-bit and so cannot represent the 51-bit2349872764943587. If stuck using a compiler that lacks 64-bit integers, code could usedouble, which typically handles 53-bit whole number values without loss of precision. ``` double data; char buf[40] = "data 2349872764943587"; if (sscanf (b...
How to useCopyFilefor copying specific type of files from one folder to a backup file (backup.bkp) Example: ``` C:\HHH abc.jpeg def.txt ghi.jpeg ``` I want to copy only jpeg files to thebackup.bkpfile I tried the below syntax but it is not working, ``` CopyFile( _T("C:\\HHH\*.jpeg"),_T("C:\\Backup.bak", FAL...
CopyFile doesn't accept wild cards or copy multiple files. It can copy a single file from one fully specified place to another. To achieve what you want you need to enumerate over the directory usingFindFirstFile/FindNextFileand copy the files one by one using CopyFile. These functions take wildcards or you can ask f...
I know if I am inputting a string into a pointer variable I would malloc that based on the size of the input received. But what if I am using a pointer variable for the use instrchr? For example if I want the pointer to point to the the character "z" in a string. ``` char *pointer; pointer=strchr(string,'z'); ``` ...
You don't have to allocate any memory here . Strchr function returns a pointer to the first occurence of a char in a string if it exists. If a given string deos not contain a char then a null will be returned. You need to allocate memory only if you want to create something new, that has not been created yet. In this...
I'm writing a C program usingnftw()to walk a filesystem and retrieve file modification times for each file. nftw()calls a supplied function pointer and provides astruct statas an argument. man stat(2)states that the time modification fields are: ``` struct timespec st_atim; /* time of last access */ struct timespe...
Typically one of the man pages describes what these structures contain. If you tell us your platform I can give further details. Otherwise, open up the header/usr/include/time.hto see whatstruct timespecis defined as.
Very simple script throw this error : passing argument 1 of ‘fprintf’ makes pointer from integer without a cast Why is that ? The code is : ``` #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { FILE *FP; if((FP = fopen("file.txt", "r+")) == NULL) { printf("File won't open\n"); re...
Change ``` int foo(FP) { ``` to ``` int foo(FILE * FP) { ``` You must put a prototype offoofunction at the top of your code.
This question already has answers here:Compiler error: memset was not declared in this scope(2 answers)Closed7 years ago. I have the following c code: ``` #include<stdio.h> int main(void) { char buff[10]; memset(buff,0,sizeof(buff)); gets(buff); printf("\n The buffer entered is [%s]\n",buff); ...
Add ``` #include <string.h> ``` at the top of file. This because is the header file where thememsetprototype can be found by compiler. Avoid using gets function... Usescanforfgetsinstead. Take a lookHERE
I wrote a simple lex file to identify C keywords. My rules looks like: ``` keyword do|while|char|if %% {keyword} { printf("Keyword %s found.", yytext); } ``` The problem is the rule correctly identifiescharin source code, but it also identifies things likeputcharas keywordchar. How can I force the rule to only id...
You need to put keywords before identifiers. That's all. Lex is searching for regular expressions sequentially. ``` %% IF|ELSE|etc {action for keywords } [a-zA-Z_][a-zA-Z0-9]* {action for identifiers} %% ```
I have recently started programming in C and was wondering about a more concise way to write a simple function that returns 1 or -1 depending on the equality of two int values. What I wrote: ``` int valueCompare(int i, int j) { if (i != j) { return -1; } else { return 1; } } ``` It's ...
You can use the ternary operator: ``` int valueCompare(int i, int j) { return (i == j) ? 1 : -1; } ```
If I am looping through an array, should I useintoruint8_t? ``` for (int i = 0; i < 100; i++) {} ``` or ``` for (uint8_t i = 0; i < 100; i++) {} ``` Which is better when working with embedded systems?
The first choice is much better: ``` for (int i = 0; i < 100; i++) { } ``` The alternative is sometimes encouraged by local coding rules, it is a bad recommendation: it tends to generate more code if you useiin the loop body as an index or in an expression.it can also lead to more bugs especially if you later modif...
My objective is to call a void function "sum" which is passed two integers where they will be added together. I then want the first integer variable to be modified so that it is pointing at the sum of the two integers. When I compile I get "error: indirection requires pointer operand ('int' invalid)."
This should work: ``` void sum(int *x, int y){ *x += y; // *x means "contents of what is pointed to by pointer x" } void call_sum() { int x = 1, y = 2; sum(&x,y); // &x because you're passing the address printf("%d\n", x); // this should print 3 } ```
This is the if statement I have: ``` if (fgetc(fileName) != EOF) { } ``` I know if I runfgetc()when not within theifstatement it will remove a character and I would have to doungetcto return it. Will this happen when thefgetcis within theifstatement?
Yes it will, and since you did not store the byte that was read, you lost it. Use this instead: ``` int c; if ((c = fgetc(fp)) != EOF) { ungetc(c, fp); /* put the byte back into the input stream */ /* not at end of file, keep reading */ ... } else { /* at end of file: no byte was read, nothing to p...
I just read in a string using the following statement: ``` fgets(string, 100, file); ``` This string that was just read in was the last line. If I callfeof()now will it return TRUE? Is it the same as callingfeof()right at the start before reading in any lines?
No, don't usefeof()to detect the end of the file. Instead check for a read failure, for examplefgets()will returnNULLif it attempts to read past the end of the file whereasfeof()will return0until some function attempts to read past the end of the file, only after that it returns non-zero.
I was wondering if (and how) one can print only the sign of an array entry. For example I'd have something like ``` {1, -1, -1, 1} ``` and I would like the output to look something like ``` + - - + ``` I'm pretty new to C and the only solution I can come up with is some sort ofif (... < 0)contdition that results i...
The way you have mentioned is effective for this purpose. If you want to do same thing by some other way, you can use ternary operator as: ``` a[i] < 0 ? printf("-"): printf("+"); ```
I tried to implementstrcmp: ``` int strCmp(char string1[], char string2[]) { int i = 0, flag = 0; while (flag == 0) { if (string1[i] > string2[i]) { flag = 1; } else if (string1[i] < string2[i]) { flag = -1; } else { i++; } } ...
Uhm.. way too complicated. Go for this one: ``` int strCmp(const char* s1, const char* s2) { while(*s1 && (*s1 == *s2)) { s1++; s2++; } return *(const unsigned char*)s1 - *(const unsigned char*)s2; } ``` It returns <0, 0 or >0 as expected You can't do it without pointers. In C, index...
I have a server application that creates a UNIX Domain Socket in a specific path with a name andbind()s to it. I need to delete the socket only when I close/stop the application intentionally, from within the the application code; otherwise it needs to be open. How do I do this? Thanks! Edit:Consider that I start a...
You're making this harder than it needs to be. Put theunlink()right before thebind(). That's how everybody else does it. (Example:BSD syslogd, one of the classic unix-domain-socket-based services)
I am a bit at a loss as to why the compiler doesn't throw any kind of warning. ``` int32_t CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int32_t nCmdShow) { //.. } ``` Above is my Windows specific main function. Note thatlpCmdLineparameter has typeLPSTRwhich atypedeffor achar *. ...
Setting the compilation warning level to/Wallwill produce the mentioned warnings.
For example if the file contains: ``` 12345 -3445654 1245646 ``` I want to read the first line into a string usingfgets(). Then I want to read the second line in too check if there is a'-'in the first spot. If there is one, I will read the second line andstrcatit to the first line. Then I want to read the thrid lin...
Use fgetc to read the first character on the next line, and if it's not a '-' use ungetc to put it back.
I'm trying to debug a setup.py file for a package that builds a C extension with ``` from distutils.core import Extension ext = Extension(... ``` I'd like to see what compiler / linker commands are actually getting executed. How do I print them when running ``` pip install -e ./ ``` or ``` python setup.py instal...
The problem seems to be that it wasn't rebuilding the extension, but rather using a cached version. If I run ``` python setup.py clean --all python setup.py develop ``` it rebuilds and shows all the compile/link commands.
I wrote two little programs in C,cryptanddecrypt. I can call from the terminal: ``` ./crypt some_argument it works. ``` But I want to pass to decrypt the output ofcrypt. I already tried: ``` ./decrypt $(./crypt hello) does not work ./crypt hello | ./decrypt ...
The output contains spaces. You need to quote it if you want everything inargv[1]. i.e../decrypt "$(./crypt some_argument)"
if you have a simple function e.gint open(const char *path, int oflags);you could pass a string directly as*pathe.g"filename.txt. You also could pass a&foo(which is an address, it might have no sense in this case). You can even put a normal pointer in it. So my question is, is actually anaddressexpected when you have...
It expects a pointer. A string constant, e.g."filename.txt", actually has a pointer value: An array is created to hold the string, and the value of the expression is the address of that array, i.e. a pointer to it.
This question already has answers here:What is the difference between %*c%c and %c as a format specifier to scanf?(3 answers)Closed7 years ago. So I stumbled across this code and I haven't been able to figure out what the purpose of it is, or how it works: ``` int word_count; scanf("%d%*c", &word_count); ``` My fir...
*cmeans, that a char will be read but won't be assigned, for example for the input "30a" it will assign 30 toword_count, but 'a' will be ignored.
I was wondering if (and how) one can print only the sign of an array entry. For example I'd have something like ``` {1, -1, -1, 1} ``` and I would like the output to look something like ``` + - - + ``` I'm pretty new to C and the only solution I can come up with is some sort ofif (... < 0)contdition that results i...
The way you have mentioned is effective for this purpose. If you want to do same thing by some other way, you can use ternary operator as: ``` a[i] < 0 ? printf("-"): printf("+"); ```
I tried to implementstrcmp: ``` int strCmp(char string1[], char string2[]) { int i = 0, flag = 0; while (flag == 0) { if (string1[i] > string2[i]) { flag = 1; } else if (string1[i] < string2[i]) { flag = -1; } else { i++; } } ...
Uhm.. way too complicated. Go for this one: ``` int strCmp(const char* s1, const char* s2) { while(*s1 && (*s1 == *s2)) { s1++; s2++; } return *(const unsigned char*)s1 - *(const unsigned char*)s2; } ``` It returns <0, 0 or >0 as expected You can't do it without pointers. In C, index...
I have a server application that creates a UNIX Domain Socket in a specific path with a name andbind()s to it. I need to delete the socket only when I close/stop the application intentionally, from within the the application code; otherwise it needs to be open. How do I do this? Thanks! Edit:Consider that I start a...
You're making this harder than it needs to be. Put theunlink()right before thebind(). That's how everybody else does it. (Example:BSD syslogd, one of the classic unix-domain-socket-based services)
I am a bit at a loss as to why the compiler doesn't throw any kind of warning. ``` int32_t CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int32_t nCmdShow) { //.. } ``` Above is my Windows specific main function. Note thatlpCmdLineparameter has typeLPSTRwhich atypedeffor achar *. ...
Setting the compilation warning level to/Wallwill produce the mentioned warnings.
For example: "16" should print out the decimal values: 49,54"24" should print out the decimal values: 50,52 How do I achieve this?
It's really simple, you don't need to convert anything it's a matter of representation, example ``` const char *sixteen = "16"; const char *twentyfour = "24"; const char *number = "1345461"; printf("%d,%d\n", sixteen[0], sixteen[1]); printf("%d,%d\n", twentyfour[0], twentyfour[1]); // ^ ^ use the `%d' specifi...
I have a program that make the sum of a and b(readed from file) and write it in a file.The problem come when i compile the code. I have no idea why i get this error because on windows the same code works fine.Thank You.
Most likely your use of relative paths is incorrect — Xcode doesn't launch the executable in the folder where the source is (even if it tried to: what should it do when the source is in multiple folders?), soinisNULLand therefore thefscanfhas undefined behaviour. In general, assuming you know the current working dire...
I am usingVexRobotCand have a function:setTouchLEDRGB(portx, R,G,B);which sets the RGB colour of a touch LED. I have 9 TouchLEDs and want to change the colour of them all at once, now annoyingly this is 9 lines of code at a time, i hope to create a function with an iteration such as: ``` for (int i = 0, i < 9, i++) ...
``` setTouchLEDRGB(portx, R,G,B); ``` Not sure about the platform, but you could create an array containg the ports: ``` #define NUM_PORTS 9 // 'int' should be the type of your port parameter int ports[NUM_PORTS] = {PORTA, PORTB, etc}; for (int i = 0; i < NUM_PORTS; ++i) { setTouchLEDRGB(ports[i], R, G, B); } ...
I'm porting some Arduino code to a mcu in pure c. The data typebyteis used in the arduino code which is not supported by the compiler. I'm wondering which data byte should I useuint8_torunsigned char? Which is more correct? I'm relatively new to coding. I gather it depends what the intent of the variable. The varia...
According tothis linkan arduino byte is an unsigned 8 bit value. I personally would use the more expressiveuint8_t, but anunsigned charwould work as well. What type is used on the new platform to return a byte received from the serial port? Might also want to check out thisquestion.
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 Basically which one of the Codes will return 0, faster ? // if the answer is "the same" because the code i...
There will be no difference in the compiler generated code. Theelseis unnecessary but may be written for clarity.
I've encountered to this following code during my C learning. I've paste it into CodeBlocks therefore I know the output but (here's my question) how it's done? Can you explain it to me? ``` #include <stdio.h> int main() { unsigned char t[10] = {0,1,2,3,4,5,6,7,8,9}; unsigned short *w; w = (unsigned int*)...
Beware that this code, as is, contains errors: bad cast, undefined behavior and platform dependent results... This is pointer arithmetic.winitially points to the content at the address of the first element oft(this is whatw = (unsigned short *)&tmeans). Then, hereafter, you access this memory as containing successive...