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
```
#include<stdio.h>
int main()
{
int s,i = 0;
while(i < 10)
{
scanf("%d",&s);
i++;
printf("%d",s);
}
while(i < 20)
{
printf("%d",s);
scanf("%c",&s);
}
}
```
|
%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 code?
PS: I am using structs shown inthis program.
|
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 translating the bytes into human-readable numbers. In your code, you can use your platform'sntohs()function to do the same thing.
|
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 visual studio.
Thanks!
|
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_t *, uint8_t)) ptr )(addr, data, erase);
```
|
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 format i,j k,l");
//exit here
else
printf("%d %d %d %d", i, j, k, l);
}
```
This uses the fact that if user enters input in some other format (other then 1,2 3,4) thenscanf()will not be able to read all the4inputs, and thus will not return4.
|
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 = Foo
JAVADOC_AUTOBRIEF = YES
```
When I run thedoxyfilecommand, I get a documentation that looks like this.
Why is there no documentation generated for theworld()macro? How can I ensure that documentation is generated for theworld()macro too without bringing it out of the functionmain()?
|
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 warning message if any of these features is used.) To test for the availability of these features in conditional compilation, check for a predefined macroGNUC, which is always defined under GCC.
|
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 explain what is happening?
Ex:
Creating a structure "line"This structure has a char variable "string" -> Whats with the "*" ??In this structure we create a new one called "line*" -> Whats with the "*" ??New struct has a field "next"
|
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 a new command in both Debug x86 and Release x86:
-ast-dump
I then build the program in Debug mode. The program builds successfully and gives the expected results; however, there is this warning from clang.exe:
1> Source.cpp1>clang.exe : warning : argument unused during compilation: '-ast-dump'1> tester5.vcxproj -> c:\users\erika\documents\visual studio 2015\Projects\tester5\Debug\tester5.exe
Why was the argument -ast-dump left unused during the compilation? How do I get Clang, from here, to dump the AST?
|
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 that displays the four hex numbers, but only takes up one character, for example轩?
|
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 = write(new_fd, msg, strlen(msg));
if (n < 0)
{
perror("Erreur lors de la transmission de message");
exit(EXIT_FAILURE);
}
}
```
And the result to that is the following:
```
write_client_msg
Message is:
```
It's just empty... I don't understand and I have no idea how to fix it.
|
```
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 thought thatp_int++;would be equivalent top_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.
I try to produce the warning by doing :
```
> echo -n "int main(void) {return 0;}" > test.c
> gcc -Wall -Wextra -Werror test.c
```
But no prob, it compiles. I understand end-of-line marker as new-line char, but it seems to be anything else.
How could I produce the warning ?
|
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 the code:
```
#include <stdio.h>
int main(int argc, char *argv[]){
int n;
FILE *fptr;
fptr=fopen(argv[0],"w");
if(fptr==NULL){
printf("Error!");
exit(1);
}
printf("Enter n: ");
scanf("%d",&n);
fprintf(fptr,"%d",n);
fclose(fptr);
return 0;
}
```
|
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];
}
printf("%lld", sum);
return 0;
}
```
|
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 all of the terms, unless you
want to look at them to check correctness (and simply printing them
would work just as well for that).
|
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 thought thatp_int++;would be equivalent top_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.
I try to produce the warning by doing :
```
> echo -n "int main(void) {return 0;}" > test.c
> gcc -Wall -Wextra -Werror test.c
```
But no prob, it compiles. I understand end-of-line marker as new-line char, but it seems to be anything else.
How could I produce the warning ?
|
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 the code:
```
#include <stdio.h>
int main(int argc, char *argv[]){
int n;
FILE *fptr;
fptr=fopen(argv[0],"w");
if(fptr==NULL){
printf("Error!");
exit(1);
}
printf("Enter n: ");
scanf("%d",&n);
fprintf(fptr,"%d",n);
fclose(fptr);
return 0;
}
```
|
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];
}
printf("%lld", sum);
return 0;
}
```
|
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 all of the terms, unless you
want to look at them to check correctness (and simply printing them
would work just as well for that).
|
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];
}
printf("%lld", sum);
return 0;
}
```
|
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 all of the terms, unless you
want to look at them to check correctness (and simply printing them
would work just as well for that).
|
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 some other function in kernel using same buffer, unmap buffer from device usingdma_unmap_singlewithDMA_FROM_DEVICEdirection.
Are all the above steps acceptable?
|
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 transfer, you do not need to calldma_sync_single_for_cpu(); you can just read the buffer after thedma_unmap_single()call.
|
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 lost and need help.
Here's the text of the make file:
```
CC=gcc
all: fibonacci
fibonacci: fibonacci.c
$(CC) -pthread -o fib.exe
clean:
rm fib.e xe
```
|
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 scratch folder. Thanks.
|
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;
retAddr += 0x100000;
return retAddr;
}
```
I'm on a 32-bit ARM andsizeof(void *)is4
Clarification: Why I needed a 64-bit address on a 32-bit ARM?
Because my memory map uses 36-bit addressing.
|
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 the contents of
printf("%c\n", *ptr); //this will give you the first byte, you can add any more bytes you need to the ptr itself, like so: *(ptr + nbyte).
return 0;
}
```
You'll likely get a segmentation fault though, unless you really know what you're doing. My guess is that you think this is the way to solve some other problem, whereas this isn't the actual solution. This does answer your question in the OP, though.
Here isAnother Virtual Memory learning resource.
|
```
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 or any errors. Any suggestions to what the problem might be? Thanks.
|
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 process has exited I would like to determine the reason it exited.
Currently I checkWEXITSTATUS(status)(wherestatusis returned bywaitpid) to determine exit code.
Is there a way to reliably detect if child exited abnormally?
|
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: file prog.c, line 94.
94 void subfunc() {
```
Change selected frame:
```
(gdb) up
#1 0x0000000000400f7e in main (argc=1, argv=0x7fffffffe468) at prog.c:70
70 subfunc();
```
I want to stop at line 71 ofprog.c:
```
(gdb) n
95 i = 0;
```
... but it stop line 95 ofprog.c.
|
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 process has exited I would like to determine the reason it exited.
Currently I checkWEXITSTATUS(status)(wherestatusis returned bywaitpid) to determine exit code.
Is there a way to reliably detect if child exited abnormally?
|
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: file prog.c, line 94.
94 void subfunc() {
```
Change selected frame:
```
(gdb) up
#1 0x0000000000400f7e in main (argc=1, argv=0x7fffffffe468) at prog.c:70
70 subfunc();
```
I want to stop at line 71 ofprog.c:
```
(gdb) n
95 i = 0;
```
... but it stop line 95 ofprog.c.
|
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;
return Py_BuildValue(a+b); //This is Errorus.
}
static PyMethodDef
module_functions[] = {
{ "hello_world", hello_world, METH_NOARGS, "hello world method" },
{ NULL }
};
PyMODINIT_FUNC
inittesty2(void)
{
Py_InitModule("testy2", module_functions);
}
```
|
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 version). What are the magic compiler invocations I should be using to build for a "generic" CPU?llcfor instance supports a-mpcu=genericflag, but clang doesn't recognise that flag, and the clangmanpage suggests-march=cpu, but if I try-march=genericI get anerror: unknown target CPU 'generic'error.
I'm already specifying older OSX versions through-mmacosx-version-min, that doesn't seem to be the issue.
Do I have to specify a generic CPU through a target triple? What are the options there?
|
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 doesn't conveniently help me and so I'd prefer the decimal value. What is the simplest way of print out these address' decimal value?
|
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 effect, and be portable to earth compilers, usepointer = NULL;
|
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==10evaluates to true but then I'm getting the output as0. Why does this happen?
|
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 variable in the same expression without a sequence point to separate them, you're invokingundefined behavior.
|
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;
uint8_t status_4;
} rsp;
} msg_t;
```
sizeof(msg_t)would provide the maximum size of the union, which in this case, would be 5 asrsp_is greater thanreq_.
How do you getsizeof(req_)?
|
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).
I'm currently compiling the regex withREG_EXTENDEDandREG_ICASEflags:
```
status = regcomp(&brb_regex->reg, regex_str, REG_EXTENDED|REG_ICASE);
```
...and executing it as follows:
```
status = regexec(&brb_regex->reg, cmp_str, 10, brb_regex->match, 0);
```
|
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 > 0) {
/*Parent proccess*/
[...other code...]
} else {
/*Child proccess*/
signal(SIGINT, SIG_IGN); //does not work
sigaction(SIGINT, &action, 0); //does not work either
[...other code...]
}
}
```
Ideas?
|
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 some other regular string-to-integer function:const char *text = gtk_entry_get_text(entry1);
const long value = strtol(text, NULL, 10);
printf("the value is %ld\n", value);The above isn't 100% rock-solid, you can use the middle argument tostrtol()to make it better but I omitted it for brevity and topicality.
|
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)
return NULL;
return __kmalloc(n * size, flags);
}
```
I wonder who needed that ;))
|
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 Henle) as the maximum length of the string to fill, because one byte is already filled.
|
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);
^
```
How can I properly assign my address to my pointer?
|
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 any cacheing assumption.
|
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()
{
char word[100];
printf ("Enter a word: ");
scanf ("%s", word);
const char needle[] = "Point";
char *ret;
ret = strstr(word, needle);
printf("The substring is: %s\n", ret);
return(0);
}
```
|
%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 Henle) as the maximum length of the string to fill, because one byte is already filled.
|
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);
^
```
How can I properly assign my address to my pointer?
|
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 any cacheing assumption.
|
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()
{
char word[100];
printf ("Enter a word: ");
scanf ("%s", word);
const char needle[] = "Point";
char *ret;
ret = strstr(word, needle);
printf("The substring is: %s\n", ret);
return(0);
}
```
|
%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 result is a pointer to the function.
|
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.403124 -nan
```
Why does this happenes.
|
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 code.
```
bind[0].buffer_type= MYSQL_TYPE_LONG;
bind[0].buffer=ppm_value;
bind[0].buffer_length=strlen(ppm_value);
bind[0].is_null=0;
bind[0].length=0;
```
It wants to replace the.with->but if I do so I get the error:
```
EXC_BAD_ACCESS(code=1, address=0x60)
```
ppm_valueis aintso I am also not sure if there is a problem withstrlen.
Do I even need thebuffer_length?
Could someone please help me.
|
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, 64 bits on 64 bit systems (unsigned)
Is that table really correct? Are there any significant implementations that violate it?
Updated Table based on responses below
int- 16 bit on ancient 16 bit systems, otherwise always 32 bits even on 64 bit architectureslong- may be 32 or 64 bit on 64 bit systems. (Windows 32, *nix usually 64)long long- always 64 bitssize_t- 32 bit on 32 bit systems, 64 bits on 64 bit systems (unsigned)
|
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 = function_name(argument);
printf("returns: %.4lf\n", l);
return 0;
}
```
When code goes into else then it prints
Output: returns: 1.#QNB
What exactly does it mean?
|
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 the function and storing in afloating type numberwhich is yielding me a1.#QNB
|
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 creates the maps file. A link to the kernel module or block of code is sufficient.
|
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 };
```
Is there no syntax for this? Do I have to use a loop with indexing to achieve this?
|
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_PATH_MAX. Is there a way to configure the answer to_PC_PATH_MAX? Is there in general a way to supply an answer to anypathconfcall?
|
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 putty.exefrom thewindowsdirectory
This works for buildingthe original PuTTY, but is not enough for FuTTY.
It complains thatKEY_WOW64_32KEYis undeclared. When I googled that, I found that apparentlythis means you need MinGW-W64.
At this point I'm making wild guesses, but I think the selector shown below means that the MinGW-W64 project is about making all kinds of toolchains run on Windows 64 bit and if I want something that works with PuTTY's MinGW makefile, I need this:
Right? So after downloading that, I am presented with questions I cannot answer:
|
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 execute statements inif?
|
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,strcmpreturns zero ifstring1andstring2are the same (or match). So in case theyarethe same, you would printBye, and if they are different then you would printHeellloww.
|
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 how should I do to allocate everyv[i].wordand next withNULL?
```
Struct hash{
Char*word;
Hash*next;
}*v[10];
```
|
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(time(NULL));
int myarray[] = { 2, 5, 10 };
//Its here where i dont know how to use rand() in to make the program generate one random number from my array, either 2, 5 or 10. I've tried, but failed.
return 0;
}
```
Ive not found any similar question to this either, so would greatly appreciate some help.
|
```
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 declare/overwrite variables in C, the result is the same.
```
char a = 0x2B;
char b = 43;
if (a == b)
printf("But of course they're the same!\n");
else
printf("This should not happen\n");
```
|
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 parameters, i.e.aandbin my case. In other words, I want the second file to supply it with the parameters and not the user.
|
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 execute statements inif?
|
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,strcmpreturns zero ifstring1andstring2are the same (or match). So in case theyarethe same, you would printBye, and if they are different then you would printHeellloww.
|
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 how should I do to allocate everyv[i].wordand next withNULL?
```
Struct hash{
Char*word;
Hash*next;
}*v[10];
```
|
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 definition ofstruct sockaddr_un. How can the program know thesizeofa struct that has not been initialized? Because when I did the same thing in my program, GCC gives me an error. Thanks.
|
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 if you have included proper headers for Unix socket:
```
#include <sys/socket.h>
#include <sys/un.h>
```
|
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 understanding why this code won't open the file i'm asking it to open.
```
#include<stdio.h>
#include<stdlib.h>
int main(){
FILE *pFile;
pFile = fopen("C:\Users\Wilmer\Desktop\abc.txt", "w");
if (pFile != NULL){
printf("Hello");
fclose(pFile);
}else{
printf("File does not exist.");
}
getchar();
return 0;
}
```
|
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.hlibrary and usedabsfunction and this error shows:
```
error: implicit declaration of function ‘abs’ [-Werror=implicit-function-declaration]
razlika=(abs(x3) / ((x1+x2)/2))*100;
^
cc1: some warnings being treated as errors
```
|
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);
}
printf("\nMax is %d", max);
getch();
}
```
Thank you in advance.
|
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 and y_angle printed just fine , but when i am trying to print xc and ret i am getting this print
"The arc tangent of f is f degrees"
any idea why?
----UPDATE-----
seems like Dos is not printing double to screen so i casted the result to int
and it printed fine!
|
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 definition ofstruct sockaddr_un. How can the program know thesizeofa struct that has not been initialized? Because when I did the same thing in my program, GCC gives me an error. Thanks.
|
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 if you have included proper headers for Unix socket:
```
#include <sys/socket.h>
#include <sys/un.h>
```
|
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 understanding why this code won't open the file i'm asking it to open.
```
#include<stdio.h>
#include<stdlib.h>
int main(){
FILE *pFile;
pFile = fopen("C:\Users\Wilmer\Desktop\abc.txt", "w");
if (pFile != NULL){
printf("Hello");
fclose(pFile);
}else{
printf("File does not exist.");
}
getchar();
return 0;
}
```
|
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.hlibrary and usedabsfunction and this error shows:
```
error: implicit declaration of function ‘abs’ [-Werror=implicit-function-declaration]
razlika=(abs(x3) / ((x1+x2)/2))*100;
^
cc1: some warnings being treated as errors
```
|
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);
}
printf("\nMax is %d", max);
getch();
}
```
Thank you in advance.
|
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 and y_angle printed just fine , but when i am trying to print xc and ret i am getting this print
"The arc tangent of f is f degrees"
any idea why?
----UPDATE-----
seems like Dos is not printing double to screen so i casted the result to int
and it printed fine!
|
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 with the reader. See xmlBytesConsumed() for more information.reader:an XML readerReturns:the index in bytes from the beginning of the entity or -1 in case the index could not be computed.
|
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%s", strtod(a, &b), b);
return 0;
}
```
I expect the Console Terminal to represent something like this after running the code:
```
99.5
HELLO
```
But what I actually got was something strange:
```
99.5
@
```
What's happening? Where did I make a mistake?
|
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 examples?
At the best case I will provide a support for code like this:
```
double twice ( double x )
{
return x*x;
}
```
Many thanks in advance,
Alex
|
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 error or mistake?
Thanks
```
int locate_color( const uint8_t array[],
unsigned int cols,
unsigned int rows,
uint8_t color,
unsigned int *x,
unsigned int *y )
{
int i,j;
for(i=0;i<cols;i++)
{
for(j=0;j<rows;j++)
{
if(array[i+(j*cols)]==color)
{
*y=i;
*x=j;
return 0;
}
}
}
return 1;
}
```
|
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.x & wall.y manually.
Is there any SDL_function that determine the width/height of an SDL_surface right from the dimensions of the image loaded ?
|
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.numPages = 7;
var.numBooks = 9;
int allPages = (*var.p) (&var.numPages, &var.numBooks);
printf("%d\n", allPages);
return (EXIT_SUCCESS);
}
```
I trying to use function in struct but my program have no result, no warning although I used -Wall, -Wextra. I'm a newbie. Hope everybody help.
|
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 == 0 && temp != NULL)
{
temp = temp -> next;
if (temp -> frequency > parent_node -> frequency) /*<--- SEG FAULT HERE */
{
parent_node -> next = temp -> next; /* parent points at higher freq node */
temp -> next = parent_node; /* parent node is temp next */
ind = 1;
}
if (temp -> next == NULL)
{
temp -> next = parent_node;
ind = 1;
}
}
```
|
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 calling which other function.
I am working with Visual Studio 2013 Express for Windows, on a Windows-7 system.As far as I know, I'm not working with a gcc compiler.
Is this even possible?Thanks
|
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 array identifier is5which is not a valid identifier. Why does5[a]not generate an error about an invalid identifier?
|
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 operands shall have arithmetic type, orone
operand shall be a pointer to a complete object type and the other
shall have integer type.
|
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 calling which other function.
I am working with Visual Studio 2013 Express for Windows, on a Windows-7 system.As far as I know, I'm not working with a gcc compiler.
Is this even possible?Thanks
|
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 array identifier is5which is not a valid identifier. Why does5[a]not generate an error about an invalid identifier?
|
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 operands shall have arithmetic type, orone
operand shall be a pointer to a complete object type and the other
shall have integer type.
|
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.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.