문제

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.

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top