I'm getting the following error message in my code:
Segmentation fault (core dumped)
Another thing is that when I performed the same operation as preenche
on main
, using ficha.name
instead of dados
, the system printed only the first letter.
Why is the string not printing in full? And why do I get the error when I use the function?
#include<stdio.h>
#include<stdlib.h>
typedef struct{
char *name;
char *phone;
char *city;
char *state;
}ficha_t;
void aloca (char *ptr){
ptr = (char*) calloc (1, sizeof(char));
if(ptr == NULL){
puts("** Memória Insuficiênte **");
exit(0);
}
}
char *preenche (){
char *dados;
int i = 0;
do{
aloca(dados);
dados[i] = getchar();
i++;
}while(dados[i] == '\n');
dados[i] = '#include<stdio.h>
#include<stdlib.h>
typedef struct{
char *name;
char *phone;
char *city;
char *state;
}ficha_t;
void aloca (char *ptr){
ptr = (char*) calloc (1, sizeof(char));
if(ptr == NULL){
puts("** Memória Insuficiênte **");
exit(0);
}
}
char *preenche (){
char *dados;
int i = 0;
do{
aloca(dados);
dados[i] = getchar();
i++;
}while(dados[i] == '\n');
dados[i] = '%pre%';
return (dados);
}
int main(int argc, const char *argv[])
{
ficha_t ficha;
ficha.name = preenche();
printf("%s", ficha.name);
return 0;
}
';
return (dados);
}
int main(int argc, const char *argv[])
{
ficha_t ficha;
ficha.name = preenche();
printf("%s", ficha.name);
return 0;
}