Hello i wrote this program, it works perfect, however at the end i have a segmentation fault problem.. can anyone tell me how do i correct that mistake???
int main(){
char* word;
char letter;
int i=0;
printf ("Please enter the word.");
scanf("%s",word);
letter=*word;
while(letter!=0){
printf("%c\n",letter);
i++;
letter=*(word+i);
}
return 0;
}
The program works perfect, but when the program ends the segmentation problem appears.. For example, if i write "hello" the program does the following:
h
e
l
l
o
segmentation fault
char* is not a string, it's a pointer. If you want to use it, you have to make it point to something. Right now it's not pointing to anything (or, more accurately, it's pointing to garbage). When you copy a string to it (with scanf), you're corrupting memory, which is what's giving you a segfault.
A solution here is to use a C-style string (char buffer), ie:
char word[100];
But note that this method limits how long your word can be (you'll get a segfault if the user inputs a word longer than 99 characters).
A better solution is to use a C++ std::string and C++ iostreams (ie: cin/cout) instead of scanf()/printf(). Using std::string greatly reduces the risk of buffer overflow and segfaults (but doesn't completely protect against them).