Originally Posted by
dougieb
also I think (with a combination of what you guys have said and that tutorial) my problem was that
Code:
hostlist[0].name = "myspace.com"
worked, but
Code:
hostlist[0].name = hp->h_name
didn't. BUT, the "myspace.com" string constant, which is just a char array with a beginning address/pointer. but, memory is allocated as it's initialized. so, these two lines are effectively doing the same thing, copying a pointer. it's just that (now obvious, and as was said in the first reply) the string constant is not overwritten so hostlist[0].name can point to it as long as it exists without it being overwritten; unlike the static memory location of gethostbyname. but, crucially, for my understanding, both of the above assignments are doing the same thing, assigning pointers. and the strcpy is used to copy the contents out to a new memory location, and then it is copying the address of that new memory location into hostlist[i].name
thanks for all your help. I'll keep practicing :-)
Ok, here's a little code sample I post from time to time to illustrate why you should not try to return arrays from functions... or in your case assign pointers to static arrays... Give this a run, I'll bet it explains your problem for you...
Code:
#include <stdio.h>
int* MyFunction(int a, int b, int c)
{ static int array[3];
array[0] = a;
array[1] = b;
array[2] = c;
return array; } // return a pointer.
int main (void)
{ int *a1, *a2; // int pointers
printf("calling a1 = MyFunction(10,20,30);\t");
a1 = MyFunction(10,20,30);
printf("a1 has %d %d %d\n",a1[0],a1[1],a1[2]);
printf("calling a2 = MyFunction(100,200,300);\t");
a2 = MyFunction(100,200,300);
printf("a2 has %d %d %d\n",a2[0],a2[1],a2[2]);
printf("\nLooks good, except...\t");
printf("a1 now has %d %d %d\n",a1[0],a1[1],a1[2]);
getchar();
return 0; }