printf crashes the program
I am using sprintf
to convert int
to string and then if I use printf
the program crashes otherwise it works fine. Can anyone tell me the reason?
typedef char* string;
buffer[8] = (string*)malloc(sizeof(string));
buffer[8] = sprintf(buffer[8],"%d",inf[i].mPermissions);
It's working fine until here bu开发者_C百科t when I print it like this:
printf("%s",buffer[8]);
...my program crashes.
typedef char* string;
The C language has no string type. A char pointer is not the same thing as an allocated string.
buffer[8]=(string*)malloc(sizeof(string));
Why are you setting item number 9 in buffer to a string? (C is zero-indexed, so 0-8 = 9 items). Is that an array of pointers? Perhaps you meant to allocate a buffer of 8 characters?
It doesn't make any sense to typecast the result from malloc in the C language. In C++ you would have to do a cast.
You are allocating the size of a pointer, not the size of a buffer.
buffer[8]=sprintf(buffer[8],"%d",inf[i].mPermissions);
The first argument to sprintf must be an allocated buffer, not a character (one item of a buffer).
printf("%s",buffer[8]);
You are trying to print a string, but passing an item of a buffer (a character).
To sum this up, I would strongly recommend reading the first chapters of a C language book regarding arrays and pointers before attempting any form of string handling or dynamic memory allocation. If you don't know how something works, don't take a chance at the syntax.
My bet is you're not allocating the buffer sprintf is writing into.
You need something like:
int myNumber = 42;
char myBuffer[12];
sprintf(myBuffer, "%d", myNumber);
精彩评论