0

I have wrote two programs like this, I am inputting 'hello'

prog1:

#include <stdio.h>
#include <string.h>

int main(void)
{

char arr[10];
scanf("%s", arr);
printf("%s\n", arr);
return 0;
}

output : hello

prog2

#include <stdio.h>
#include <string.h>
int main(void)
{

char *str;
scanf("%s", str);
printf("%s\n", str);
return 0;
}

output:segmentation fault

Based on my understanding that array name at run time will be changed to char * type. I thought str is already char * so it should be able to point a string in the second case.

1) How in this case array works but str does not?

2) Where the difference between arr and str starts in this program? Why it should be obvious to programmers?

acidlategamer
  • 163
  • 2
  • 14

1 Answers1

1

When you are passing uninitialized pointers into scanf() which means undefined behaviour. So, allocate memory for pointer using malloc or calloc before calling scanf.

msc
  • 33,420
  • 29
  • 119
  • 214
  • so arr know that where is the 10 locations it is pointing to, but str do not know as str may have some garbage value that is not an address or permissible address to access? – acidlategamer Mar 25 '17 at 10:21