I'm always wondering what is the difference between those two in C
char *str;
char str[50];
I have the following code used to read string from user input instead of using gets.
int read_line(char *str, int n);
int main (int *argc, char *argv[])
{
char *str;
read_line(str, 50);
printf("%s", str);
return 0;
}
int read_line(char *str, int n)
{
int ch, i = 0;
while((ch = getchar()) != '\n')
{
if(i < n)
{
*str++ = ch;
i++;
}
}
*str = '\0';
return i;
}
The compilation works fine as expected but get crashed when I tried to run.
And then I change the argument to the read_line()
function, instead of char *str
i use char str[50]
.
The program runs as expected when using char *str[50]
as argument.
can someone explain why this happens? or what is the main difference
of pointer to char
and character array
?