I am not so clear on character pointer and how they work.
The program builds, but crashes when I run it.
char *ab = NULL;
//ab = \"abc123\"; // works f
You have allocated no memory to use with ab
.
The first assignment works because you are assigning to ab
a string constant: "abc123"
. Memory for constant strings are provided by the compiler on your behalf: you don't need to allocate this memory.
Before you can use ab
with e.g. sprintf
, you'll need to allocate some memory using malloc
, and assign that space to ab
:
ab = malloc(sizeof(char) * (NUM_CHARS + 1));
Then your sprintf
will work so long as you've made enough space using malloc
. Note: the + 1
is for the null terminator.
Alternately you can make some memory for ab
by declaring it as an array:
char ab[NUM_CHARS + 1];
Without allocating memory somehow for ab
, the sprintf
call will try to write to NULL
, which is undefined behavior; this is the cause of your crash.