[C] Problema durante la stampa di alcune stringhe in linguaggio C

Messaggioda GN00Fu » 08/06/2020, 22:09

Ho appena finito di studiare le stringhe e le funzioni malloc/calloc in C. Sto provando a mettere insieme le cose ma ho un problema:


code:


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

int main(void) {
char **arr;
arr = (char **)malloc(4*sizeof(char *));

int i;
for (i=0; i<4; i++)
arr[i] = (char *)malloc(20*sizeof(char));

for (i=0; i<4; i++) {
printf("Insert the name of the alumn\n");
scanf("%s", &arr[i][1]);
printf("Insert the surname of the alumn\n");
scanf("%s", &arr[i][2]);
printf("Insert the grade of the alumn\n");
scanf("%s", &arr[i][3]);
}

for (i=0; i<4; i++) {
printf("The name of the alumn is %s", arr[i][1]);
printf("The surname of the alumn is %s", arr[i][2]);
printf("The grade of the alumn is %s", arr[i][3]);
}
return 0;
}

Credo che la scanf funzioni a dovere (quantomeno il compilatore non da errore), ma la printf non funziona e per ogni printf nel ciclo alla fine del codice ottengo l'errore:

warning: format '%s' expects argument of type 'char *', but argument 2 has type 'int' [-Wformat=]

Non capisco perché dice che l'argomento 2 ha tipo int. Forse non ho capito bene come sfruttare la malloc in modo da creare un array bidimensionale di stringhe?

Grazie in anticipo per ogni risposta.
GN00Fu
New Member
New Member
 
Messaggio: 23 di 64
Iscritto il: 08/04/2020, 21:48

Re: [C] Problema durante la stampa di alcune stringhe in linguaggio C

Messaggioda DeltaEpsilon » 08/06/2020, 23:29

Sarebbe meglio se formattassi il codice inserendolo tra gli opportuni tag, in modo da renderlo più leggibile.

Il problema risiede nel fatto che hai creato una matrice di char non di stringhe.

Codice:
char **arr = (char **)malloc(4*sizeof(char *));

for (int i=0; i<4; i++)
     arr[i] = (char *)malloc(20*sizeof(char));


Hai creato 4 char* e successivamente ognuno di essi lo hai fatto puntare a un array di 20 caratteri (char)

Ma a te servono 4 array di stringhe, non di caratteri... quindi la frase precedente deve diventare:

Hai creato 4 char** e successivamente ognuno di essi lo hai fatto puntare a un array di 20 stringhe (char*)



Immagine
É così dichiarato che è celato! Non c'è nulla di più sfuggente dell'ovvio. (Sherlock Holmes)
Avatar utente
DeltaEpsilon
Average Member
Average Member
 
Messaggio: 198 di 648
Iscritto il: 08/04/2019, 18:58

Re: [C] Problema durante la stampa di alcune stringhe in linguaggio C

Messaggioda GN00Fu » 11/06/2020, 12:44

Scusami per la formattazione, non credevo ci fosse una funzione specifica.

Ho seguito il tuo consiglio ed ora funziona tutto, grazie mille!
GN00Fu
New Member
New Member
 
Messaggio: 24 di 64
Iscritto il: 08/04/2020, 21:48


Torna a Informatica

Chi c’è in linea

Visitano il forum: Nessuno e 1 ospite