0

I'm creating a program that asks the user to enter the number of their friends, then the program makes a pointer to string array and allocating dynamic memory according to the number of friends, then the user is asked to enter the names of his friends, and the program adds the names to the array. My problem is when i'm getting the friend's names my program crashes and i can't access the string in the array and their letters

I tried changing the way i'm accessing the string from names[i] to (names + i) but when i do this i can't access the letter of the string.

int num_of_friends = 0;
char** names = { 0 };
int i = 0;

// Getting from the user the number of friends
printf("Enter number of friends: ");
scanf("%d", &num_of_friends);
getchar();

// Allocating dynamic memory for the friends's names
names = (char*)malloc(sizeof(char*) * num_of_friends);
// Getting the friends's names
for (i = 0; i < num_of_friends; i++)
{
    printf("Enter name of friend %d: ", i + 1);
    fgets(names[i], DEFAULT, stdin);
    // Removing the \n from the end of the string
    names[i][strlen(names[i]) - 1] = '\0';
}
// Just a test to see if it prints the first string
printf("Name: %s\n", names[0]);

I expect the output to be the the strings in the array without the \n at the end aswell.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
xBm
  • 69
  • 8
  • [Do I cast the result of malloc?](https://stackoverflow.com/q/605845/2173917) – Sourav Ghosh Apr 16 '19 at 13:10
  • Your array should be init this way `char* names = (char*) malloc(sizeof(char) * num_of_friends);` and don't forget to free it later `free(names);` – acarlstein Apr 16 '19 at 13:16
  • After malloc. `names` is just an array of uninitialized pointers. You must assign them to point at something meaningful, you can't just "store data into the pointers". For example you can malloc space for every string. – Lundin Apr 16 '19 at 13:23

1 Answers1

0

You have allocated memory to names, equal to the size of a char *, multipled by the amount of num_of_friends. So, you have names[0] to names[num_of_friends-1] elements allocated.

However, the names[i] does not point to any valid memory block. Just like the names, you need to allocate memory to each names[i].

Something like

for (i = 0; i < num_of_friends; i++)
{
  names[i] = malloc(DEFAULT);
  assert(names[i]);  // check against failure
}

before you can expect to write into them, like

for (i = 0; i < num_of_friends; i++)
{
    printf("Enter name of friend %d: ", i + 1);
    fgets(names[i], DEFAULT, stdin);
    // Removing the \n from the end of the string
    names[i][strlen(names[i]) - 1] = '\0';
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261