-1

What i intend to achieve with this code is to take a string character from main function, and then assign it to name in structure at a specific index. Example: It should print for me Name=> Charles Key=> 0 Next line will be Name=> George Key=> 1...and so on. But it rather picks the last name entered and use it for all though my structure is an array of structure. I don't also want to take it direct in the main...like scanf("%s", &node[i].name) because in the real project i am building, i will calculate for i based on the what the user enters. Please help me out. Thanks

#include<stdio.h>
#include<stdlib.h>
typedef struct{
   int key;
   char *name;
}test;

int main(){
test node[5];

int i;
char see[10];
 //for loop for taking string character in see and then assigning name in structure to it 
for(i=0; i<5; i++){
 printf("Enter name\t");
 scanf("%s", &see);
 //assigns name in structure index i to see
 node[i].name=see;
 node[i].key=i;
}
//prints data stored in structure
for(i=0; i<5; i++){
  printf("Name=> %s\t\tKey=> %d",node[i].name, node[i].key);
}
return 0;
}

2 Answers2

0

You need to malloc space inside the struct and copy the text rather than assigning it. When you assign the pointer you are effectively making the struct's pointer point to the same memory so the next time you read into that memory you overwrite the old value.

Try replacing:

node[i].name = see;

with:

node[i].name = malloc(strlen(see) + 1);
if (node[i].name == NULL)
{
   // Handle Malloc error
}
strncpy(node[i].name, see, strlen(see) + 1);
twain249
  • 5,666
  • 1
  • 21
  • 26
0

Change as per following...

  1. char *name; ----> char name[10];
  2. scanf("%s", &see); ----> scanf("%s", see);
  3. node[i].name=see; ----> strcpy(node[i].name, see);
roottraveller
  • 7,942
  • 7
  • 60
  • 65
Yunbin Liu
  • 1,484
  • 2
  • 11
  • 20