#include <stdio.h>
#include <stdlib.h>
void main()
{
char str[] ="asdfasdf";
char *s;
strcpy(s,str);
printf("%s",s);
}
What's wrong with this code? Am I messing up with char* and char[]?
#include <stdio.h>
#include <stdlib.h>
void main()
{
char str[] ="asdfasdf";
char *s;
strcpy(s,str);
printf("%s",s);
}
What's wrong with this code? Am I messing up with char* and char[]?
You never set s
to a value, so you're invoking undefined behavior.
Perhaps s = strdup(str);
is better in your case?
strcpy
doesn't allocate space for your copy - it assumes you've already done that. strdup
allocates memory for you. As Jonathan Leffler points out in the comment - if you don't want to use dynamic memory allocation, you just need a big enough "chunk" to copy the string into.
In your case, char *
and char[]
types can be used interchangeably, it's just that your pointer is not set to anything valid (it could be set to anything), but your code assumes it is valid.
char *s;
in only a character pointer and currently does not point anywhere meaningful.
s
to str
, and then both will point to the same array in memory.char s[16]
, where you can copy the array into. In this case, s
and str
will be two independent arrays, and will live in different memory address in the stack.malloc
or strdup
. Allocating memory is like taking out a loan. We need to give it back at the end of our program. Make sure to free
the pointer once done using it. In this case, the two arrays live in different memory addresses, the first in the stack and second in the heap.