Question:
C++ Segfault when comparing two characters?
?
2011-08-31 15:12:47 UTC
It says the segfault occurs on the 5th line.
strcmp() will not work for here because it needs to be a const char.
It uses SDL but I don't think that has anything to do with the problem.


void pstr(const char str[], int x, int y, SDL_Surface* scr, SDL_Surface* chars){
int i;
int len = sizeof(str);
do{
if(str[i]=='a'){pchar(0,0,x+(i*8),y,scr,chars);};
//...
//... This here is just similar to the line above.
//...
}while(i};


I'm building it with g++ if that makes any difference.
Four answers:
Ratchetr
2011-08-31 15:21:54 UTC
You need to initialize i to 0. As it is, it will be a random value that isn't a valid index into str, which is why you fault.



Also, I'm pretty sure you don't want to set len to sizeof(str). Since str is a pointer (char str[] is equivalent to char *str), sizeof(str) will be sizeof a pointer, which is probably 4 on your system. If it doesn't make sense to always set len to 4, then you don't want sizeof. You probably want strlen(str), assuming str is a properly nul terminated string.
cauley
2016-12-13 19:43:16 UTC
i've got indexed 2 sites which could help you out. evaluate ability the failings that are alike. assessment ability the ameliorations. you're able to additionally contain on the tip of your essay why the ameliorations are significant.
PleaseInsertACoin
2011-08-31 15:35:13 UTC
While we're at it, when you're already using C++ don't use char* as strings, use std::string instead.
green meklar
2011-08-31 16:34:00 UTC
You didn't initialize i to anything. Are you sure that's what you intended to do?


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...