#include <stdio.h>
#include <string.h>
int main(void) {
char *w;
strcpy(w, "Hello Word");
printf("%s\n", w);
return 0;
}
What is wrong with the way the char pointer is used in the above code?
#include <stdio.h>
#include <string.h>
int main(void) {
char *w;
strcpy(w, "Hello Word");
printf("%s\n", w);
return 0;
}
What is wrong with the way the char pointer is used in the above code?
You allocate no space for the string. w is just a pointer to some memory (garbage value since it's not initialized).
char w[32];
or
char *w = malloc(32);
You need to allocated the space for the characters.
It's an uninitialized pointer. The strcpy will write to some unknown location in memory.
Ok, you did not ask to the system for memory, to use it with the string. This code will work
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char w[11];
strcpy(w, "Hello Word");
printf("%s\n", w);
return 0;
}
That code declare w as an array of char, reserving the memory space for it. Other alternative is to use malloc or calloc for the char pointer. Read about that.