1

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.

Rahul R Dhobi
  • 5,668
  • 1
  • 29
  • 38
yukapuka
  • 87
  • 1
  • 2
  • 8

1 Answers1

3
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.

Community
  • 1
  • 1
LearningC
  • 3,182
  • 1
  • 12
  • 19
  • so i need to use malloc instead of the string in the scanf? i.e scanf("%s", string=malloc((strlen)*sizeof(char)))? – yukapuka Apr 22 '14 at 05:37
  • @yukapuka you will not know the size of the string before reading so you need to read the number then allocate or instead declare a char array. – LearningC Apr 22 '14 at 05:39
  • @yukapuka you can use getline if you can use it. since it will do the memory allocation. – LearningC Apr 22 '14 at 05:42
  • how do i read the number? is my only option to read into an string[SIZE] and then find its length strlen(string) – yukapuka Apr 22 '14 at 05:43
  • @yukapuka you will need to ask for length of string from user first then read the string. or you can read the string character by character and allocate memory for one character using `realloc` and then store it and repeat this in a loop. So if can use getline use it directly. – LearningC Apr 22 '14 at 05:49
  • @yukapuka i added one link for dynamic allocation read it to get idea about how to use dynamic allocation for strings – LearningC Apr 22 '14 at 05:53
  • that sounds very complicated to use realloc, thanks anyway i understand it now – yukapuka Apr 22 '14 at 06:39