I'm doing a program for a simple purpose: Take a phrase and turn it into a version of it with the characters of each word isolated to the contrary, like: "I'm in trouble" would turn "uotsE moc samelborp". When compiling with gcc questao1.c -o q1 -g, writing gdb ./q1 and giving run, it displays the following error:
Program received signal SIGSEGV, Segmentation fault.
0x0000555555554836 in pilha_push (p=0x555555757010, v=101 'e') at questao1.c:23
23 p->c[p->topo] = v;
I have looked in many places and nothing has been useful to me. Here is the code:
#include<stdlib.h>
#include<stdio.h>
int N = 50;
typedef struct pilha{
char *c;
int topo;
}Pilha;
Pilha* pilha_cria(void)
{
Pilha* p = (Pilha*) malloc(sizeof(Pilha));
p->topo = 0;
return p;
}
void pilha_push (Pilha* p, char v)
{
if (p->topo == N) {
printf("Capacidade da pilha estourou.\n");
exit(1);
}
p->c[p->topo] = v;
p->topo++;
}
void inverte_palavra(char c[], int n){
char c1[n];
int i=0;
for(i=n-1;i>=0;i--){
c1[i] = c[n-i];
}
i=0;
for(i=0;i<n;i++){
printf("%c", c1[n]);
}
}
void zerar_char(char c[], int n){
char c1[n];
c = c1;
}
void inverter_pilha(Pilha *p){
int n = 0;
int i=0;
char c1[p->topo];
for(i = 0; i<p->topo;i++){
if(p->c[i] != ' '){
c1[i] = p->c[i];
n++;
}else{
inverte_palavra(c1, n);
n = 0;
zerar_char(c1, p->topo);
}
}
}
int main(){
Pilha *p;
p = pilha_cria();
pilha_push(p, 'e');
pilha_push(p, 's');
pilha_push(p, 't');
pilha_push(p, 'a');
pilha_push(p, ' ');
pilha_push(p, 'p');
pilha_push(p, 'r');
pilha_push(p, 'o');
pilha_push(p, 'v');
pilha_push(p, 'a');
inverter_pilha(p);
}