Function keeps triggering Segmentation Faults.
I'm trying to write a function that will select the first word from a string. It compiles fine, but whenever I run it a segmentation fault is triggered. This code is written in C and compiled with DevC/C++. Any suggestions or help is appreciated.
//Prototype char *word(char *str1, char *str2);
int main() {
char *test_str = "Monday Tuesday";
char *result;
word(test_str, result);
printf("%s\n", result);
getchar();
return 0;
}
//Function Definition char *word(char *str1, char *str2) {
int x = 0;
char space = ' ';
while (str1[x] != space) {
str2[x] = str1[x];
x = x + 1;
}
getchar();
return str2;
};
while (str1[x] != space) {
str2[x] = str1[x];
x = x + 1;
}```
I'm punching in your code to test it right now, but I'm pretty sure that's the problem. C deosn't work like that.
EDIT: A side note, if you're going to increment "x" at the end, you may as well use a for loop.
Here is a quick fix that works. I will post something better in a moment (I just need to go learn what I want to do). Like I said, "I don't know C."
#include <stdio.h>
#include <string.h>
//Prototype
void word(char *str1);
int main() {
char test_str[] = "Monday Tuesday";
word(test_str);
getchar();
return 0;
}
//Function Definition
void word(char *str1) {
char *SpaceIndex=strchr(str1,' ');
int index = SpaceIndex-str1+1;
for (int i=0; i < index; i++){
printf("%c", str1[i]);
}
};
Edit : Sorry, I didn't see that it had been solved.
The problem is in this line :
str2[x] = str1[x];
Unhandled exception at 0x00411488 in test.exe: 0xC0000005: Access violation writing location 0x00000008. str2[x] = str1[x];
Read this, may help :
http://blogs.msdn.com/chappell/archive/2005/01/12/351856.aspx