printf("ENTER NAME1\n");
scanf("%s",&n1.p);
printf("\nENTER NAME2\n");
scanf("%s",&n2.p);
Where do you want to store the strings with the names into?
Into the object of the pointer p
inside of the respective structure itself?
This is invalid and illegal. Pointers are made to point anywhere, not to be assigned with a value of an object they do point to themselves.
Thus to answer your question:
"How do pointers in the structure work in the following code?"
They don't work at all. Your code is a mess of undefined behavior.
You need to allocate memory first, where p
is pointing to, f.e. by using malloc()
:
n1.p = malloc(sizeof(char) * 20); // Allocates memory for a string up to 19 characters.
if (!n1.p)
{
fputs("Error at allocation!", stderr);
return EXIT_FAILURE;
}
n2.p = malloc(sizeof(char) * 20); // Allocates memory for a string up to 19 characters.
if (!n2.p)
{
fputs("Error at allocation!", stderr);
return EXIT_FAILURE;
}
and then pass the argument to scanf()
properly:
printf("ENTER NAME1\n");
scanf("%s", n1.p);
printf("\nENTER NAME2\n");
scanf("%s", n2.p);
(Note n1.p
instead of &n1.p
. Same goes for n2.p
)
Or better:
printf("ENTER NAME1\n");
if (scanf("%s", n1.p) != 1)
{
fputs("Error at input!", stderr);
return EXIT_FAILURE;
}
printf("\nENTER NAME2\n");
if (scanf("%s", n2.p) != 1)
{
fputs("Error at input!", stderr);
return EXIT_FAILURE;
}
to ensure safety at input errors.
Furthermore the %s
conversion specifier expects an argument of type char *
, not pointer to char *
(char **
) as it is with &n1.p
and &n2.p
.
To provide an argument of wrong type invokes undefined behavior, too.
Just use n1.p
and n2.p
.
Also this printf()
call is wrong:
printf("ENTERED NAMES ARE %s , %s", &n1.p,&n2.p);
You need to omit the &
too:
printf("ENTERED NAMES ARE %s , %s", n1.p, n2.p);
All in one:
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
struct name
{
char *p;
} n1, n2;
n1.p = malloc(sizeof(char) * 20); // Allocates memory for a string up to 19 characters.
if (!n1.p)
{
fputs("Error at allocation!", stderr);
return EXIT_FAILURE;
}
n2.p = malloc(sizeof(char) * 20); // Allocates memory for a string up to 19 characters.
if (!n2.p)
{
fputs("Error at allocation!", stderr);
return EXIT_FAILURE;
}
printf("ENTER NAME1\n");
if (scanf("%s", n1.p) != 1)
{
fputs("Error at input!", stderr);
return EXIT_FAILUE;
}
printf("ENTER NAME2\n");
if (scanf("%s", n2.p) != 1)
{
fputs("Error at input!", stderr);
return EXIT_FAILURE;
}
printf("ENTERED NAMES ARE %s , %s", n1.p, n2.p);
free(n1.p):
free(n2.p);
return 0;
}
Execution:
ENTER NAME1
Peter
ENTER NAME2
Maria
ENTERED NAMES ARE Peter , Maria