Hi there,
i was trying to make a code wich would allow a user to insert a phrase and then the console app would print back the same phrase, although all the words of the phrase would be reverted (for example: 's''a''m''e' would be printed back as 'e''m''a''s'.
The editor don't accuse any error in the code, yet it keeps crashing when i run it.
I'm writing in C++ (Visual Studio 2015).
#include <stdio.h>
#include <string.h>
#define A 1000
void main()
{
char frase1[A], frase2[A];
int i=0, j=0, g=0, h=0; //j indicates the beggining of the word / g indicates the final of the word / h has the function of keeping the code working until the purpose of the code is achieved
printf("Insira frase:");
gets_s(frase1);
for (; h < strlen(frase1);)
{
while (frase1[i] == ' ')
{
i++;
frase2[i] = frase1[i];
j = i + 1;
}
g = j;
while (frase1[g] != ' ' || frase1[g] != '\0')
g++;
h = g;
for (; g >= j; g--)
{
frase2[j] = frase1[g];
j++;
}
}
frase2[strlen(frase1)] = '\0';
printf("Frase antiga: %s", frase1);
printf("Frase nova: %s", frase2);
}
Could you use [code][/code] tags? There is no indentation which makes the program almost unreadable.
Are you writing in C or C++? This looks like C to me.
void main(): The main function should return an int.
j, k, etc.: You have comment that explains the purpose of each variable. Why not just give them names?
Where does it crash? Have you opened a debugger to see what your program is trying to do? I'd guess an out-of-bounds memory access but you should find out for certain.
The editor don't accuse any error in the code, yet it keeps crashing when i run it.
This is an infinite loop:
1 2
while (frase1[g] != ' ' || frase1[g] != '\0')
g++;
It will not stop looping even when frase1[g] becomes '\0' because first condition frase1[g] != ' ' will be satisfied ('\0' != ' '). You might want to reconsider that line or to break if frase1[g] becomes '\0'.