Reputation: 97
I'm a bit confused about this here
char *string;
scanf("%s",string);
int i=strlen(string);
int k = 0;
while(k<i){
printf("%c", string[k]);
k++;
}
and when I compile this it prints out nothing.
Upvotes: 1
Views: 17387
Reputation: 3162
scanf("%s",string);
string
is a pointer. you need to allocate memory to it so that it can hold the input read using scanf
.
char *string;
this statement just creates a pointer to a character array but doesn't allocate memory to hold the array.
You need to allocate memory explicitly using dynamic-allocation. you can use malloc
like functions. read this
or you can declare a array instead of pointer as,
char string[SIZE];
SIZE is the maximum possible size of string.
You can use even getline instead of scanf
since getline
allocates memory if NULL pointer is passed.
Upvotes: 3