question
stringlengths
25
894
answer
stringlengths
4
863
I have a text file like below. I use fscanf to read until it sees "found", and then read everything else in that line into an array. ``` text text some words text text hello text text text text random text world found read1 read2 read3 don't read any of this ``` So far I have the following): ``` while(fscanf(file, "%s", var) != EOF){ if(strcmp(var, "found") == 0){ //put 'read1' 'read2' 'read3' into an array } } ``` How do I just read until the end of that line? Thanks
Thefgetsfunction will read until the end of line or file - whichever comes first! It will read from your current file read point. Here's some documentation for fgets, with an excerpt: ``` char line[LINE_MAX]; while (fgets(line, LINE_MAX, file) != NULL) { .. } ``` Edit:Then use a string operation on the line to extract what you want. Eitherstrtokorsscanfwould be OK places to start. I quite likestrchrtoo.
How do I convert physical address to kernel page structure inside kernel module? (only for x86-64 arch). following is what I have so far: ``` void *kernel_logical_address = phys_to_virt(physical_address); ``` Now, how do I getstruct pagefor this kernel_logical_address? Why do I need it? In the kernel module I am working on, it maintains a list of free pages ``` struct page *pages ``` I want to add this special page (the one points to physical_address) to this particular list. How do I do this?
Use pfn_to_page(pfn_num) macro. Pfn num == phys_addr >> 12
``` void main() { i/* nt */a=10; return; } ``` Number of tokens in above code:? I have calculated it as 13 by removing comment and not considering white space Does we consider 'i' and 'a' as single token after removing comment? Thanks lot
It's two tokens. A comment is replaced with a single space, so after the comment is removed it's equivalent to: ``` i a=10; ``` The space separates tokens. FromWikipedia article on the C Preprocessor Tokenization: The preprocessor breaks the result into preprocessing tokens and whitespace. It replaces comments with whitespace.
This is the code that i don't understand thank you!! ``` Enter integers a,b,c: 1 1 1 !a || !b++ && c: False (a-1 || b/2) && (c*=2): True (a-- || --b) && (c+=2): True a || !(b && --c): False ```
There are a few concepts inC. First is short-circuit, for&&and||. Then post-increment or pre-increment. Last, inC, integers can be used for logical operations. You can find these in most books regardingCprogramming. For example,!a || !b++ && c, a is 1, !a will be 0, or false. !b++ will be evaluated as false too because b is 1 initially and !b will make it 0. That is why the final answer is false.
I would like to iterate through all possible process id's but for this, I would need to know the limit of the process table. How can I find this out? My idea is to do something like ``` while (counter < table size) { do something } ```
I think there is no posix API to get these info directly in C,you need popen() function to call command line to get this kind of info,I do not recommend system() though it is similar with popen.(Display all process using a posix function). the system max process number can be set/check by command ulimit. ``` popen("ulimit -a max user processes","r"); ``` or you can check the current max number in current processes ids.(ps aux show all processes,sed find last line ,and awk find process id) ``` FILE *fp = popen("ps aux|sed -n '$p'|awk '{print $2F}'","r"); if(NULL!=fp) { char buff[1024]; fgets(buff,1024,fp); printf("%s\n",buff); pclose(fp); } ```
C requires different headers files, likestdio.h, stdlib.h, fcntl.h, etc.,for different functions and structure definitions, why is that? Underneath the hood it all boils down tolibcso why not create a single header file with all the definitions and prototypes?
These files are provided by the C standard library to make accomplishing common tasks easier. As to why the declarations and definitions are kept in separate files, it's for convenience and maintainability reasons. The same reason why, for example, the Linux kernel is not defined in a single C file, even though theoretically it could be.
Why would one create avolatilepointer? And suppose I want avolatilepointer which points to avolatilevariable, which of the following declarations would accomplish this: ``` volatile int *pData; ``` or ``` volatile int * volatile pData; ```
Why would one create a volatile pointer? Example: To access data whose pointer is updated by a background process. ``` Stuff * volatile VideoFrame; for (;;) { Block_Changes(); Stuff MyCopy = *VideoFrame; Allow_Changes(); Use(&MyCopy); } ``` I want a volatile pointer which points to a volatile variable, which of the following declarations would accomplish this: The 2ndmeets the goal.volatile int * volatile pData;is a:pData as volatile pointer to volatile int The 1stvolatile int *pData;is a non-volatile pointer to volatile data:pData as pointer to volatile int Thevolitlekeyword is most often used in this context.@ Eugene Sh.
Say I successfully open a file for reading using fopen, but fgets fails. I want my function to set errno appropriately. There are many errno vals associated with file operations, but none seem explicit to "something happened while reading this.". fgets also does not set errno. What is the closest errno value to use for failures reading from an already open file?
While the C standard itself rarely mandateserrnobe set, assuming you're on a POSIX or POSIX-like system,fgetswill already be settingerrnoto an appropriate value for you. See the specification forfgets: http://pubs.opengroup.org/onlinepubs/9699919799/functions/fgets.html which specifies that it can fail for any of the reasons defined forfgetc: http://pubs.opengroup.org/onlinepubs/9699919799/functions/fgetc.html The reason it's done that way is that both C and POSIX specify all the compound stdio functions in terms of repeated calls tofgetcorfputc.
Is there a way to have the decimal value (in int) of ASCII / extended ASCII characters in C (especially the extended ones) ASCII & extended ASCII table :http://www.theasciicode.com.ar/ Example of my problem with some code : ``` int a = (int) 'a'; int b = (int) '│'; printf("%i\n", a); printf("%i\n", b); ``` and the output is : ``` 97 14849154 ``` in the ASCII table, "│" is normally 179.
OP' platform is using implementation defined behavior concerningstring literalsoutside the basic coding set. UTF-8 encoding. The'│'is a Unicode characterU+2502 When coded as a UTF-8, it has the 3-byte sequence 0xE2 0x94 0x82 or in big endian order: 0xE29482 which is 14849154 (decimal) as printed out by OP. ``` int b = (int) '│'; ``` Note:ASCIIis only defined for codes 0 to 127.
I am taking input from a file and reading a character but file contains some comments starting by # so i dont want to read these inputs. How to ignore these inputs in c. Is there any command like cin.ignore() in c to do this. thanks
``` FILE * fp; char * line = NULL; size_t len = 0; ssize_t read; fp = fopen("file", "r"); if (fp == NULL) exit(EXIT_FAILURE); while ((read = getline(&line, &len, fp)) != -1) { if (read > 0 && line[0] == '#') printf("ignored\n"); //ignore this line else if (read > 0) printf("%s", line); } ```
I am confused whetherint arr[n]={0}takes constant time i.e. O(1), or O(n)?
You should expect O(N) time, but there are caveats: It is O(1) if memory occupied by array is smaller than the word size. (it may be O(1) all the way to the cache line size on modern CPUs)It is O(N) if array fits within a single tier in the memory.It is complicated if array pushes through the tiers: There are multiple tiers on all modern computers (registers, L0 cache, L1 cache, L3 cache?, NUMA on multi-CPU machines, Virtual memory(mapping to swap), ...). If array can't fit in one - there will be a severe performance penalty. CPU cache architecture impacts the time needed to zero out memory quite severely. In practice calling it O(N) is somewhat misleading given that going from 100 to 101 may increase time 10x if it falls on a cache boundary (line or whole). It may be even more dramatic if swapping is involved. Beware of the tiered memory model...
I know that during normal SSL handshake, the client receives the server's certificate and verifies it, then uses the server's public key to encrypt the session key. I want to write a SSL client in C language on Linux. During SSL handshake, it doesn't have to wait for the server's certificate and it sends the session key encrypted with the server's public key that have already been downloaded previously. I am learning how to use OpenSSL, I only need the do-handshake part here. Thanks for attention. Why to do this? The ISP or gateway can censor the certificate and block the connection according to names in the certificate.
Unfortunately, this is impossible. As part of the SSL (or TLS) protocol, the server will always send its certificate. If you would like to bypass ISP censorship, I recommend using a VPN or Tor.
If I open a file in C in any of the following ways, thenfopenworks fine. ``` fopen("file.txt", "w"); fopen("/file.txt", "w"); fopen("dir/file.txt", "w"); ``` If I put a slash '/' (or '\' in case of Windows) before directory's name as follows, thenfopenfails (returns NULL). ``` fopen("/dir/file.txt", "w"); ``` It happens both on Windows (MSVC) and Linux. What is the reason of it? Should I expunge starting slash '/'?
you need to add "." infront of the "/" ex :fopen("./dir/file.txt", "w"); if you start with "/" it will start from the root directory. That is the reason fopens returns null
No matter what "cmd" string is passed in popen(), it is never FAILING for me So fp is never NULL even for random "cmd" string. ``` FILE *fp; char path[1035]; char cmd = "randomrandomrandom"; fp = popen(cmd, "r"); if (fp == NULL) { //Handle Error exit(1); } while (fgets(path, sizeof(path)-1, fp) != NULL) { printf("%s", path); } pclose(fp); ```
popenruns an instance of theshell. Starting a shell normally succeeds. You need to determine if it hasterminatedsuccessfully.popenitself cannot do that, butpclosecan: it returns the status of the child process (or -1 if another error has occurred). So in order to verify that the command has been executed successfully, one needs to check return values of bothpopenandpclose.
I installed the MJPG-Streamer and i want to run this from a C program. I start the MJPG-Streamer entering the following code in the pi terminal: ``` LD_LIBRARY_PATH=/usr/local/lib mjpg_streamer -i "input_file.so -f /tmp/stream -n pic.jpg" -o "output_http.so -w /usr/local/www" ``` I want to run mjpg streamer from a C program, how do I do this? Thanks!
You can usesystem()function inside stdlib header.
This question already has answers here:Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer(5 answers)Closed5 years ago. I am trying to reverse a string using command line argument but I don't know why am I getting segmentation fault for this . ``` #include <stdio.h> #include <string.h> #include <assert.h> int main(int argc, char *argv[]) { char *str = argv[1]; char *rev; int i, j, k; for (i = 0; str[i] != '\0'; i++); { k = i - 1; } for (j = 0; j <= i - 1; j++) { rev[j] = str[k]; k--; } printf("The reverse string is %s\n", rev); return 0; } ```
You have to allocate memory for reverse string and makerevto point to that location. ``` char *rev = malloc(strlen(argv[1]) + 1); // 1 extra space to store null character. ``` And terminate the reversed string at the end ``` rev[j] = '\0'; ```
In my program,p_meta->paddingis a char array. When I print it in gdb, the result is: ``` (gdb) p p_meta->padding $18 = "\037\000\000\000\332\375\024e\203\000\000\000\am\333p", '\000' <repeats 215 times> ``` It seems that it use the octal format. But I can't understand what do\024eor\am\333pmean. When I use a explicit format, I got: ``` (gdb) p /o p_meta->padding $19 = {037, 0, 0, 0, 0332, 0375, 024, 0145, 0203, 0, 0, 0, 07, 0155, 0333, 0160, 0 <repeats 216 times>} (gdb) p /x p_meta->padding $20 = {0x1f, 0x0, 0x0, 0x0, 0xda, 0xfd, 0x14, 0x65, 0x83, 0x0, 0x0, 0x0, 0x7, 0x6d, 0xdb, 0x70, 0x0 <repeats 216 times>} ``` The version of gdb is: ``` # gdb -v GNU gdb (GDB) Fedora 7.12-24.fc25 ``` Thanks for any help!
It seems that Gdb use the char format for printable characters and use the octal format for non-printable characters. Theeof\024ein default format equates the0145followed by024in octal format.
I am really new C and I am trying to run the following piece of code in C: ``` #include <stdio.h> int main() { unsigned long i = 1UL << 2; int j = (i==4); printf('%d', j); return 0; } ``` But it's giving the error: ``` prog.c: In function 'main': prog.c:6:10: warning: multi-character character constant [-Wmultichar] printf('%d', j); ^ prog.c:6:10: warning: passing argument 1 of 'printf' makes pointer from integer without a cast [-Wint-conversion] In file included from prog.c:1:0: /usr/include/stdio.h:362:12: note: expected 'const char * restrict' but argument is of type 'int' extern int printf (const char *__restrict __format, ...); ``` I am not sure what's wrong here. Any help?
You can't use single quotes for a printf statement. Try this: ``` printf("%d", j); ```
I am trying to do a simple comparison to be able to do something if the file type read is a directory. Sample code : ``` int main() { DIR *dir = opendir("."); struct dirent *dirent = readdir(dir); if (dirent->d_type == DT_DIR) //do something return 0; } ``` Here is says: DT_DIRnot initialised When I try to use brackets around as such:"DT_DIR"I get the following errors: comparing pointer and integercomparison with string literal results in undefined behavior If I understand correctly I need to putDT_DIRin achararray? This is the first time I'm using these structs and functions.
The macroDT_DIRis not part of the POSIX but a glibc extension. Define#define _GNU_SOURCEat the top before including headers to get it (or define_DEFAULT_SOURCEif your glibc version is >= 2.19). In factd_typeisn't even mentioned in POSIX'sdefinition ofstruct dirent.
I am really new C and I am trying to run the following piece of code in C: ``` #include <stdio.h> int main() { unsigned long i = 1UL << 2; int j = (i==4); printf('%d', j); return 0; } ``` But it's giving the error: ``` prog.c: In function 'main': prog.c:6:10: warning: multi-character character constant [-Wmultichar] printf('%d', j); ^ prog.c:6:10: warning: passing argument 1 of 'printf' makes pointer from integer without a cast [-Wint-conversion] In file included from prog.c:1:0: /usr/include/stdio.h:362:12: note: expected 'const char * restrict' but argument is of type 'int' extern int printf (const char *__restrict __format, ...); ``` I am not sure what's wrong here. Any help?
You can't use single quotes for a printf statement. Try this: ``` printf("%d", j); ```
I am trying to do a simple comparison to be able to do something if the file type read is a directory. Sample code : ``` int main() { DIR *dir = opendir("."); struct dirent *dirent = readdir(dir); if (dirent->d_type == DT_DIR) //do something return 0; } ``` Here is says: DT_DIRnot initialised When I try to use brackets around as such:"DT_DIR"I get the following errors: comparing pointer and integercomparison with string literal results in undefined behavior If I understand correctly I need to putDT_DIRin achararray? This is the first time I'm using these structs and functions.
The macroDT_DIRis not part of the POSIX but a glibc extension. Define#define _GNU_SOURCEat the top before including headers to get it (or define_DEFAULT_SOURCEif your glibc version is >= 2.19). In factd_typeisn't even mentioned in POSIX'sdefinition ofstruct dirent.
This question already has answers here:In C, what's the size of stdout buffer?(4 answers)Closed5 years ago. I had to do a little test in my code so I wrote something like this : ``` printf("Some stuff"); while(true){ //Some other stuff } ``` But my printf was absent in my terminal. Adding\nat the end of my string solved the problem. Why did my printf disappeared ?
It is called buffering - you need to flush the buffer Use ``` fflush(stdout); ``` after theprintfto do this.
This question already has answers here:What is the strict aliasing rule?(11 answers)Closed5 years ago. I put the code directly. ``` #include <stdio.h> struct A { int a; int b; }; int main() { struct A test; double *p = (double *)&(test.a); *p = 5; printf("variable a: %d\n", &test.a); printf("variable b: %d\n", &test.b); return 0; } ``` I run this code in centos7, the compiler isgcc4.8.5.And my computer uses little ending to store. As you see, the memory of variablebwill be overwritten, I expectedais0x0000 0005andbis0x0000 0000. But the answer is: ``` variable a: 0 variable b: 1075052544 ``` Why variableais0x 0000 0000andbis0x4014 0000?
The behaviour of your code isundefined. You can't dereferenceponce you've set it to the address of something that is not adoubletype. To see what your compiler has done with this input, check the generated assembly.
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed5 years ago.Improve this question ``` for i := 0 to 5 do begin i := i + 1; counter++ end; ``` I am trying to write the code for a loop in C that will increment a counter from 0 to 5, writing out the counter value with each iteration. Use the C short-hand: counter++ to increment counter by 1 in each iteration of the loop. Am I doing it right?
No, this is not a correct syntax in C. You must write it like : ``` for ( int i = 0; i < 5 ; i++ ) { printf("Value of i: %d\n", i); } ``` For more information:https://www.tutorialspoint.com/cprogramming/c_for_loop.htm
This question already has answers here:What happens when I use the wrong format specifier?(2 answers)Closed5 years ago. i have used the code. ``` char *y; y="hello world"; printf("%c",y); ``` it just shows something useless. What mistake i am making.
Change : ``` printf("%c",y); ``` to : ``` printf("%s",y); ``` as%cspecifier indicates achar. To identify a string, you need the specifier%s.
File is there and having json data inside it. I want to know length of file.but when i try below code it but size remains 0. ``` int file_contentl_Len = 0; int fd_0 ; fd_0 = open(FILE_PATH_CONFIG_0, O_WRONLY | O_TRUNC | O_CREAT, 0644); if(fd_0 < 0) { printf("\r\nError opening Config file %s: %s\n",FILE_PATH_CONFIG_0, strerror(errno)); return -1; } struct stat buf; fstat(fd_0, &buf); file_contentl_Len = buf.st_size; printf("\r\nConfig file %s content length: %d\r\n", FILE_PATH_CONFIG_0, file_contentl_Len); ```
You opened the file for writing with truncation, creating it if necessary —O_WRONLY | O_TRUNC | O_CREAT. The size of zero tells you the truncation worked, or the file was created empty. If you wanted to read what was in the file, useO_RDONLYinstead. Or useO_RDWRand think carefully about whether to allow the file to be created.
I am trying to remove double quotes usingstrtok()in C. My string contains "b" but I want the double quotes to be removed. Whenever I usedstrtok()all I can remove is the second double quote. Output: ``` "b ``` Desired Output: ``` b ``` My attempt: ``` strtok(inttbo[ctr].value1, "\"\""); ```
Though not the best way, but you can try this. Since it is C, your string must be stored in an array. So instead of printing it from 0th index, print from first index. OR copy string using strncpy to another string from 1st index and then print
Timestamp is defined as the number of seconds elapsed since midnight of January 1, 2000, UTC. Using standard C only, how to get unix timestamp with epoch of Jan 1, 2000 UTC and not Jan 1, 1970? time(NULL)returns seconds since January 1, 1970. ``` time_t seconds; seconds = time(NULL); ```
I thought someone else might benefit from the time I spent in trying to figure this out. If you have a requirement where in standard C you want to find time elapsed since epoch other than January 1, 1970, then this how you do it, ``` time_t secondsY2K = 946684800; // Epoch / Unix timestamp for Jan 1, 2000 https://www.epochconverter.com/timestamp-list time_t unixEpochTime; time(&unixEpochTime); double seconds = difftime(unixEpochTime , epochY2k); printf("seconds since jan 1, 2000 %.f", seconds); printf("current time in UTC %s\n", asctime(gmtime(&unixEpochTime))); ```
Lets say I have the following program. Which part of memory isaallocated in? Also is the behavior same for bothcandc++? ``` // a is allocated in the ? int a[3] = {1, 2, 3}; int main() { // x is allocated in the stack int x[3] = {4, 5, 6} // y is allocated in the heap int* y = malloc(sizeof(int)*3); } ```
Where they are allocated is dependent on your machine architecture and your compiler and linker implementation (neither of which you have specified). the C++ Language Standard has nothing to say on the subject.
I am trying to print out the return code from exit() systemcall. But since program exits it doen not have a chance to print out something it will be killed. My question is that how can I print that return code in the program. ``` y = syscall(NR_mycall); //makes an exit in this second printf("%s\n", strerror(y)); ``` As expected no output! :U(
If you callexit()from multiple places in your program, and you want to know which exit code was used in these exit calls, then instead of usingexit, usesetjmpinmainand uselongjmpin your code where there is nowexitand pass the error/exit code in thelongjmpcall. Now main will know which exit/error code was used.
Timestamp is defined as the number of seconds elapsed since midnight of January 1, 2000, UTC. Using standard C only, how to get unix timestamp with epoch of Jan 1, 2000 UTC and not Jan 1, 1970? time(NULL)returns seconds since January 1, 1970. ``` time_t seconds; seconds = time(NULL); ```
I thought someone else might benefit from the time I spent in trying to figure this out. If you have a requirement where in standard C you want to find time elapsed since epoch other than January 1, 1970, then this how you do it, ``` time_t secondsY2K = 946684800; // Epoch / Unix timestamp for Jan 1, 2000 https://www.epochconverter.com/timestamp-list time_t unixEpochTime; time(&unixEpochTime); double seconds = difftime(unixEpochTime , epochY2k); printf("seconds since jan 1, 2000 %.f", seconds); printf("current time in UTC %s\n", asctime(gmtime(&unixEpochTime))); ```
Lets say I have the following program. Which part of memory isaallocated in? Also is the behavior same for bothcandc++? ``` // a is allocated in the ? int a[3] = {1, 2, 3}; int main() { // x is allocated in the stack int x[3] = {4, 5, 6} // y is allocated in the heap int* y = malloc(sizeof(int)*3); } ```
Where they are allocated is dependent on your machine architecture and your compiler and linker implementation (neither of which you have specified). the C++ Language Standard has nothing to say on the subject.
I am trying to print out the return code from exit() systemcall. But since program exits it doen not have a chance to print out something it will be killed. My question is that how can I print that return code in the program. ``` y = syscall(NR_mycall); //makes an exit in this second printf("%s\n", strerror(y)); ``` As expected no output! :U(
If you callexit()from multiple places in your program, and you want to know which exit code was used in these exit calls, then instead of usingexit, usesetjmpinmainand uselongjmpin your code where there is nowexitand pass the error/exit code in thelongjmpcall. Now main will know which exit/error code was used.
I am trying to print out the return code from exit() systemcall. But since program exits it doen not have a chance to print out something it will be killed. My question is that how can I print that return code in the program. ``` y = syscall(NR_mycall); //makes an exit in this second printf("%s\n", strerror(y)); ``` As expected no output! :U(
If you callexit()from multiple places in your program, and you want to know which exit code was used in these exit calls, then instead of usingexit, usesetjmpinmainand uselongjmpin your code where there is nowexitand pass the error/exit code in thelongjmpcall. Now main will know which exit/error code was used.
``` #include <stdio.h> int a = printf("cs136/n"); int main(){ printf("%d\n", a); } ``` Error: (initializer element is not a compile-time constant)
You can't use printf outside of an function. Move the line "int a = printf..." inside main. You variable "a" is an global variable. You can only initialize "a" with an constant. For example: ``` int a = 42; int main() { a = printf(... ```
This question already has answers here:Does C have classes?(8 answers)Closed5 years ago. I am learning how to program in C and using Eclipse helios that can compile both C and C++. When I tried to create a class, it always says creating a C++ class but not C. How do I create a C class with some default setting(#include, #include, etc.) on it?
C does not have classes. The capability of your IDE to compiler both C and C++ doesn't mean that it can transfer the constructs and concepts of C++ into a C program. It means that you can either compile a C program, or a C++ one.
I would like to know all the C standard functions that uses malloc() internally and returns a pointer to the newly allocated block of memory. AFAIK there is: strdup()getcwd()get_current_dir_name() Is that it? I am writing a complex parser that will change all C raw pointers to more elaborate C++ smart pointers and I need to know where this can't be done automatically.
The list is: malloccallocreallocaligned_alloc(new in C11) None of the functions you listed are standard C.
I have preprocessor macro in .config file as below ``` CONFIG_IDENTIFIER=y ``` Then, the Makefile contents are as below ``` -include .config OBJ += ./src/myfile.o .... myapp: $(OBJS) $(CC) $(LDFLAGS) -o myapp $(OBJS) @$(E) " LD " $@ ``` Then in ./src/myfile.c file, I try to use the perprocessor macro as below, ``` #ifdef CONFIG_IDENTIFIER .... /* Compiler does not execute in here */ .... #endif ``` But not able to get the preprocessor macro definition in ./src/myfile.c file. Any help on this?
I have preprocessor macro in .config file as belowCONFIG_IDENTIFIER=y This defines a variable local to the Makefile. It doesnotdefine a C-preprocessor macro. To make it a C-preprocessor macro you could adjust the Makefile like this: ``` -include .config CFLAGS += -DCONFIG_IDENTIFIER=$(CONFIG_IDENTIFIER) .... ```
i have the following code: ``` unsigned short a, b, c, d; unsigned long result; a = 30000; b = 40000; c = 50000; d = 60000; result = (unsigned long)(a + b + c + d) / 4; printf("result is %i", result); ``` The result of this is (30000 + 40000 + 50000 + 60000) / 4 = 180000 / 4 = 45000 which is correct. But i wonder why. I would expect the addition of unsigned shorts to overflow because it is done in 16 bit and after the addition the overflowed result is converted to unsigned long and then divided by 4. What am i missing here?
Yourshorts were promoted toints before addition. http://en.cppreference.com/w/cpp/language/implicit_conversion(the link is about C++, but C rules are basically same) Integral promotion...arithmetic operators do not accept types smaller thanintas arguments, and integral promotions are automatically applied...
Just have been trying to write a makefile that consists of 5 files --> arrays.h arrays.c pointers.h pointers.c stringtest.c When I run make however, I get and error expecting "=", "," ";" etc and it then later says that no targets are specified. Any ideas? ``` stringtest : stringtest.c arrays.o pointers.o cc -std=c99 -Wall -pedantic -Werror -o stringtest stringtest.c arrays.o pointers.o arrays.o : arrays.c arrays.h cc -std=c99 -Wall -pedantic -Werror -c -o arrays.o arrays.c pointers.o : pointers.c pointers.h cc -std=c99 -Wall -pedantic -Werror -c -o pointers.o pointers.c ```
You are using TABs for indentation? Commands for an target must be indent with it. Like: ``` pointers.o: ... ---->cc -std=c99 .. ```
How can you map a quotation mark in flex? such as: ``` """ {return ' " ';} ``` I have tried the method above and it doesn't seem to be accepting that as a rule. I have also tried ``` "\"" {return ' " ';} ``` this has also not worked.
``` "\"" {return ' " ';} ``` Isn't legalC. You need to return'"', without the spaces. It's only a single character you're matching. You coud also try: ``` ["] return '"'; ``` but in fact I prefer to omit all single special-character rules and just have ``` . return yytext[0]; ``` at the bottom of the grammar. That way yiou don't have thousands of rules for+,-, etc. etc., and incidentally illegal characters become parsing errors and can be error-recovered from.
I have preprocessor macro in .config file as below ``` CONFIG_IDENTIFIER=y ``` Then, the Makefile contents are as below ``` -include .config OBJ += ./src/myfile.o .... myapp: $(OBJS) $(CC) $(LDFLAGS) -o myapp $(OBJS) @$(E) " LD " $@ ``` Then in ./src/myfile.c file, I try to use the perprocessor macro as below, ``` #ifdef CONFIG_IDENTIFIER .... /* Compiler does not execute in here */ .... #endif ``` But not able to get the preprocessor macro definition in ./src/myfile.c file. Any help on this?
I have preprocessor macro in .config file as belowCONFIG_IDENTIFIER=y This defines a variable local to the Makefile. It doesnotdefine a C-preprocessor macro. To make it a C-preprocessor macro you could adjust the Makefile like this: ``` -include .config CFLAGS += -DCONFIG_IDENTIFIER=$(CONFIG_IDENTIFIER) .... ```
i have the following code: ``` unsigned short a, b, c, d; unsigned long result; a = 30000; b = 40000; c = 50000; d = 60000; result = (unsigned long)(a + b + c + d) / 4; printf("result is %i", result); ``` The result of this is (30000 + 40000 + 50000 + 60000) / 4 = 180000 / 4 = 45000 which is correct. But i wonder why. I would expect the addition of unsigned shorts to overflow because it is done in 16 bit and after the addition the overflowed result is converted to unsigned long and then divided by 4. What am i missing here?
Yourshorts were promoted toints before addition. http://en.cppreference.com/w/cpp/language/implicit_conversion(the link is about C++, but C rules are basically same) Integral promotion...arithmetic operators do not accept types smaller thanintas arguments, and integral promotions are automatically applied...
Just have been trying to write a makefile that consists of 5 files --> arrays.h arrays.c pointers.h pointers.c stringtest.c When I run make however, I get and error expecting "=", "," ";" etc and it then later says that no targets are specified. Any ideas? ``` stringtest : stringtest.c arrays.o pointers.o cc -std=c99 -Wall -pedantic -Werror -o stringtest stringtest.c arrays.o pointers.o arrays.o : arrays.c arrays.h cc -std=c99 -Wall -pedantic -Werror -c -o arrays.o arrays.c pointers.o : pointers.c pointers.h cc -std=c99 -Wall -pedantic -Werror -c -o pointers.o pointers.c ```
You are using TABs for indentation? Commands for an target must be indent with it. Like: ``` pointers.o: ... ---->cc -std=c99 .. ```
How can you map a quotation mark in flex? such as: ``` """ {return ' " ';} ``` I have tried the method above and it doesn't seem to be accepting that as a rule. I have also tried ``` "\"" {return ' " ';} ``` this has also not worked.
``` "\"" {return ' " ';} ``` Isn't legalC. You need to return'"', without the spaces. It's only a single character you're matching. You coud also try: ``` ["] return '"'; ``` but in fact I prefer to omit all single special-character rules and just have ``` . return yytext[0]; ``` at the bottom of the grammar. That way yiou don't have thousands of rules for+,-, etc. etc., and incidentally illegal characters become parsing errors and can be error-recovered from.
I am new to C code . Today I try to make a check input loop with error lineI want it to print error line whenever input is smaller than5But it's wrong and I can't fix it . ``` int x=0,n, s1=0 , s2=1 ; float s3=0; do{ printf("\ninput n: \n"); scanf("%d", &n); printf("n must be bigger than 5"); }while(n<=5); for(int i=1;i<=n;i++) { s1=s1+i; s2=s2*i; s3= s3+ (float)(1/i); } printf("s1 = %d\ns2 = %d\ns3= %.4f ", s1, s2 ,s3); ```
If by error line you mean this lineprintf("n must be bigger than 5");and you want to print this line only when n is smaller than 5 then just putifcondition there like this: ``` if(n<=5){ printf("n must be bigger than 5"); } ```
I'm using CLion in order to connect to remotegdbserverwhich is run on remote machine (via ssh port forwarding). I't works quite well except one thing, it downloads all linked dependenciesevery timeI connect togdbserver: So, I could not find out is there any flag to pass ingdb remoteto cache such files.
If your problem is not caching the libs but actually speeding up the GDB starting process you could set solib-absolute-prefix to a location on your host that contains all the shared libs. If you are using a nfs mounted environment for your target on your host. You could use the solib-absolute-prefix to set the path of shared libraries to your nfs host location so you don't retrieve them through the network every time you start the session.
Let's say I am changing the password of a user, ``` #include <stdio.h> #include <stdlib.h> int main() { system("net user myUsername *"); return 0; } ``` and when run this program, I get back ``` Type a password for the user: ``` How do I write to the console with a function without manually typing on to the keyboard? Is there some function like ``` writeConsoleWindow("myPass"); submitConsole(); ```
UseCreateProcess()to launchcmd.exe(which is whatsystem()does) with a redirected STDIN handle, then you can write data tocmdin your code. SeeCreating a Child Process with Redirected Input and Output. However, in the specific case ofnet usercommands, you should be using functions likeNetUserGetInfo(),NetUserSetInfo(),NetUserChangePassword(), etc instead.
If my_function() returns a 0 for success or -EINVAL for failure, then would these two statements be equivalent? ``` if( my_function() ){ ``` and ``` if( my_function() == 0){ ``` I'm aware that 1 is boolean True and 0 is boolean False in C, so I wasn't sure if the first statement would fail the if statement if my_function() successfully returned 0.
In C in boolean context expressionais typically equivalent to expressiona != 0. This means that your first variant ``` if( my_function() ){ ``` is equivalent to ``` if( my_function() != 0 ){ ``` This in turn means that your second variant is not equivalent to the first one. It is actuallyoppositeto the first one. Your first version checks for failure, while the second one checks for success.
I am working on a project which involves usingstrtokand for some reason I am getting null values instead of the actual values (which should be "Two" and "Three"). Here is my code: ``` int main(){ int h,z; char text[100] = "One Two Three"; for(h = 0; h < 4; h ++){ char *first = strtok(text, " "); printf("%s\n",first); for(z = 0; z < 3; z++){ char *second = strtok(NULL, " "); printf("%s\n",second); } } return 0; } ``` The output I am getting is: ``` One Two Three One (null) (null) One (null) (null) One (null) (null) ``` What can I do in order to get the right valueTwoandThreeinstead of null?
You could tokenize the string , save it in a double pointer and print it as many times you want!
I usepcap_open_offlinefor parsing packets. I what to check if ethernet header is type IEEE 802.1Q. I know I need to check if first 16 bits in 802.1Q tag are equal to 8100 but I do not know how to do it. Or if you know another way I can try it.
Assume you want a solution in C, here is a simple implementation: ``` struct ether_header { /* destination MAC */ uint8_t dst_mac[6]; /* source MAC */ uint8_t src_mac[6]; /* EtherType */ uint16_t ether_type; }; #define ETHERTYPE_VLAN 0x8100 /* this method gets the packet data read from pcap file and returns 1 if ether type is 802.1Q, 0 otherwise */ int is_IEEE_802_1Q(const uint8_t* packet_data) { /* cast ethernet header */ ether_header* eth_header = (ether_header*)packet_data; /* assuming big endian as most pcap files are in big endian */ if (eth_header->ether_type == ETHERTYPE_VLAN) { return 1; } return 0; } ```
As in the subject. I'm wondering if it is possible to get encrypted bytes like below when using AES128 CBC: ``` 7b 22 63 6d 64 22 3a 22 73 65 74 41 70 22 2c 22 73 63 6f 22 2c 22 70 61 00 73 22 3a 22 70 61 73 73 77 6f 72 64 22 7d 00 00 00 00 00 00 00 00 00 ``` Note the NULL byte in the second row. EDIT: A bit of background behind this question. I have a C function that takes my buffer and plain text (utf8) after calling it I need to know who much of the buffer was filled up.
Yes, any byte value is possible including 0. The implied question here is "can I use string handling functions on encrypted data". You cannot because 0 is a valid value. You need to keep track of the number of bytes in the encrypted data.
My Program task is to remove and character <32 and >127 ascii value, but output shows me 2 spaces instead. Example : input: préféré expected output : pr f r my output : pr(2spaces)f(2spaces)r(2spaces) ``` #include<stdio.h> #include<string.h> int main() { unsigned char str[100]; unsigned char space = ' '; fgets(str,100,stdin); int i=0; int length = strlen(str); while(i<length) { if( ((int)str[i]>32) && ((int)str[i]<127) ) { i++; continue; } else { str[i]=space; } i++; } printf("%s\n",str); } ```
It's probably because the characters likeé(non-ASCII) take up 2 bytes. So your loop runs twice for eaché, thus putting 2 spaces in place ofé. On a related note, useisascii()from<ctype.h>to test for ASCII characters.
Let's say we have this C code snippet: ``` if (condition) x = a; else x = b; ``` Is it allowed to insert comments like this, without changing the semantics of the code: ``` if (condition) /* blah blah blah */ x = a; else x = b; ``` (if there were curly braces, the answer would be obviously yes, but what about these cases of if statements without curly braces?)
Comments have no effect on the code other than the fact that they help to understand and edit code later. The code you have shown is valid. If theifstatement is followed by codes inside curly braces all the codes inside the brace will get executed if the condition forifis met. If there is no curly braces to group the code, the statement immediately after theifstatement gets executed. If there is comments before this statement it will not effect the code as the comments will be removed when the code is compiled.
Let's say I have a char *str and I want to assign it characters one by time using using pointers and incrementing ? I've done : ``` char *str; char c = 'a'; *str++ = c; ``` But it doesn't work. How can I do that ?
stris just a pointer. It doesn't point anywhere valid (especially not to some memory you could write to). A simple possibility would be to have it point to an array: ``` char buf[1024] = {0}; // room for 1024 chars (or 1023 + a 0 byte for a string) char *str = buf; char c = 'a'; *str++ = c; ```
I need to compute the average of each row and store in the last element. I managed to do but the subsequent rows are the accumulated average from the previous row. eg: input: 1 2 3 0 4 5 6 0 output: 1.00 2.00 3.00 2.00 4.00 5.00 6.007.00(This should be 5.00) Here is my code ``` void findAverage2D(float matrix[4][4]) { int i,j = 0; float sum,avg=0; for(i=0;i<4;i++) { for(j=0; j<4;j++) { sum+= matrix[i][j]; } avg = sum/3; matrix[i][3] =avg; } } ``` Thanks in advance. :)
Move variable "sum" inside first for loop - ``` for(i=0;i<4;i++) { float sum = 0; ```
This question already has answers here:What happens to a declared, uninitialized variable in C? Does it have a value?(9 answers)Closed5 years ago. I just made this short program. Can someone please explain why I am getting 2 as a result here? Here is the code ``` #include <stdio.h> #include <stdlib.h> int main() { int variable; int a; a=variable; a=200; printf("%d",variable); return 0; } ```
Because you print the value of an uninitialized variable. It will have anindeterminate(and seemingly random) value. The assignment you make toajust copies the value ofvariableand then of200intoa. The value ofvariableremains unmodified and indeterminate. I recommend youfind a good beginners book or twoto read.
Here is one not-so-common way of initializing the pointer: ``` int *p = (int[10]){[1]=1}; ``` Here, pointer point to compound literals. ``` #include <stdio.h> int main(void) { int *p = (int[10]){[1]=1}; printf("%d\n", p[1]); } ``` Output: ``` 1 ``` This program is compiled and run fine in G++ compiler. So, Is it the correct way to initializing a pointer to compound literals? orIs it undefined behaviour initialize pointer to compound literals?
Yes, it is valid to have a pointer to compound literals. Standard allows this. n1570-§6.5.2.5 (p8): EXAMPLE 1 The file scope definitionint *p = (int []){2, 4};initializespto point to the first element of an array of two ints, the first having the value two and the second, four. The expressions in this compound literal are required to be constant.The unnamed object has static storage duration.
I need to compute the average of each row and store in the last element. I managed to do but the subsequent rows are the accumulated average from the previous row. eg: input: 1 2 3 0 4 5 6 0 output: 1.00 2.00 3.00 2.00 4.00 5.00 6.007.00(This should be 5.00) Here is my code ``` void findAverage2D(float matrix[4][4]) { int i,j = 0; float sum,avg=0; for(i=0;i<4;i++) { for(j=0; j<4;j++) { sum+= matrix[i][j]; } avg = sum/3; matrix[i][3] =avg; } } ``` Thanks in advance. :)
Move variable "sum" inside first for loop - ``` for(i=0;i<4;i++) { float sum = 0; ```
This question already has answers here:What happens to a declared, uninitialized variable in C? Does it have a value?(9 answers)Closed5 years ago. I just made this short program. Can someone please explain why I am getting 2 as a result here? Here is the code ``` #include <stdio.h> #include <stdlib.h> int main() { int variable; int a; a=variable; a=200; printf("%d",variable); return 0; } ```
Because you print the value of an uninitialized variable. It will have anindeterminate(and seemingly random) value. The assignment you make toajust copies the value ofvariableand then of200intoa. The value ofvariableremains unmodified and indeterminate. I recommend youfind a good beginners book or twoto read.
Here is one not-so-common way of initializing the pointer: ``` int *p = (int[10]){[1]=1}; ``` Here, pointer point to compound literals. ``` #include <stdio.h> int main(void) { int *p = (int[10]){[1]=1}; printf("%d\n", p[1]); } ``` Output: ``` 1 ``` This program is compiled and run fine in G++ compiler. So, Is it the correct way to initializing a pointer to compound literals? orIs it undefined behaviour initialize pointer to compound literals?
Yes, it is valid to have a pointer to compound literals. Standard allows this. n1570-§6.5.2.5 (p8): EXAMPLE 1 The file scope definitionint *p = (int []){2, 4};initializespto point to the first element of an array of two ints, the first having the value two and the second, four. The expressions in this compound literal are required to be constant.The unnamed object has static storage duration.
Here is one not-so-common way of initializing the pointer: ``` int *p = (int[10]){[1]=1}; ``` Here, pointer point to compound literals. ``` #include <stdio.h> int main(void) { int *p = (int[10]){[1]=1}; printf("%d\n", p[1]); } ``` Output: ``` 1 ``` This program is compiled and run fine in G++ compiler. So, Is it the correct way to initializing a pointer to compound literals? orIs it undefined behaviour initialize pointer to compound literals?
Yes, it is valid to have a pointer to compound literals. Standard allows this. n1570-§6.5.2.5 (p8): EXAMPLE 1 The file scope definitionint *p = (int []){2, 4};initializespto point to the first element of an array of two ints, the first having the value two and the second, four. The expressions in this compound literal are required to be constant.The unnamed object has static storage duration.
What is wrong with this code? It is giving me ridiculously high values for Celsius.` ``` #include <stdio.h> int temp (int fahr, int celsius) { celsius = 5*(fahr-32)/9 } int main() { int fahr, celsius; printf ("Enter fahrenheit value here: "); scanf("%d", &fahr); printf ("The Celsius value is: %d ",celsius); return 0; } ``` `
``` #include <stdio.h> int temp(int fahr) { return 5*(fahr-32)/9; } int main() { int fahr, celsius; printf ("Enter fahrenheit value here: "); scanf("%d", &fahr); celsius = temp(fahr); printf ("The Celsius value is: %d ", celsius); return 0; } ```
I have a virtual machine with ArchLinux installed. Here when I compile with GCC by runninggcc file.cit gives me a shared library instead of an executable. Later I find out that the problem is related only toGCC 7.2, in fact, when I compile withGCC 6.4, the output file is an executable. How do I fix this?
Thefileutility is just incorrect in calling your program a shared library. It is a position-independent executable (PIE). If you really don't want this, you can specify-no-pieat link time, or build a gcc toolchain with--disable-default-pie, but in general you shouldn't need to change this.
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed5 years ago.Improve this question ``` error: expected expression before ';' token graph[ ptr->count ].count- ; ^ ``` I am getting the error shown when I compile my code in Geany. Can anyone please help what to do?
Assuming you’re trying to decrement...count by 1...you need one more minus sign, like this ``` int i = 10; i--; ``` to be a valid expression in C/C++.
I am working with a C code base that uses an API function (https://developer.gnome.org/glib/stable/glib-Hash-Tables.html#g-hash-table-size) that returns a guint. I needed to pass this along downstream as an int. I am wondering if there's any way to do this? I searched the docs and Google but came up empty.
The mere existence of these typedefs baffles me. Checkglib/gtypes.h: ``` typedef char gchar; typedef short gshort; typedef long glong; typedef int gint; typedef gint gboolean; typedef unsigned char guchar; typedef unsigned short gushort; typedef unsigned long gulong; typedef unsigned int guint; ``` So no conversion is needed betweenunsigned intandguint, they are the same type. The usual warnings about converting betweenunsigned intandintapply.
How can I read in C a line from the console to not initialize a some array likeint buf[30];? I need to allocate it once and required length, i.e. to I can know input characters count before read it...Is it possible in C?
There is no way to know the number of characters available in standard input before reading them. You can, however, usegetline(3), which will read until\nand then return the data in a dynamically-allocated buffer holding the data (along with the size of that buffer). You must free the buffer when you're done with it. You should be aware that this will routine will block until it reads a newline. It's also difficult to use this routine safely, as malformed inputs are not handled well. (What if the input has no newline?) This is one of the reasons many applications often read a fixed length input.
In my function I want to return an empty string"", function looks like this: ``` char *myFunction(nodeType *arg){ if (something){ return anotherFunction(arg); } else { return EMPTYSTRING; } } ``` (EMPTYSTRING should be replaced with correct expression to return"") Some ways I came up with: ``` return "" return '\0' ``` What is the right way to return an empty string?
It is not good idea to return "". Because, it is const char and you may try to dealloc it in where you get it from the function and this likely crashes your application. So, I would returnstrdup(""), so you can free it safely.
I'm attempting to display the contents of a specific address, given a char* to that address. So far I had attempted doing it using the following implementation ``` int mem_display(char *arguments) { int address = *arguments; int* contents_pointer = (int*)address; int contents = *contents_pointer; printf("Address %p: contents %16x\n", contents_pointer, contents); } ``` But I keep getting a "Segmentation Fault (Core Dumped)" error. I attempted to make a dummy pointer to test on ``` char foo = 6; char *bar = &foo; ``` But the error still persists
I'm finding it hard to explain what the problem is because almost every single line in your code is wrong. Here's what I would do: ``` void mem_display(const void *address) { const unsigned char *p = address; for (size_t i = 0; i < 16; i++) { printf("%02hhx", p[i]); } putchar('\n'); } ```
I receive two string values over the UART to an stm32f3 and would like to concatenate them to a float, but I actually don't see how to do this. Let's do this in the example below. ``` char *s1="100"; char *s2="09"; //should result in 100.09 float x=???(s1,s2); ``` How can I achieve this?
I'd convert each string to an integer, then use arithmetic: ``` int whole = atoi(s1); int frac = atoi(s2); float x = whole + frac / powf(10, strlen(s2)); ``` The last part computes 10^strlen(s2) because "09" means 09/100, "5" means 5/10, etc. Ifpowf()doesn't work on your system (as you said in a comment), you can use this (only good for small non-negative inputs but that's what you have): ``` float myexp10(unsigned x) { if (x == 0) return 1.0; float res = 10; while (--x) res *= 10; return res; } ```
I am interested in programming my own OS from scratch(in C). However, every tutorial I encounter has made a message print on the screen by writing directly to the VDU. Why can't I use standard library functions while writing my OS? I don't have much problem in writing directly to the VDU. However, it sometimes makes my mind utterly confused(especially in large programs). Are the library functions not converted into the same low-level code as the functions created by us?
This is a kind of chicken-and-egg problem: Standard library functions use OS functions to print to the screen (deep down there, someone actuallyneeds towrite directly to the hardware). Without an OS (because you just start writing one) this will not work. The standard library you want to use will need to be written specifically for and together with your OS.
In my function I want to return an empty string"", function looks like this: ``` char *myFunction(nodeType *arg){ if (something){ return anotherFunction(arg); } else { return EMPTYSTRING; } } ``` (EMPTYSTRING should be replaced with correct expression to return"") Some ways I came up with: ``` return "" return '\0' ``` What is the right way to return an empty string?
It is not good idea to return "". Because, it is const char and you may try to dealloc it in where you get it from the function and this likely crashes your application. So, I would returnstrdup(""), so you can free it safely.
I'm attempting to display the contents of a specific address, given a char* to that address. So far I had attempted doing it using the following implementation ``` int mem_display(char *arguments) { int address = *arguments; int* contents_pointer = (int*)address; int contents = *contents_pointer; printf("Address %p: contents %16x\n", contents_pointer, contents); } ``` But I keep getting a "Segmentation Fault (Core Dumped)" error. I attempted to make a dummy pointer to test on ``` char foo = 6; char *bar = &foo; ``` But the error still persists
I'm finding it hard to explain what the problem is because almost every single line in your code is wrong. Here's what I would do: ``` void mem_display(const void *address) { const unsigned char *p = address; for (size_t i = 0; i < 16; i++) { printf("%02hhx", p[i]); } putchar('\n'); } ```
I receive two string values over the UART to an stm32f3 and would like to concatenate them to a float, but I actually don't see how to do this. Let's do this in the example below. ``` char *s1="100"; char *s2="09"; //should result in 100.09 float x=???(s1,s2); ``` How can I achieve this?
I'd convert each string to an integer, then use arithmetic: ``` int whole = atoi(s1); int frac = atoi(s2); float x = whole + frac / powf(10, strlen(s2)); ``` The last part computes 10^strlen(s2) because "09" means 09/100, "5" means 5/10, etc. Ifpowf()doesn't work on your system (as you said in a comment), you can use this (only good for small non-negative inputs but that's what you have): ``` float myexp10(unsigned x) { if (x == 0) return 1.0; float res = 10; while (--x) res *= 10; return res; } ```
I am interested in programming my own OS from scratch(in C). However, every tutorial I encounter has made a message print on the screen by writing directly to the VDU. Why can't I use standard library functions while writing my OS? I don't have much problem in writing directly to the VDU. However, it sometimes makes my mind utterly confused(especially in large programs). Are the library functions not converted into the same low-level code as the functions created by us?
This is a kind of chicken-and-egg problem: Standard library functions use OS functions to print to the screen (deep down there, someone actuallyneeds towrite directly to the hardware). Without an OS (because you just start writing one) this will not work. The standard library you want to use will need to be written specifically for and together with your OS.
I have just started off with C socket programming. I have read that 0 as an integer constant, refers to a null pointer when compared with a pointer and '\0' refers to a null character, something that sets all the bits to 0. And, in the case concerning my question, I know I should probably be using '\0'. But I can see a lot of implementations that uses 0 instead. What would be the difference as such? I don't wanna go with whatever that works. I can't move on till I understand why. Thanks!
There is no difference. They are equal.
After many years of reading on this site (and getting many helpful solutions), it's time for me to ask a question:) I was wondering about the default enum values. I'm using enums to send error codes from an MCU to a PC (and vice versa) is it a good practice (and safe) to define enums like this C: ``` typedef enum { no_error = 0, error_1 error_2, ... } ``` C# ``` enum { no_error = 0, error_1, error_2, } ``` All enum values are cast intoUint32before Transfer. Can I always assume thaterror_1 = 1anderror_2=2on C and C# side? I'm using the GCC Compiler.
Yes, both languages guarantee that if you don't explicitly give an enum value as integer value then it is one more than the previous enum value.
This question already has answers here:Bitwise '&' operator(6 answers)Closed5 years ago. I've found this in code, but I never encountered such thing as&, only&& ``` if ((code & 1) == 1){ ``` Can you tell me what is it?
This isbitwise operator. This means that someaction is done with 'code' before comparasion happens. Wikipedia says: A bitwise AND takes two equal-length binary representations and performs the logical AND operation on each pair of the corresponding bits, by multiplying them. Thus, if both bits in the compared position are 1, the bit in the resulting binary representation is 1 (1 × 1 = 1); otherwise, the result is 0 (1 × 0 = 0 and 0 × 0 = 0). By the way, there is such thread but about C++ not C,here.
I want to create a program to print out the first printf statement, Then in the next line, it will clear the first printf statement and print the next statement. Please help me fix the code. ``` printf("Please wait while Loading..."); Sleep(2132); printf("Done Loading"); ```
This should work: ``` printf("Please wait while Loading..."); fflush(stdout); // flush output, this is necessary on some platforms, // otherwise the text won't be printed immediately Sleep(2132); printf("\rDone Loading \n"); // the \r returns to the start of the line, // and the trailing spaces are necessary to // erase the remaining text ```
``` #include <stdio.h> int main() { int num=1234; printf("%p", &num); return 0; } //Ouput: //0xffffcbfc ``` Is 0xffffcbfc a RAM or a Hard Drive address memory?
That code is, strictly speaking, exhibiting undefined behavior. You must convert the pointer tovoid *since that's what%pexpects: ``` printf("%p\n", (void *) &num); ``` And it's probably unspecified from C's point of view exactly what kind of physical device holds the address, but on a typical computer it's going to be RAM.
Is there a way to create a string of characters from a set of elements taken from a existing array? Example: say I have an array of four characters ``` #include <cs50.h> #include <stdio.h> #include <string.h> int main (void) { char abcd[] = "abcd"; string sabcd = "0"; } ``` Is there a way I can create strings with a subset of array elements, such as "ac", "cd" and so on? Edited: added libraries for clarification.
You could always index the characters you wish your substring to have. For example: ``` char adb[4] = {abcd[0], abcd[3], abcd[1], '\0'}; ``` Another approach is to usestrncpy(), like this: ``` #include <stdio.h> #include <string.h> int main (void) { char abcd[] = "abcd"; char bc[3] = ""; strncpy(bc, abcd + 1, 2); puts(bc); } ``` Output: bc
I am working on porting a large piece of software to a new platform, and basically at this point all I am doing is fixing compilation errors I stumble upon. My management is asking me "how far you've got?" - how can I measure how much I was able to compile successfully and how much is to go? This is c sources only, and the logs I get from 'make' are so insanely stuffed, that I don't even know what to grep to find this out.
I'd naively compare the number of .cpp files and .o files: ``` #!/bin/bash number_of_sources=$(find . -name \*.cpp | wc -l) number_of_objects=$(find . -name \*.o | wc -l) progress=$(echo "${number_of_objects} * 100 / ${number_of_sources}" | bc) echo "${progress}% of translation units successfully compiled." ``` This would need adaption related to your context (some subpath not to look into like.git/, some renaming, ...)
``` int main(int argc, char *argv[]) { if (argc < 2) { printf("missing argument\n"); exit(-1); } printf("%s %s %s", argv[1], argv[2]); return 0; } ``` Just want to give command line arguments like ./a 3 4 without using .out in linux terminal thanks!!
Assuming your source file wasa.c, just use the-o("output") flag when you compile it, like this: ``` cc -o a a.c ``` Or, if you already did ``` cc a.c ``` meaning it left it ina.outby default, you can always rename it: ``` mv a.out a ``` Of course you can call it anything you want: ``` cc -o mytestprogram a.c ```
I am trying to run the "libwebsockets-test-server" that is installed with the LWS library, but it will not run because "lwsts[31616]: libuv support not compiled in". I have checked that libuv is installed (1.8.0). I also changed the setting for LIBUV in cmake and recompiled the library. ``` LWS_USE_LIBUV = 1 ``` How do I get the project compiled with libuv? I am on Ubuntu 16.04, cross-compiling using arm-linux-gcc. I have successfully compiled programs, loaded them to the embedded board (TS-7800), and run the executable, but not yet with LWS. I am relatively new to Linux and cross-compilers.
Configuring the cmake using 'cmake -DLWS_WITH_PLUGINS=1', changes the configuration to set LWS_USE_LIBUV equal to 1 and compiles libuv with the make. Since I was planning to use plugins with LWSWS, this was an appropriate fix for the problem.
I am trying to run the "libwebsockets-test-server" that is installed with the LWS library, but it will not run because "lwsts[31616]: libuv support not compiled in". I have checked that libuv is installed (1.8.0). I also changed the setting for LIBUV in cmake and recompiled the library. ``` LWS_USE_LIBUV = 1 ``` How do I get the project compiled with libuv? I am on Ubuntu 16.04, cross-compiling using arm-linux-gcc. I have successfully compiled programs, loaded them to the embedded board (TS-7800), and run the executable, but not yet with LWS. I am relatively new to Linux and cross-compilers.
Configuring the cmake using 'cmake -DLWS_WITH_PLUGINS=1', changes the configuration to set LWS_USE_LIBUV equal to 1 and compiles libuv with the make. Since I was planning to use plugins with LWSWS, this was an appropriate fix for the problem.
Here is my code for the pset1 greedy. Now it all works from what I can tell and tested and used cs50 check aswell... Problem is it was hinted in the walk through and me having to look up how to use round properly, that I maybe should of used modular somewhere? I get what it does. eg 10 % 3 = 1. Is it worth doing it again using modular %. Also any advice on my method? Thanks in advance.
To calculate how much coins are needed you can dividechange_intby the current coin value. To calculate how much change is left you can the do the same calculation, but only with%instead of/. This will speed up the programm for large change values because you don't have to use thewhileloop anymore. Also as Weather Vane wrote in a comment you can put the four coin values in an array and do the calculation in a loop.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed5 years ago.Improve this question When is it appropriate to use ``` void* space_to_use = malloc(size); ```
``` void* space_to_use = malloc(size); // malloc always return void pointer that means it can be typecast to any type. // before using void pointer it is necessary to typecast it into proper type. // for example:- // if size is 8 byte.It will allocate 8 byte of memory. /* void* space_to_use = malloc(size); char * ptr = (char*)space_to_use; */ // These two line can be combine in one statement. char * ptr = (char*)malloc(size*sizeeof(char)); // NOTE:sizeof(char) is to make sure platform independent. // Same for int if we want to store some integer. int * ptr = (int*)malloc(size*sizeeof(int)); ```
Theprintf()function uses the format specifier%sto printchar *. The standard does not specify howcharis implemented as signed or unsigned. So whencharis implemented as signedchar, and we use%sto printunsigned char *, is it safe to do this? Which format specifier should we use in this case?
... whencharis implemented insigned char, and we use"%s"to printunsigned char*. Is it safe to do this? Yes it is safe. ``` char *cp = ...; signed char *scp = ...; unsigned char *ucp = ...; printf("%s", cp); // OK. printf("%s", scp); // OK. printf("%s", ucp); // OK. ``` (%s) ... the argument shall be a pointer to the initial element of an array of character type. ... C11dr §7.21.6.1 8The three typeschar,signed char, andunsigned charare collectively called thecharacter types. C11 §6.2.5 15
``` int i,j; for(i=0;j=10;j>=0;i<10;i++;j--){ printf("%d %d",i,j); } ``` It brings error while executing, how to rectify it and what is the correct syntax for using multiple iterators in for loop
Aforloop has the following syntax: ``` for ( expression ; expression ; expression ) ``` There are 3 expressions separated by semicolons. You have 6 expressions separated by semicolons. That's invalid syntax. You should write it as follows: ``` for(i=0,j=10; j>=0 && i<10; i++,j--) ``` For the first expression, separate the two assignments with the comma operator. Similarly for the third expression. For the second, you want both conditionals to be true, so separate them with the logical AND operator&&. Also, the error you got was not while executing but whilecompiling.
My application runsread(sockfd, buffer, BUFFSIZE, 0). I know the kernel needs to do some copy work behind the scene. How many memory copies occur whenbufferis allocated on the stack, and will it change ifbufferis allocated on the heap? Thanks.
Number of memory copies is always the same no matter if buffer is onheaporstack. Difference is only where is the memory located where you copy your data. In case of stack, you can enter to stack overflow and your program will have undefined behavior while if you do it on heap, you can enter to memory leaks if you don't free your memory after you don't need it anymore.
I wanted to ask you because when I run my program, I get that the arithmetic mean of 5 and 18 is 11, not 11.5? I put my program in C: ``` #include <stdio.h> int main(void) { int a,b; a = 5; b = 18; printf("La media aritmética de %d i %d es %d\n", a, b, (a+b)/2); return 0; } ``` Thanks
Modify your code like below - ``` #include <stdio.h> int main(void) { float a,b; a = 5; b = 18; printf("La media aritmética de %.f i %.f es %f\n", a, b,(a+b)/2); return 0; } ``` Currently, you are getting 11. Because when this operation(a+b)/2is happening, it is saving the result in an integer. Which is ignoring the floating point value. EDIT:If you want to print only 2 floating points then do the following - printf("La media aritmética de %.f i %.f es %%0.2f\n", a, b,(a+b)/2); For more info please see thisFloating point rounding
I have a C project with 2 modules - A and B. B has a function that calls a function from A. ``` int B_func() { if (1 == A_func()) {return 1;} return 2; } ``` I use unity to test these modules. ``` TEST(B, test_b) { TEST_ASSERT_EQUAL(1, B_func()) } ``` When I test module B, I want to mock A_func so it will use my implementation and change the return value. Is there a way to do this without changing the source code of module B?
I ended up using Mimick.https://github.com/diacritic/Mimick It's a bit cumbersome. I needed to compile my project as a shared object and link it to my tests so my functions will be in the GOT, so it is not ideal, but successfully solves my problem.
Given the following struct ``` struct foo { int b; int a; int r; }; ``` I want to create a new type from this struct, like following ``` typedef struct foo * foo_t; ``` That is to say thatfoo_tis supposed to equal a pointer ofstruct foo.Sostruct foo *var;<=>foo_t var; Why am I not able to malloc this struct from its type? foo_t var = malloc(sizeof(*foo_t));throws an error at the compilation time error: expected expression beforefoo_tfoo_t var = malloc(sizeof((*_foo_t)));
Becausesizeof's operand must be either an expression or a parenthesized type name.*foo_tis neither. I strongly recommend against hiding pointers behind typedefs. However, you can do the following: ``` foo_t var = malloc(sizeof *var); ``` varis not a type, so*varis a valid expression.
I wanted to ask you because when I run my program, I get that the arithmetic mean of 5 and 18 is 11, not 11.5? I put my program in C: ``` #include <stdio.h> int main(void) { int a,b; a = 5; b = 18; printf("La media aritmética de %d i %d es %d\n", a, b, (a+b)/2); return 0; } ``` Thanks
Modify your code like below - ``` #include <stdio.h> int main(void) { float a,b; a = 5; b = 18; printf("La media aritmética de %.f i %.f es %f\n", a, b,(a+b)/2); return 0; } ``` Currently, you are getting 11. Because when this operation(a+b)/2is happening, it is saving the result in an integer. Which is ignoring the floating point value. EDIT:If you want to print only 2 floating points then do the following - printf("La media aritmética de %.f i %.f es %%0.2f\n", a, b,(a+b)/2); For more info please see thisFloating point rounding
I have a C project with 2 modules - A and B. B has a function that calls a function from A. ``` int B_func() { if (1 == A_func()) {return 1;} return 2; } ``` I use unity to test these modules. ``` TEST(B, test_b) { TEST_ASSERT_EQUAL(1, B_func()) } ``` When I test module B, I want to mock A_func so it will use my implementation and change the return value. Is there a way to do this without changing the source code of module B?
I ended up using Mimick.https://github.com/diacritic/Mimick It's a bit cumbersome. I needed to compile my project as a shared object and link it to my tests so my functions will be in the GOT, so it is not ideal, but successfully solves my problem.
Given the following struct ``` struct foo { int b; int a; int r; }; ``` I want to create a new type from this struct, like following ``` typedef struct foo * foo_t; ``` That is to say thatfoo_tis supposed to equal a pointer ofstruct foo.Sostruct foo *var;<=>foo_t var; Why am I not able to malloc this struct from its type? foo_t var = malloc(sizeof(*foo_t));throws an error at the compilation time error: expected expression beforefoo_tfoo_t var = malloc(sizeof((*_foo_t)));
Becausesizeof's operand must be either an expression or a parenthesized type name.*foo_tis neither. I strongly recommend against hiding pointers behind typedefs. However, you can do the following: ``` foo_t var = malloc(sizeof *var); ``` varis not a type, so*varis a valid expression.
I saw the following line of codeherein C. ``` int mask = ~0; ``` I have printed the value ofmaskin C and C++. It always prints-1. So I do have some questions: Why assigning value~0to themaskvariable?What is the purpose of~0?Can we use-1instead of~0?
It's a portable way to set all the binary bits in an integer to 1 bits without having to know how many bits are in the integer on the current architecture.
I've created a SDL2 based project, that after the building proccess creates a prog.exe file.Sending the project to other systems creates an error:ERROR: The program can't start because SDL2.dll is missing from your computer.Which makes sense, because they didn't install sdl to begin with.Is there a way for me to send them the .exe file that already has all the needed libraries, without making them to install SDL by themselves?Thanks.
You can take sdl2.dll from your computer and copy that to the same directory on the other computer as you have the .exe in. Typically an installer for your application would handle this.
I have the following C code which works: ``` int ex(unsigned int x) { int mask = 0x55555555; int a = ((x >> 0) & mask ); return a + ((x >> 1) & mask ); } ``` However, when I expand it to this, I get a different result: ``` int ex(unsigned int x) { int mask = 0x55555555; int a = ((x >> 0) & mask ); int b = ((x >> 1) & mask ); return a + b; } ``` What is the reason for this difference? EDIT: Note, I'm compiling this for 32bit.
What is the reason for this difference? The 1stsnippet returns the result of adding twounsigneds with the result being (implicitly) converted to anint. The 2ndsnippet returns the result of adding twoints . More on "The Usual Arithmetic Conversions": Usual arithmetic conversions in C : Whats the rationale behind this particular ruleC usual arithmetic conversionsImplicit integer type conversion in C
Given the following varibles ``` int *a = 0; char *b = "string" ``` I can put them both into avoid *hold;I don't find the way forfunction pointers. ``` void (*hello)(char param1, char param2); char (*another)(); ``` Is it even possible to stock these2 different typesinto a generalonesuch as void *? And then retrieve them with casting?
You can cast function pointers to any other function pointer type and back. Just choose a target type likevoid (*)(void). From the C99 standard: A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer.