Am doing a task where am supposed to used getline function read input from a user from the terminal. Here is my code:
int main(int ac, char **av)
{
printf("Write something: \n");
char **buf = NULL;
size_t buf_size = 0;
ssize_t bytes_read = getline(buf, &buf_size, stdin);
if (bytes_read != -1)
write(STDOUT_FILENO, buf, buf_size);
else
printf("An error occured\n");
free(buf);
return (0);
}
From the code above. My program displayed the text: An error occurred. Did some code refactoring and this is what I came up with:
int main(int ac, char **av)
{
printf("Write something: \n");
char *buf = NULL;
size_t buf_size = 0;
ssize_t bytes_read = getline(&buf, &buf_size, stdin);
if (bytes_read != -1)
write(STDOUT_FILENO, buf, buf_size);
else
printf("An error occured\n");
free(buf);
return (0);
}
Voila! The code displayed whatever was inputted, just what I wanted. So I fixed my the issue. But what am trying to understand is what's wrong the first code snippet? An it is right to do this?:
char **name = "John Doe";
or
char **name = NULL;
I did some quick test on an online compiler. Here is the code:
int main() {
// Write C code here
char **name = "John Doe";
printf("%p\n", name); //0x55f5f9890004
printf("%p\n", *name); //0x656f44206e686f4a
printf("%c\n", *name); //J
printf("%p", "John Doe"); //0x55f5f9890004
return 0;
}
I realised that the double pointer was just treated as a single char pointer. Not sure if my finding are right. If you can give a better explanation the above main function that would be cool.
char **name = "John Doe";are in fact not okay to do and invoke undefined behavior down the linegetlinebe of this nature?*first_argumentcan be NULL. Doeschar **buf = NULL;do that? What is*bufin this case?