0
I am creating a code that for now needs to read the name of N companies (whose N is given). I’m trying to enter the names but the program just doesn’t read and it’s the first time I try dynamic matrix allocation. The code is here:
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
void LeiaDadosDasEmpresas( int quantEmpresas , char ** nomeEmpresas ){
int i ;
for( i = 0 ; i < quantEmpresas ; i++ ){
printf("\nDigite o nome da %dª empresa : ", i + 1 );
scanf("%[^\n]s", *(nomeEmpresas + i) );
}
}
int main()
{
int quantEmpresas, i ;
char ** nomeEmpresas ;
printf("Digite o numero de empresas que queira analisar : ");
scanf("%d", &quantEmpresas );
nomeEmpresas = (char **) malloc( quantEmpresas*sizeof(char *) );
for( i = 0 ; i < quantEmpresas ; i++ ){
*(nomeEmpresas + i) = (char *) malloc( 20*sizeof(char) ); /** cada nome possui no max 20 caracteres ( incluindo '/0 ' ) **/
}
LeiaDadosDasEmpresas( quantEmpresas , nomeEmpresas );
return 0 ;
}
"
malloc( 20*sizeof(char) ); /** cada nome possui no max 20 caracteres **/
" for 20 characters in the name, you need to reserve space for 21 bytes. And also ... C/C++ does not exist. In C++ it is advised to usenew
,delete
, etc; in C the use ofmalloc()
,free()
, etc is usual.– pmg
Yes. If it’s beautiful, but I’ve done a lot of c++ code using malloc() and free() and they’ve never been a problem.
– Alexandre Santiago da Silva
@Alexandresantiagodasilva I went several times to SP in never suffered any accident until today.
– Maniero
@Alexandresantiagodasilva Did any of the answers solve the problem? Do you think you can accept one of them? See [tour] how to do this. You’d be helping the community by identifying the best solution. You can only accept one of them, but you can vote for anything on the entire site.
– Maniero