question
stringlengths
25
894
answer
stringlengths
4
863
Can someone explain me the working of scanf. If i am entering s as integer it would work fine but i enter a character it would run continuously till it exits the loop. So it is not removing the character from the buffer and not asking for input. Can you provide more insight on scanf and it's internal implementation `...
%cspecifier is for characters not forintdata types. Using wrong format specifier for a data type invoke undefined behavior. Also note thatiis not incrementing in the second loop. This will lead to an infinitewhileloop.
I am facing a weird problem retrieving tcp header and trying to print source and destination ports code : ``` src_p = tcp->th_sport; dest_p = tcp->th_dport; output (in hex): 8e08 and 64a2 ``` wireshark shows that the ports are 088e and a264 why is libpcap swapping the bytes? or is there something wrong with my c...
The ports are stored innetwork byte order(big endian) in the TCP header (most protocols send multi-byte numbers over a network using big endian, hence the nickname). Wireshark is merely converting the bytes tohost byte order(big or little endian, depending on your PC's hardware, hence the nickname) when it is transla...
This question already has answers here:In C, why is sizeof(char) 1, when 'a' is an int?(5 answers)Closed7 years ago. ``` char c = 'A'; printf("%d\n",sizeof(c));// output = 1 printf("%d\n",sizeof('A')); // output = 4 ``` Why thesizeofoperator gives different output for same character? Please Help
cis a variable of typechar; its size is 1 byte. 'A'is anintliteral - don't ask me why the standard says that. Its size is 4 bytes on your platform (the same assizeof(1)).
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question What happens to fwrite if it the drive is full? Assuming that it was compiled on a windows machine with vis...
If a write cannot be performed,fwrite()either returns a short item count (if some items have been written before an error occurred) or0.fwrite()does not block if an error occurs. To differentiate and end-of-file condition from an IO error, use thefeof()andferror()functions.
I was looking at this open source boot loader and I saw this line of code. What is happening on the last line? Is that some kind of pointer to a function, with a cast to an address? ``` uint8_t ret = init_api(); uint16_t ptr; ptr = PGM_READ_WORD(JUMP_TABLE_INDEX(6)); ret = ( (uint8_t(*)(uint32_t, uint8...
ptris casted to a pointer to a function ``` uint8_t f(uint32_t, uint8_t *, uint8_t) ``` and the function gets called with parametersaddr,data,erase.
I have this scanf code line: ``` scanf("%d,%d %d,%d", &X, &Y, &dirX, &dirY); ``` How can I check if the input, which should be for example1,2 3,4(2 commas) is indeed written like this, and only like this? I don't want to accept1,2,3,4(3 commas) for example.
What you can do is check the return value ofscanf()to see whether the user has entered the input is the proper format or not. Like ``` int main (void) { int i, j, k, l; if(scanf("%d,%d %d,%d", &i, &j, &k, &l) != 4) printf("User entered input in wrong format\n"); printf("please enter in the fo...
I want initialize a function pointer so that it is null. Which of these two ways is preferred? ``` void (*Pointer)(void) = NULL; ``` Or ``` void (*Pointer)(void) = (void (*)(void))0; ```
0is implicit convertible to any pointer type. Though how your compiler implementsNULLdepends. In your code you can simply write void (*Pointer)(void) = 0;but it won't be portable , so writevoid (*Pointer)(void) = NULL;
I have the following code in a file named foo.c. ``` /** @file */ #include <stdio.h> /** Prints hello */ #define hello() printf("hello, ") int main() { /** Prints world */ #define world() printf("world\n") hello(); world(); } ``` I have a file named Doxyfile in the same directory. ``` PROJECT_NAME...
Macros/variables/etc inside functions bodies areoutside the scope of Doxygenand thus no documentation is generated for them at this time.
Within a function, we have the following: ``` __asm__("movl $0xe4ffffe4, -4(%ebp)"); ``` Does this mean that we move the contents of the memory address 0xe4ffffe4 over to the ebp register?
This: ``` movl $0xe4ffffe4, -4(%ebp) ``` Says "move the 4-byte value 0xe4ffffe4 into the slot 4 bytes before the address stored in register ebp."
In theonline manual, I can see, Nested functions are supported as an extension in GNU C, but are not supported by GNU C++. What does that mean? How do I get that extension?
You don't need togetthe extension. That is a feature embedded in theGNU Ccompiler. FWIW, theextensionhere point to the extension over the C standard(s). To elaborate, from theonline manual 6 . ExtensionsGNU C provides several language features not found in ISO standard C. (The -pedantic option directs GCC to print a...
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed7 years ago.Improve this question ``` struct line { char* string; struct line* next; }; ``` Can someone please exp...
Basically,stringandlinein your structure are not data items, butpointersto the place in memory where the actual data items are located. You can learn more in thistutorial on pointers in C.
I have installed the Clang and Codegen for Visual C++ 2015. I made a new console application which prints out "Hello, world!" and set the Platform Toolset in both Debug x86 and Release x86 to: Clang 3.7 with Microsoft CodeGen (v140_clang_3_7) I turned off precompiled headers and under C/C++ -> Command Line, I added ...
You need to use-Xclang -ast-dump(along with whatever other options you fancy)
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 In C, is it possible to force an unsigned char to print as a hex, not with %x, but in the little square box...
No, it is not possible. This is not related to C, but to the font your terminal uses. C outputs characters as bytes; your terminal is responsible for choosing how to display them as pixels. (You might as well ask how to make the text italic.)
I've been pulling my hairs out on this one, so this is how I call the function: ``` char* to_send; to_send = "GOO"; write_client_msg(new_fd, to_send); ``` And this is the function: ``` void write_client_msg(int new_fd, char * msg) { printf("\nwrite_client_msg\n"); printf("Message is: ", msg); int n = ...
``` printf("Message is: ", msg); ``` You forgot format specifier above. You need to use%sformat specifier for printing C style strings, e.g., see below: ``` printf("Message is: %s ", msg); ```
I am working on small project using Arduino. I have this char array which used to store some values. the problem is How to set this char array to null after assign some values in Arduino? ``` char packetBuffer[200] ```
Usememsetfromstring.h: ``` memset(packetBuffer, 0, sizeof packetBuffer); ```
This question already has answers here:Array increment operator in C(7 answers)Closed7 years ago. I have code where I want to increment a pointer. But the compiler don't like my expression. Here is the code: ``` int * p_int[5]; p_int++; ``` Compiler gives an error: lvalue required as increment operand p_int++; I ...
In your code,p_int++andp_int[++i]arenotthe same. The first one attempt to modify thep_intitself, while the second one does not. Array names are not modifiable lvaluesand cannot be used as the operand for++.
I'm reading documentation about gcc preprocessing, I read the following sentence (here): If the last line of any input file lacks an end-of-line marker, the end of the file is considered to implicitly supply one. The C standard says that this condition provokes undefined behavior, so GCC will emit a warning message. ...
It seems that it got removed from gcc. See this:https://gcc.gnu.org/bugzilla/show_bug.cgi?id=14331#c19 2007-05-31PR preprocessor/14331 * lex.c (_cpp_get_fresh_line): Don't warn if no newline at EOF.
I've changed the code. And I do the following: Open TerminalWrite gcc program.c -o program1./program1I get Error! I conclude that no file is being created, the pointerfptr==0and that is why I get that error. Also when I enter more strings or integers after ./program1 (like ./program 1 2) shows "Error!" again. Here's...
argv[0]is the name of the program, if you pass the file path, you should useargv[1] Try to launch like: ``` $ ./program mypath/file.name ``` argv[0]is program,argv[1]is mypatch/file.name
Here is my code: I don't understand why it gives me the wrong answer above 50. ``` #include<stdio.h> int main() { long long int i, sum=0; long long int a[50]; a[0] = 1; a[1] = 1; for(i=2;i<50;i++) { a[i] = a[i-1] + a[i-2]; if(a[i]%2==0 && a[i]<4000000) sum = sum + a[i]...
Yourfirstmistake was not breaking out of the loop when a term exceeded 4,000,000. You don’t need to consider terms beyond that for the stated problem; you don’t need to deal with integer overflow if you stop there; and you don’t need anywhere near 50 terms to get that far. Nor, for that matter, do you need to store a...
This question already has answers here:Array increment operator in C(7 answers)Closed7 years ago. I have code where I want to increment a pointer. But the compiler don't like my expression. Here is the code: ``` int * p_int[5]; p_int++; ``` Compiler gives an error: lvalue required as increment operand p_int++; I ...
In your code,p_int++andp_int[++i]arenotthe same. The first one attempt to modify thep_intitself, while the second one does not. Array names are not modifiable lvaluesand cannot be used as the operand for++.
I'm reading documentation about gcc preprocessing, I read the following sentence (here): If the last line of any input file lacks an end-of-line marker, the end of the file is considered to implicitly supply one. The C standard says that this condition provokes undefined behavior, so GCC will emit a warning message. ...
It seems that it got removed from gcc. See this:https://gcc.gnu.org/bugzilla/show_bug.cgi?id=14331#c19 2007-05-31PR preprocessor/14331 * lex.c (_cpp_get_fresh_line): Don't warn if no newline at EOF.
I've changed the code. And I do the following: Open TerminalWrite gcc program.c -o program1./program1I get Error! I conclude that no file is being created, the pointerfptr==0and that is why I get that error. Also when I enter more strings or integers after ./program1 (like ./program 1 2) shows "Error!" again. Here's...
argv[0]is the name of the program, if you pass the file path, you should useargv[1] Try to launch like: ``` $ ./program mypath/file.name ``` argv[0]is program,argv[1]is mypatch/file.name
Here is my code: I don't understand why it gives me the wrong answer above 50. ``` #include<stdio.h> int main() { long long int i, sum=0; long long int a[50]; a[0] = 1; a[1] = 1; for(i=2;i<50;i++) { a[i] = a[i-1] + a[i-2]; if(a[i]%2==0 && a[i]<4000000) sum = sum + a[i]...
Yourfirstmistake was not breaking out of the loop when a term exceeded 4,000,000. You don’t need to consider terms beyond that for the stated problem; you don’t need to deal with integer overflow if you stop there; and you don’t need anywhere near 50 terms to get that far. Nor, for that matter, do you need to store a...
Here is my code: I don't understand why it gives me the wrong answer above 50. ``` #include<stdio.h> int main() { long long int i, sum=0; long long int a[50]; a[0] = 1; a[1] = 1; for(i=2;i<50;i++) { a[i] = a[i-1] + a[i-2]; if(a[i]%2==0 && a[i]<4000000) sum = sum + a[i]...
Yourfirstmistake was not breaking out of the loop when a term exceeded 4,000,000. You don’t need to consider terms beyond that for the stated problem; you don’t need to deal with integer overflow if you stop there; and you don’t need anywhere near 50 terms to get that far. Nor, for that matter, do you need to store a...
I have a situation where I need to calldma_unmap_singleafterdma_sync_single_for_cpu. Below is my scenario. Allocate memory for a buffer usingkmalloc()Map the buffer to device usingdma_map_singlewithDMA_FROM_DEVICEdirection.After receiving packet, get buffer ownership usingdma_sync_single_for_cpu.After some time, if s...
The buffer "ownership" (CPU or device) matters only for deciding who is allowed to access the buffer's contents. dma_unmap_single()does not care about the contents; it can be called in either state. Please note that after the DMA unmapping, the memory again "belongs" to the CPU. If you are doing only a single DMA tr...
I don't want to usewindows.hbecause I will be compiling with mingwgcc.I want to get the cursor position of the console, without using any external libraries. So, how would I get the cursor position of the terminal?
I want to get the cursor position of the console, without using any external libraries. This isn't possible in standard C, it knows nothing about the mouse, cursor or even the screen. Youmustuse platform-specific libraries. For the record, I believe Mingw supports windows.h just fine.
I have a small C program that just computes Fibonacci. I have make file to build the file, and when I call make, I get the messagemake: *** No targets specified and no makefile found. Stop.. If I call make clean, I getmake: *** No rule to make target `clean'. Stop.but it seems to see a makeFile (I think). I'm pretty...
rename your makefile toMakefileor usemake -f <whatever_name_you_like>. Remember that in unix-like systems file names are often case-sensitive (not in all types of filesystems but in many)
I'm newbie to Arduino. I'm making a cross-platform lib, I need to tell whether it's compiling to an Arduino, I searched but got nothing. Is there any predefined platform macro in the Arduino compiler, which I can tell I'm compiling to Arduino? Not only can be used in the main *.ino file, but also other *.c files under...
The Arduino headers defineARDUINO. The toolchain defines its own AVR- and ARM-specific defines, if you need to distinguish between those. See their documentation for details.
I have a function foo(void* pBuf). I need to pass it a 64 bit address but I can't seem to get the right typecast when I'm passing by value. Example: foo(address). Where- uint64_t address=0x00000000DEADBEEF EDIT: Compiling using an ARM compiler. ``` uint64_t foo(void *pBuf){ uint64_t retAddr = (uint64_t) pBuf; ...
Call it this way: ``` uint64_t address = 0xDEADBEEF; foo((void*)address); ``` That is, youcastthe address to a void-pointer to be compatible with the function signature.
How do I read a value from a given memory address (e.g.0xfed8213) using the C programming language?
Each process has its ownvirtual address space, so, address0x12345678in one program will not be the same as address0x12345678in another. You can access what is at the address simply by doing: ``` #include <stdio.h> int main(int argc, char *argv[]){ char *ptr = (char *)0x12345678; //the addr you wish to access th...
``` void read_class_information(head* beginning, int scale_type) { puts("hello"); // printf("hello"); } ``` I have a simple function called by main and printf() and fprintf() to stdout does not seen to work within it. On the other hand, puts() works fine. I have no files open at the time of the printf() call...
Becauseprintf()does not flush the output stream automatically. On the other handputs()adds a new line'\n'at the end of the passed string. So it's working because the'\n'flushes destdout. Try ``` printf("hello\n"); ``` Or, explicitly flushstdout ``` fflush(stdout); ``` right after theprintf()statement.
A child process can: Exit normally (by exiting usingexit(0),exit(22),exit(23)) -- This is obviously specific to my applicationExit abnormally (code throws an exception, receives an unhandled signal, core dumps, etc...) I am doing a fork/exec from a parent process and looping onwaitpid, when I detect that child proce...
You can check forWIFSIGNALED(status). For testing this check outTest cases in C for WIFSIGNALED, WIFSTOPPED, WIFCONTINUED. Of course you can also do a positive check for normal termination withWIFEXITED(status).
Ingdb, when you runnextcommand. It apply to innermost frame instead of selected frame. How to ask to gdb to break in next line of the selected frame? For exemple: Set a breakpoint in a sub-function: ``` (gdb) b subfunc Breakpoint 1 at 0x400f09: file prog.c, line 94. (gdb) c Continuing. Breakpoint 1 at 0x400f09: fi...
I finally found what I want.advanceallow to continue until a particular line. Thusadvance +1do the job. It can be abbreviatedadv +1.
A child process can: Exit normally (by exiting usingexit(0),exit(22),exit(23)) -- This is obviously specific to my applicationExit abnormally (code throws an exception, receives an unhandled signal, core dumps, etc...) I am doing a fork/exec from a parent process and looping onwaitpid, when I detect that child proce...
You can check forWIFSIGNALED(status). For testing this check outTest cases in C for WIFSIGNALED, WIFSTOPPED, WIFCONTINUED. Of course you can also do a positive check for normal termination withWIFEXITED(status).
Ingdb, when you runnextcommand. It apply to innermost frame instead of selected frame. How to ask to gdb to break in next line of the selected frame? For exemple: Set a breakpoint in a sub-function: ``` (gdb) b subfunc Breakpoint 1 at 0x400f09: file prog.c, line 94. (gdb) c Continuing. Breakpoint 1 at 0x400f09: fi...
I finally found what I want.advanceallow to continue until a particular line. Thusadvance +1do the job. It can be abbreviatedadv +1.
I was trying to pass a value by calling C file from python and then return that value from C to python again. My question is how to do this? Can it possible to use returnPy_BuildValue(a+b)kind of thing? ``` #include <Python.h> static PyObject * hello_world(PyObject *self, PyObject *noargs) { int a=5,b=10; re...
Specify the format of the value: ``` return Py_BuildValue("i", a+b); // "i" for int ``` You can find more format unithere (Py_BuildValuedocumentation).
I'm compiling a cross-platform C/C++ CLI app for OSX usingcmakeandclang(700.1.81) on OSX 10.11 on a ~1 y.o. RMBP. I'm using CPack to package my application up as a drag-n-drop.dmginstaller. When I test the binary on older machines (~ 4 .y.o) I'm regularly getting aSIGILLillegal instruction fault (even on the same OSX...
For a generic architecture, try-march=x86-64. That should prevent, for example, Haswell-specific instructions from being generated.
I find myself wanting to print out the pointer to a memory address at each given iteration of a function call. I wish to see if the location in memory is advanced linearly at each iteration (because I suspect this may be the case based on the nature of the API). Viewing the resultant hexadecimal logs in the console ...
To do this portably (in a way that will work even if pointers andints are different sizes, you can use: ``` #include <inttypes.h> printf("%" PRIuPTR, (uintptr_t)some_pointer); ```
Could somebody explain me why is this snippet of code returning 0? ``` #include <stdio.h> int factorial(int input) { if (input > 0) { input--; return input * factorial(input); } return 1; } int main() { printf("%d", factorial(20)); return 0; } ```
For the very lastinbounditeration, in your code, wheninputis 1, executing ``` if (input > 0) { input--; // see here, 1 goes to 0..... return input * factorial(input); } ``` essentially gives you ``` return 0 * factorial (0); ``` which will eventually make thewholereturn value as 0.
I have achar* pointerand when I do(++pointer)= NULL, there's an error: ``` lvalue required as left operand of assignment ``` What does it mean and how do I fix it? The code is ``` void func(const char*p1, const char *p2){ char * pointer; pointer=malloc(strlen(p1)+strlen(p2)+2; (++pointer)=NULL; } ```
The symbolpointeris an lvalue and can be used in an assignment on the left hand side.(++pointer), however, is not an lvalue and cannot be used in the same assignment. If on an alien planet far far away it did compile, this code would increment pointer by one and then set it to zero (NULL) so to achieve the same effec...
This question already has answers here:What is the best way to print the result of a bool as 'false' or 'true' in C?(5 answers)Closed7 years ago. ``` #include<stdio.h> int main() { int var = 10 ; printf ( "\n%d %d",var==10, var = 100) ; } ``` Output: ``` 0 100 ``` Inside the printf statement,var==10evalua...
You're modifyingvarinside of the function call. Parameters to a function can be evaluated in any order. In this particular example,var = 100is being evaluated beforevar==10, but there's no guarantee the behavior will be the same if you use a different compiler. Because you're attempting to read and modify a variabl...
How do you get the size of a struct within a union in C? Given the following definition: ``` typedef union { struct req_ { uint8_t cmd1; uint8_t cmd2; } req; struct rsp_ { uint8_t cmd_result; uint8_t status_1; uint8_t status_2; uint8_t status_3; ...
Like this: ``` sizeof(struct req_); ``` For example: ``` int main() { printf("sizeof msg_t=%zd\n",sizeof(msg_t)); printf("sizeof struct req_=%zd\n",sizeof(struct req_)); } ``` Output: ``` sizeof msg_t=5 sizeof struct req_=2 ```
I'm trying to do a regex using posix to match some numbers of 5 digits: ``` 551.. 552.. 553.. ^(55[123]..)$ ``` But i need to exclude the next numbers: ``` 55341 55312 55227 ``` I'm trying to figure out how to create a regex that match some numbers and exclude another using posix (because my program is in C). ...
The only way with POSIX regex is the hard way (you must list all possible cases): ``` ^55(1[0-9][0-9]|2([013-9][0-9]|2[0-689])|3([0235-9][0-9]|1[013-9]|4[02-9]))$ ``` (or use^55[132][0-9][0-9]$and check forbidden numbers with a simple if)
I have been trying to prevent my parent thread from killing the child proccess if the parent proccess recives a ctrl-C signal. I have run out of ideas. The parent proccess allready catches SIGINT and so i want the same as now the children dies. ``` int main() { pid_t pid; pid = fork(); if(pid ...
SIGINTis sent to the entire process group. Try usingsetpgrp();in the child process to put it into a different process group.
How do I limit the gtkEntry only to numbers and also how to store the value entered by the user for further calculation. ``` entry1 = gtk_entry_new(); ```
You can attach a function to handle thekey-press-event, and in that function you can filter the keys. This way you can block any keypresses that you don't want to affect the content of the GtkEntry.You can usegtk_entry_get_text()to get the text, then of course for an integer you need to convert using e.g.strtol()or so...
Is there a meaningful difference betweenkmallocandkmalloc_array? I was under the impression that memory was memory, but as it is describedherethere appears to be some difference. kmalloc — allocate memorykmalloc_array — allocate memory for an array. Are they just two different ways to accomplish the same thing?
From the kernel-source (slab.h) ``` /** * kmalloc_array - allocate memory for an array. * @n: number of elements. * @size: element size. * @flags: the type of memory to allocate (see kmalloc). */ static inline void *kmalloc_array(size_t n, size_t size, gfp_t flags) { if (size != 0 && n > SIZE_MAX / size) ...
I have a following function: ``` void printerror(char *fmt, ...) { char string[256]; va_list str; va_start(str, fmt); vsnprintf(string, 256, fmt, str); va_end(str); } ``` I want to add an const char at the beginning of the string variable in the vsnprintf. How can i achieve this? Thanks.
To put a char at the beginning of a string: ``` string[0] = 'X'; ``` Then fill the remainder of the string. Its address is 1 greater: ``` vsnprintf(&string[1], 255, fmt, str); ``` or (which is the same) ``` vsnprintf(string + 1, 255, fmt, str); ``` Here I am using 255 instead of 256 (bugfix, noted by Andrew Henl...
I would like to assign an address value to a pointer, but I get thiswarning: ``` #define PRODUCT_NUMBER_ADDR 0x12345 "foo\foo.c", line 1444: cc1967: {D} warning: "long *" pointer set to literal value - volatile needed? ram_address = (long*) (PRODUCT_NUMBER_ADDR); ...
Change: ``` ram_address = (long*) (PRODUCT_NUMBER_ADDR); ``` to ``` ram_address = (volatile long*) (PRODUCT_NUMBER_ADDR); ``` Also make sureram_addressis declared as avolatile long *. Usingvolatilehere tells the compiler the memory object can have its value changed unexpectedly and so the compiler should not make ...
In C Programming, how do I store user input in a variable so that I can get a substring from it? When typing in "hello Point" in the console I get an error: The substring is NULL. This means my word variable is empty? What exactly did I do wrong and why? ``` #include <stdio.h> #include <string.h> int main() { ch...
%sforscanf()stops reading when it found a whitespace. Try usingscanf ("%99[^\n]", word);instead. (added99to avoid buffer overrun)
This question already has answers here:Pointers in C: when to use the ampersand and the asterisk?(10 answers)Closed7 years ago. What does the * mean in C? I see it used when declaring a char or FILE variable (char = *test) How does that change how a variable behaves?
This type of*is called "indirection operator", and*testmeans "get the data from where the pointertestpoints". charis reserved for use as a keyword, sochar = *testwon't compile unlesscharis defined as a macro.
I have a following function: ``` void printerror(char *fmt, ...) { char string[256]; va_list str; va_start(str, fmt); vsnprintf(string, 256, fmt, str); va_end(str); } ``` I want to add an const char at the beginning of the string variable in the vsnprintf. How can i achieve this? Thanks.
To put a char at the beginning of a string: ``` string[0] = 'X'; ``` Then fill the remainder of the string. Its address is 1 greater: ``` vsnprintf(&string[1], 255, fmt, str); ``` or (which is the same) ``` vsnprintf(string + 1, 255, fmt, str); ``` Here I am using 255 instead of 256 (bugfix, noted by Andrew Henl...
I would like to assign an address value to a pointer, but I get thiswarning: ``` #define PRODUCT_NUMBER_ADDR 0x12345 "foo\foo.c", line 1444: cc1967: {D} warning: "long *" pointer set to literal value - volatile needed? ram_address = (long*) (PRODUCT_NUMBER_ADDR); ...
Change: ``` ram_address = (long*) (PRODUCT_NUMBER_ADDR); ``` to ``` ram_address = (volatile long*) (PRODUCT_NUMBER_ADDR); ``` Also make sureram_addressis declared as avolatile long *. Usingvolatilehere tells the compiler the memory object can have its value changed unexpectedly and so the compiler should not make ...
In C Programming, how do I store user input in a variable so that I can get a substring from it? When typing in "hello Point" in the console I get an error: The substring is NULL. This means my word variable is empty? What exactly did I do wrong and why? ``` #include <stdio.h> #include <string.h> int main() { ch...
%sforscanf()stops reading when it found a whitespace. Try usingscanf ("%99[^\n]", word);instead. (added99to avoid buffer overrun)
This question already has answers here:Pointers in C: when to use the ampersand and the asterisk?(10 answers)Closed7 years ago. What does the * mean in C? I see it used when declaring a char or FILE variable (char = *test) How does that change how a variable behaves?
This type of*is called "indirection operator", and*testmeans "get the data from where the pointertestpoints". charis reserved for use as a keyword, sochar = *testwon't compile unlesscharis defined as a macro.
I have a file with the following content ``` "AAA";"BBB" ``` I try to extract the 2 columns this way : ``` char v1[50]; char v2[50]; int ret = fscanf(fp, "\"%s\";\"%s\"", v1, v2); ``` But it returns 1 and everything in 'v1' ! Is it normal ?
It's because the"%s"format readsspace delimitedstrings. It will read the input until it hits a white-space or the end of the input. You could possibly use the"%["format here, maybe something like ``` fscanf(fp, "\"%[^\"]\";\"%[^\"]\"", v1, v2); ``` See e.g.thisscanf(and family) referencefor more information.
Did the name of the function represent an pointer to this function like array? If I declare an function as followvoid fu (void);and an array of pointer to function like thatvoid(*ptr_fn[8])(void);so can I do thatptr_fn[0] = fu;
No, and the name of an array does not represent a pointer, either. The name represents the function, but there's an implicit conversion when you use the function name in an expression. See 4.3 Function-to-pointer conversion: An lvalue of function type T can be converted to a prvalue of type “pointer to T.” The re...
While doing some code excercise, I observed unusual ouput caused by the sqrt funtion, The code was, ``` #include<stdio.h> #include<math.h> int main() { double l,b,min_r,max_r; int i; scanf("%lf %lf",&b,&l); printf("%lf %lf\n",sqrt(l*l+b*b),sqrt(b*b-l*l)); return(0); } ``` Output: ``` 4 5 6.4031...
Look at the numbers:bis 4 andlis 5. Sob*b - l*lis -9. What's the square root of -9? It's an imaginary number, butsqrtdoesn't support imaginary results, so the result is nan (not a number). It's a domain error. The solution: Don't pass negative arguments tosqrt.
Hello I am writing aCprogram (no C++) to push data into myxampp database. To program I useXcode 7.1 I already got a normal query to work. So now I thought about using prepared statements. I already found here how to do it:How to setup prepared statements for mysql queries in C? But my compiler does not like the cod...
You have to provide a pointer: ``` bind[0].buffer = &ppm_value; bind[0].buffer_length = sizeof(ppm_value); ```
The spec is obviously vague to the point of being almost useless, but my understanding is thatin practicethe integer types are always as follows: int- 16 bit on ancient 16 bit systems, otherwise always 32 bits even on 64 bit architectureslong- always 32 bitslong long- always 64 bitssize_t- 32 bit on 32 bit systems, 6...
long - always 32 bits That's wrong assumption. There are platforms with 64-bitlongI think you can begin fromhere
I was writing a menu driven program in C. So when I call a function I'm trying to understand how return works. So I wrote a code something like ``` double function_name(parameters){ //some code here if(condition here) return (x); else return ; } int main( void ){ //some code here double l = func...
A QNaN (is a Quiet Not-a-Number) is an NaN with the MSB of the fraction part set. A QNaN, as opposed to an SNaN (Signalling NaN) is allowed to continue through floating point operations without raising an exception.In this case as I don't found much info on it, I'm guessing is similar. As I'm returningNOTHINGfrom t...
How do i make the printf("%d, veck[i]); print out all 100 numbers of the array instead of only 1-10? ``` int vek[100]; for(int a=0;a<10;a++){ for(int i=0;i<10;i++){ printf("%d ", vek[i]); //only shows numbers 1-10 } printf("\n"); } ```
You should change the index of vek. ``` printf("%d ", vek[10* a + i]); ```
I am doing some memory introspection and it requires me to know how proc/$pid/maps is created. I'm a bit confused by the code found inhttp://lxr.free-electrons.com/source/fs/proc/base.con line 2750 I notice that there is a definition in this struct for maps but I want to know for each pid_entry which kernel function c...
You did something weird with the link. Clicking through few definitions reveals the file is generated on demand here:https://github.com/torvalds/linux/blob/bcf876870b95592b52519ed4aafcf9d95999bc9c/fs/proc/task_mmu.c#L271 (at least for the common mmu case) the usual question: why are you asking?
``` int zero[5][4] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; int m1[5][4] = { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } }; //errors here m1 = zero; m1 = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; m1[0] = { 0, 0, 0, 0 }; ``...
In C, arrays are not assignable or can't be on the left side of assignment (=) operator. Usememcpy. ``` memcpy(m1, zero, sizeof(zero)); // Assuming size of 'm1' is no less than the size of 'zero' ``` You can usememsetto set an array with a constant value like0or-1 ``` memset(m1, 0, sizeof(m1)); ```
I would like to create a FUSE file system to mount tape archives. To do this correctly, I need to be able to supply replies to twopathconfkeys, specifically_PC_NAME_MAXand_PC_PATH_MAX. It seems that FUSE takes the answer for the_PC_NAME_MAXkey from thestatfsfunction you provide, but I haven't found a way to set_PC_PAT...
Further research indicates that this is not possible with FUSE at all. What a sad excuse for an API.
I want to buildFuTTY. The original author uses Visual Studio, I want to avoid that. I found out that apparently I have to: AddMinGW/binandMinGW/msys/1.0/binto the PATHrunperl mkfiles.plto restore some missing makefilesRemove-mno-cygwinfrom Makefile.cygAddXFLAGS = -DCOVERITYto Makefile.cygrunmake -f Makefile.cyg putt...
I'm using more handy tool chain distributionMSYS2
``` char string1[10]; char string2[10]; strcpy(string1, "hello"); strcat(string2, string1); if(strcmp(string1, string2)){ printf("Heellloww!!!); } else { printf("Bye"); } ``` When I perform check onif(strcmp(string1, string2))then what shouldstrcmp()return? Should it always return positive 1 in order to execu...
Always check the manual: int strcmp(const char *s1, const char *s2); Return value: The strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2. In your case,strcmpr...
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed7 years ago.Improve this question Can someone tell me ...
Make aforloop, let it iterate fromi = 0to9. In each iteration, allocate onestruct hashand pointv[i]to it. Afterwards, initialize*v[i]as needed. Don't forget to check ifmalloc()failed.
I get the following error form the Makefile: ``` VERSION=`git describe --abbrev=0 --tags` TAG=$(VERSION) all: prepare prepare: $(TAG) ``` Error: ``` `git describe --abbrev=0 --tags` /bin/sh: v1.1.2: command not found make: *** [prepare] Error 127 ``` What am I doing wrong?
your subshell commandgit describe --abbrev=0 --tagsis executed an returns the string "v1.1.2". Make then tries to execute it as a program. ``` prepare: echo $(TAG) ``` should work
I've been trying to understand how to print out some random numbers from my own array,dontconfuse this with that i want to generate random numbers into an array, which is not what im trying to accomplish. However, my code is like this ``` #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { srand(ti...
``` int number = myarray[rand() % 3]; ``` This generates a random number :0 1 2and then accesses that element from the array.
What's the representation of0x2bin binary? And how to convert it ? Im a little confused aboutb. ``` char a = 0x2b; ```
The0xpart means the following number is in hexadecimal notation. Since in hex,0x10 == 16and0xb = 11, we have: ``` 0x2B = 0x20 + 0xB = 32 + 11 = 43 ``` So0x2Bis43in decimal (the system we commonly use), and that's ``` 101011 ``` in binary. To clarify, no matter what notation you use (decimal or hexadecimal) to de...
I have a C++ algorithm which takes in some user input, so roughly something like ``` ./sum.out Enter a: 2 Enter b: 3 Sum is 5 ``` on a UNIX shell. What I want to do is automate the process by using another c++ file which sends severalsystem("./sum.out")commands but I don't know how to make it also send the parameter...
useIO redirection: ``` $ ./sum.out < in.txt ``` wherein.txtis a text file containing input: ``` $ cat in.txt 2 3 ``` to redirect stdout from a programa.outto stdin ofsum.out ``` `$ ./input.out | ./sum.out` ```
How can I open a file in an ext2 file system. For example, lets say I want to open the file:/a/b/c.txt I'm looking at the functions here:http://www.nongnu.org/ext2-doc/ext2.html
The same as any other filesystem: usefopen("/path/to/the/file", "r")or similar. The documentation you found is only relevant to people implementing the filesystem.
``` char string1[10]; char string2[10]; strcpy(string1, "hello"); strcat(string2, string1); if(strcmp(string1, string2)){ printf("Heellloww!!!); } else { printf("Bye"); } ``` When I perform check onif(strcmp(string1, string2))then what shouldstrcmp()return? Should it always return positive 1 in order to execu...
Always check the manual: int strcmp(const char *s1, const char *s2); Return value: The strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2. In your case,strcmpr...
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed7 years ago.Improve this question Can someone tell me ...
Make aforloop, let it iterate fromi = 0to9. In each iteration, allocate onestruct hashand pointv[i]to it. Afterwards, initialize*v[i]as needed. Don't forget to check ifmalloc()failed.
I get the following error form the Makefile: ``` VERSION=`git describe --abbrev=0 --tags` TAG=$(VERSION) all: prepare prepare: $(TAG) ``` Error: ``` `git describe --abbrev=0 --tags` /bin/sh: v1.1.2: command not found make: *** [prepare] Error 127 ``` What am I doing wrong?
your subshell commandgit describe --abbrev=0 --tagsis executed an returns the string "v1.1.2". Make then tries to execute it as a program. ``` prepare: echo $(TAG) ``` should work
I am doing a UNIX socket practice and trying to create a socket that's similar to a stream socketexample, but I realize that in the example code, the 3rd parameter passed tomemset()is thesizeofastruct: ``` memset(&addr, 0, sizeof(struct sockaddr_un)); ``` whereaddris declared in the beginning of the program as a def...
How can the program know the sizeof a struct that has not been instantialized? Same assizeof(int),sizeof(char), etc. You don't need variable to be initialized before applyingsizeof, all you need is the type of the variable. Because when I did the same thing in my program, GCC gives me an error. In your case, check ...
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed7 years ago.Improve this question I need help understa...
Replace\with double slash\\: ``` pFile = fopen("C:\\Users\\Wilmer\\Desktop\\abc.txt", "w"); ``` A single slash makes them interpret as escape sequences. Escaping the single slash will do.
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed7 years ago.Improve this question I includedmath.hlibr...
Includestdlib.h, notmath.h. Implicit declaration errors are generally due to missing/incorrect header files.
How can I save and print the biggest random number here? ``` #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <time.h> void main() { int i,max=0; srand(time(NULL)); printf("rand gives value between 1-1000\n"); for (i = 0; i < 30; i++) { printf("%d ", rand() % 1000 + 1); } pr...
Instead of directly printing the value, you can save it in a temporary and compare it withmax: ``` for (i = 0; i < 30; i++) { int r = rand() %1000 + 1; printf("%d ", r); if(r>max) max = r; } ```
i am trying to print double variable using printf function. using this function ``` int x_angle,y_angle; double xc, ret, val; x_angle=mouse_shoot.x-10; y_angle=19-mouse_shoot.y; xc=y_angle/x_angle; val = 180.0 / PI; ret = atan (xc) * val; printf("The arc tangent of %f is %f degrees", xc, ret); ``` x_angle a...
Maybexc = y_angle / x_anglegives problems since both angles are integers? Try casting them todoublemaybe: ``` ((double)y_angle) / ((double)x_angle) ```
I am doing a UNIX socket practice and trying to create a socket that's similar to a stream socketexample, but I realize that in the example code, the 3rd parameter passed tomemset()is thesizeofastruct: ``` memset(&addr, 0, sizeof(struct sockaddr_un)); ``` whereaddris declared in the beginning of the program as a def...
How can the program know the sizeof a struct that has not been instantialized? Same assizeof(int),sizeof(char), etc. You don't need variable to be initialized before applyingsizeof, all you need is the type of the variable. Because when I did the same thing in my program, GCC gives me an error. In your case, check ...
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed7 years ago.Improve this question I need help understa...
Replace\with double slash\\: ``` pFile = fopen("C:\\Users\\Wilmer\\Desktop\\abc.txt", "w"); ``` A single slash makes them interpret as escape sequences. Escaping the single slash will do.
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed7 years ago.Improve this question I includedmath.hlibr...
Includestdlib.h, notmath.h. Implicit declaration errors are generally due to missing/incorrect header files.
How can I save and print the biggest random number here? ``` #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <time.h> void main() { int i,max=0; srand(time(NULL)); printf("rand gives value between 1-1000\n"); for (i = 0; i < 30; i++) { printf("%d ", rand() % 1000 + 1); } pr...
Instead of directly printing the value, you can save it in a temporary and compare it withmax: ``` for (i = 0; i < 30; i++) { int r = rand() %1000 + 1; printf("%d ", r); if(r>max) max = r; } ```
i am trying to print double variable using printf function. using this function ``` int x_angle,y_angle; double xc, ret, val; x_angle=mouse_shoot.x-10; y_angle=19-mouse_shoot.y; xc=y_angle/x_angle; val = 180.0 / PI; ret = atan (xc) * val; printf("The arc tangent of %f is %f degrees", xc, ret); ``` x_angle a...
Maybexc = y_angle / x_anglegives problems since both angles are integers? Try casting them todoublemaybe: ``` ((double)y_angle) / ((double)x_angle) ```
I'd like to create an index and later, access some specific parts of a huge xml file, so I need to get theoffset(ftell... ) for some 'startElement' Events. Using the pull parser (stax) interface oflibxml2(http://www.xmlsoft.org/xmlreader.html) is it possible to get the offset in the stream of an event usinglibxml2?...
Use the functionxmlTextReaderByteConsumed: long xmlTextReaderByteConsumed (xmlTextReaderPtr reader)This function provides the current index of the parser used by the reader, relative to the start of the current entity. This function actually just wraps a call to xmlBytesConsumed() for the parser context associated wi...
I am coding in Code-Blocks Editor with GNU GCC Compiler.I tried to use functionstrtodwhich the below prototype: double strtod(const char *a, char **b); If I use the below code: ``` #include <stdio.h> #include <stdlib.h> #include <ctype.h> int main() { char *a; a="99.5HELLO"; char *b; printf("%.1lf\n...
The order of evaluation of subexpressions is unspecified, and so the last function argument may be evaluated first and you end up reading the uninitialized valueb, which is undefined behaviour. Order the evaluations: ``` const char *a = "99.5HELLO"; char *b; double d = strtod(a, &b); printf("%.1f\n%s", d, b); ```
In the following floor loop, how wouldsum += n --be evaluated? I'm very, very confused... ``` int sum; for(sum=0;n>0;sum+=n--); ```
Forsum += n--the following operations are performed addntosumdecrementn Withsum += --n nis decrementedthe new value ofnis added tosum n--is calledpostdecrement, and--nis calledpredecrement
I'm trying to implement a support fordoubleandfloatand corresponding basic arithmetic on a CPU without an FPU. I know that it is possible on allAVR ATmega controllers. An ATmega also has no FPU. So here comes the question: How does it work? If there any suggestions for literature or links with explanations and exampl...
Here are AVR related links with explanations and examples for implementing soft double: You will find one double floating point libhere.Another one can be found it in the last messagehere.Double is very slow, so if speed is in concern, you might opt for fixed point math. Just read my messages inthis thread:
I have a 2D array represented by a 1D array, and my task is to locate the first instance of the colour in the array, store the x and y coordinates in *x and *y and return 0. If not, then return 1. There are no errors, but the server test for my class is showing all tests failing for this function. Can anyone spot any...
You have set the passed argument values with reversed row and column. ``` *y=i; *x=j; ``` should be ``` *y=j; *x=i; ```
The following code: ``` #include <stdio.h> #include <sys/types.h> #include <unistd.h> int main() { pid_t mypid = getpid(); write(1, &mypid, sizeof(pid_t)); return 0; } ``` Prints gibberish instead of actual pid. Why?
write(..will not print formatted text, but rather binary output directly to a file descriptor. Just useprintforfprintf: ``` fprintf(stdout, "%d", (int) mypid); ```
I want to make a structure that contains SDL_Surface , SDL_Rect , the width and the height of the surface, here's the prototype : ``` typedef struct wall wall; struct wall { SDL_Surface *wall; SDL_Rect wallpos; int x; int y; }; ``` the problem is that I dont want to generate the wall...
You don't need a function for this. The width and height of a surface can be read directly from the structure memberswandh(e.g, givenSDL_Surface *s, you can reads->wors->h).
I have the following code: ``` #include <stdio.h> #include <stdlib.h> struct Book { char title[50]; char author[50]; char subject[100]; int numPages; int numBooks; int (*p) (int *, int *); }; int sum (int *a, int *b) { return *a + *b; } int main() { struct Book var; var.numPage...
var.pis not initialized (meaning it almost certainly doesn't refer to a valid function), creating undefined behavior. Usevar.p = sum;to initialize it before the function call.
I have found this line in this code through gdb to be seg faulting. However I can't seem to see why? It will run through 6/7 times before a seg fault occurs. Temp is a node in a linked list which contains a frequency (int), which I use to find the place in an ascending linked list to insert a new node. ``` while (ind...
You dotemp = temp->nextbuttemp->nextmight benullptr. You must check its not null before trying to access it's memebers.
Good afternoon,I am developping a program in C, where (for debugging purposes) I am regularly adding lines like: ``` printf("[%s]\n", __FUNCTION__); ``` I would like to preceed these comment lines by an amount of spaces (or dots), being the stack depth of my function, so that I can easily determine which function is...
In case somebody finds a quicker/easier way for adding trailing blanks, don't hesitate to react. You meanleadingblanks. You can use a field width argument with*: ``` printf("%*c[%s]\n", frames+1, ' ', __FUNCTION__); ```
InWith arrays, why is it the case that a[5] == 5[a]?it is explained that the[]operator ina[5]is defined as*(a + 5)and because+is commutative,5[a]means*(5 + a)and so the two expressions refer to the same memory location. Fine. However, C also defines in 6.4.2.1 that an identifier cannot start with a digit. In5[a]the a...
5is not an identifier, it is an integer literal. The C standard literally state that5[a]is just syntactic sugar thatmustbe equivalent with*(5 + a). There is no requirement in C that the first operand of the + operator is an identifier, so the code works just fine. 6.5.6, emphasis mine: For addition, either both ope...
How can I remove, in C, a part of a string? I am interested especially in a built-in function, or an efficient code to do it. I have this line of code: ``` char namefile[256] = "/Users/student/Desktop/Silviu/g7.08e11.01024" ``` and I want to keep only "g7.08e11.01024" so I can use it somewhere else.
Usestrrchr: ``` const char* shortName = strrchr(namefile, '/') + 1; ``` strrchrreturns the address of the last occurence of/in the string.
Good afternoon,I am developping a program in C, where (for debugging purposes) I am regularly adding lines like: ``` printf("[%s]\n", __FUNCTION__); ``` I would like to preceed these comment lines by an amount of spaces (or dots), being the stack depth of my function, so that I can easily determine which function is...
In case somebody finds a quicker/easier way for adding trailing blanks, don't hesitate to react. You meanleadingblanks. You can use a field width argument with*: ``` printf("%*c[%s]\n", frames+1, ' ', __FUNCTION__); ```
InWith arrays, why is it the case that a[5] == 5[a]?it is explained that the[]operator ina[5]is defined as*(a + 5)and because+is commutative,5[a]means*(5 + a)and so the two expressions refer to the same memory location. Fine. However, C also defines in 6.4.2.1 that an identifier cannot start with a digit. In5[a]the a...
5is not an identifier, it is an integer literal. The C standard literally state that5[a]is just syntactic sugar thatmustbe equivalent with*(5 + a). There is no requirement in C that the first operand of the + operator is an identifier, so the code works just fine. 6.5.6, emphasis mine: For addition, either both ope...
How can I remove, in C, a part of a string? I am interested especially in a built-in function, or an efficient code to do it. I have this line of code: ``` char namefile[256] = "/Users/student/Desktop/Silviu/g7.08e11.01024" ``` and I want to keep only "g7.08e11.01024" so I can use it somewhere else.
Usestrrchr: ``` const char* shortName = strrchr(namefile, '/') + 1; ``` strrchrreturns the address of the last occurence of/in the string.