Input with char pointer vs. char array

前端 未结 6 1944
不思量自难忘°
不思量自难忘° 2021-01-03 05:46

consider the code

#include
int main(void)
{
   char* a;
   scanf(\"%s\",a);//&a and &a[0] give same results-crashes 
   printf(\"%s\",         


        
6条回答
  •  日久生厌
    2021-01-03 05:58

    In you first code, a is an uninitialized pointer to char. You are trying to write to non-allocated memory or reserved memory.

    You need to allocate memory for the input string with malloc().


    int main(void) {
      char* s;
      /* ... */
      s = malloc(100 * sizeof(*s));
      if (s == NULL) {
        return 1;
      /* ... */
    }
    

提交回复
热议问题