Originariamente inviato da oregon
@Vincenzo ... la malloc da correggere era la seconda, non la prima ...
La versione corretta, come suggerito da Oregon:
codice:
char **temp = NULL;
int nRighe = 3;
int nLen = 64; // Max 63 caratteri per stringa
// Allochiamo
temp = (char**)malloc(nRighe * sizeof(char*));
for ( int y = 0; y < nRighe; y++ )
temp[y] = (char*)malloc(nLen * sizeof(char));
strcpy(temp[0], "Stringa 1\n");
strcpy(temp[1], "Stringa 2\n");
strcpy(temp[2], "Stringa 3\n");
for(int x = 0; x < nRighe; x++)
printf("%s\n", temp[x]);
// Deallochiamo
for (int k = 0; k < nRighe; k++)
free(temp[k]);
free(temp);
temp = NULL;
Stranamente però, funziona anche così:
codice:
// Allochiamo
temp = (char**)malloc(nRighe * sizeof(char));
for ( int y = 0; y < nRighe; y++ )
temp[y] = (char*)malloc(nLen * sizeof(char));
Mah!
Attenzione: il fatto che funzioni non vuol dire che va bene usare "sizeof(char)" per la prima riga. Usate la varsione suggerita da oregon.