Code:
/*
The previous code and solution has evolved into a different issue now. When this program is run,
it produces this output:
zzz.y = Hello <> zzz.y2 = (null)
zzz.y = World - zzz.y2 = World
z[15]->y = World ->y2 = World
When I add the 'a1' variable, in place of the 2nd instance of the 'a' variable, I get this output:
zzz.y = Hello <> zzz.y2 = (null)
zzz.y = Hello - zzz.y2 = World
z[15]->y = Hello ->y2 = World
This is a pointer issue that I can't really comphrend. I see what is happening, but I don't understand
it. The 2nd iteration is what I am looking for but I do not want to have to use a different string
variable for each new 'word'. I thought that strcpy made a new copy of the source, pointed to by
only destination, but it appears that destination is still pointing to source (not just a copy).
Therefore, when 'a1' gets a new value in the second instance, .y points to it too and not the first word.
How can this be fixed?
*/
#include <stdio.h>
#include <string.h>
struct x {
char *y;
char *y2;
};
#define MAX 100
struct x *z[MAX], zzz;
int main ()
{
char a[100];
//char a1[100];
int n=15;
strcpy(a,"Hello\0");
zzz.y = &a[0];
printf("zzz.y = %s <> zzz.y2 = %s\n",zzz.y,zzz.y2);
strcpy(a,"World\0");
zzz.y2 = &a[0];
//strcpy(a1,"World\0");
//zzz.y2 = &a1[0];
printf("zzz.y = %s - zzz.y2 = %s\n",zzz.y,zzz.y2);
z[n] = &zzz;
printf("z[%i]->y = %s ->y2 = %s\n",n,z[n]->y,z[n]->y2);
}