-
Strings and Structures
I have a structure with a string defined inside it, is there a way to change the string later in my program....
CODE....
//define structure
struct myStruct {
char name[40];
int age;
};
//function to fill array of structures with values
void fillArray(struct myStruct *);
int main(void){
//create array of structs
struct myStruct myStructArray[10];
//put values in array of structs
fillArray(&myStructArray);
//print name from struct
printf("%s", myStructArray[2].name);
}
//fills array with values
void fillArray(struct myStruct * workwithStruct){
workwithStruct[2].name = "JOHN";
return;
}
if i print the name inside the fillArray function it will print fine but when I return to the main function it prints garbage
I'm new to structs, Can someone please help me out?
-
workwithStruct[2].name = "JOHN";
This is wrong. You have to use something like strncpy to fill the string.
Furthermore, you're accessing your pointed to structure entirely incorrectly. That's not how you access members of a structure via a pointer.
Quzah.
-
I wonder how the previous code compiled : the argument passed to the function fillarray was of the wrong type. The operator = does not copy strings in C; you have to use the function strcpy.
It is a good idea to include the appropriate headers.
Code:
#include <stdio.h>
#include <string.h>
struct myStruct {
char name[40];
int age;
};
void fillArray(struct myStruct *);
int main(void){
struct myStruct myStructArray[10];
fillArray(myStructArray);
printf("%s", myStructArray[2].name);
return 0;
}
void fillArray(struct myStruct * workwithStruct){
strcpy( (workwithStruct+2)->name,"JOHN");
return;
}
-
Thankyou, that was all the help i needed
I am new there was no reason to tear me down for doing it wrong, not everyone starts an expert!