-1

Why this code not working

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char **orderedIds;
    orderedIds = malloc(3 * sizeof(char*));
    for (int i = 0; i < 3; i++){
        orderedIds[i] = malloc((10) * sizeof(char));
        char name[10];
        printf("Enter name %d: \n",i);
        scanf("%s",&name);
        orderedIds[i] = name;
        printf("%s\n",orderedIds[i]);
    }
    printf("element is %s\n",orderedIds[0]);
}

Every element is the last element in the array i dont know why its not working plz help this is the output

Enter name 0:
john
john
Enter name 1:
guy
guy
Enter name 2:
some
some
element is some

some should be the last element but its the first why?

Lundin
  • 195,001
  • 40
  • 254
  • 396
nitu sahay
  • 11
  • 3

1 Answers1

0

You are doing shallow copying which means you are assigning two pointers to the same memory location so that they are both affected if one of them changes the pointed value state. See the shallow copy link

How to solve it? You need to do deep copying. Luckily, there is a built-in function in string.h library for that purpose. Here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char **orderedIds;
    orderedIds = malloc(3 * sizeof(char*));
    for (int i = 0; i < 3; i++){
        orderedIds[i] = malloc((10) * sizeof(char));
        char name[10];
        printf("Enter name %d: \n",i);
        scanf("%s",&name);
        strcpy(orderedIds[i], name);
        printf("%s\n",orderedIds[i]);
    }
    printf("element is %s\n",orderedIds[0]);
}