You probably want this:
#include <stdio.h>
#include <string.h>
int main(void)
{
char temp[256];
char *st[3]; // array of three pointers to char
for (int i = 0; i < 3; i++)
{
scanf("%255s", temp); // prevents potential buffer overflow
st[i] = strdup(temp);
}
for(int i = 0; i < 3; i++)
{
printf("%s\n", st[i]);
free(st[i]); // free strduped memory
}
}
This program displays:
./a.out
11
22
33
11
22
33
Whereas your program displays
./a.out
11
22
33
33
33
33
this is because:
char *st; // in your prog. you only declare one pointer
for (int i = 0; i < 3; i++)
{
scanf("%s", temp);
st= strdup(temp); // here you overwrite the st pointer loosing
// the string strduped in the previous run of the loop
}
1
solved What is the right way to explain this code? [closed]