after the memory is allocated you are not checking whether the memory is allocated or not allocated.Also, do you spot something that I am NOT doing here that I should (as part of proper housekeeping)?
you are not releasing memory after it has been used
I ran code on my systemRun it and see if you can spot a behavior that you probably don't expect.
C:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUFFERSIZE 20
int main(void)
{
char buffer[BUFFERSIZE];
printf("How many players? ");
fgets(buffer, BUFFERSIZE, stdin);
int players = atoi(buffer);
char **playerNames = NULL;
playerNames = (char **) malloc(players * sizeof(*playerNames));
if ( playerNames != NULL) // Memory allocated
{
for (int player = 0; player < players; player++)
{
printf("Name for player #%i: ", player);
fgets(buffer, BUFFERSIZE, stdin);
playerNames[player] = (char *) malloc(sizeof(char) * strlen(buffer));
strcpy(playerNames[player], buffer);
}
printf("Here are your players:\n");
for (int player = 0; player < players; player++)
{
printf("%i) %s\n", player, playerNames[player]);
}
free(playerNames);
}
return 0;
}
Name for player #0: bob
Name for player #1: devid
Name for player #2: mack
Here are your players:
0) bob
1) devid
2) mack
you are declaring pointer to pointer type char. we are allocating memory for playerNamesWhen I get back later today I can explain why it is doing that and how to deal with it. That will also put be into a position to tell you how you can deal with a really, really long name.
I don't understand what does following lines do in code
Code:
playerNames = (char **) malloc(players * sizeof(*playerNames));
Code:
playerNames[player] = (char *) malloc(sizeof(char) * strlen(buffer));