Input with char pointer vs. char array

前端 未结 6 1941
不思量自难忘°
不思量自难忘° 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 06:06

    a doesn't point to anything. Or actually, it's uninitialized so it points somewhere, just not somewhere valid.

    You could provide storage on the stack like you've already tried:

    #include 
    int main()
    {
      char x[100];
      char *a = x; // a points to the storage provided by x on the stack
      scanf("%s",a); // should work fine
      printf("%s",a);
      return 0;
    }
    

    Note that printf("%s",x); yields exactly the same result, a is pointing to x, so that's where your string will 'live'.

    Or you could have the memory management handle it by using malloc

    #include 
    #include 
    int main()
    {
      char *a = malloc (100*sizeof(char)) // a points to the storage provided by malloc
      if (a != null)
        {
          perror ("malloc"); // unable to allocate memory.
          return 1;
        }
      scanf("%s",a); // should work fine
      printf("%s",a);
      free (a); // just remember to free the memory when you're done with it.
      return 0;
    }
    

    HTH.

    EDIT
    Also, before the comments start... This is very unsafe code, but I guess you're just trying to wrap your head around pointers, so I just tried to give you a nudge in the right direction. (If not you need to look into reading limited amount of data, make sure it fits in your buffers, if it's from some other source than a file, you need to make sure you got all of it, and so on, and so on).

提交回复
热议问题