1
I’m making a program for a simple purpose: Take a sentence and turn it into a version of it with the characters of each word isolated to the contrary, as: "I’m in trouble" would become "uotsE moc samelborp". When compiling with gcc questao1.c -o Q1 -g, write gdb . /Q1 and run, it shows 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. Follows 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);
}
Thank you for your help, it was literally my solution. I don’t think I was very clear about the purpose of the program which may have caused you a confusion: The idea was not to reverse the whole stack but to invert the isolated words from the stack. So I took his program and, based on it, I added what was necessary for this goal: https://pastebin.com/tMxGncB7 (I still don’t know how to move very well with stack overflow, so I went pro Pastebin because it is simpler to put whole codes)
– J. Gaidzinski