ayo ayo - 3 months ago 17
C Question

How do I save a string to a struct array member?

I am trying to save the string on array[0] to persons[0].name but I get this error: assignment to expression with array type. What should I do?

#include <stdio.h>
#include <stdlib.h>
struct person{
char name[25];
};
int main(){
struct person persons[10];
int i=0;
int array[10];
char str[] ="This is a test";
char * pch;

printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ");
while (pch != NULL)
{
array[i]=pch;
pch = strtok (NULL, " ");
i++;
}
//persons[0].name=array[0]; //error: assignment to expression with array type
printf("persons.name: %s\n", persons[0].name);
printf("array[0] = %s", array[0]);
}

Answer

try :

strcpy(array,persons[0].name)