Reputation: 1152
Here is the function I have, "Sprite" is an object in the program, and "GetSpriteAtPosition" just returns a pointer to the correct sprite at the coordinates.
My problem is that I store a letter in each sprite, in the form of an integer. 0 is a, and 25 is z, with everything in between respectively. I need my function to return a char* that gives me the letters of a row of sprites, so if in the program the sprites spell out "abcdefgh", then that's what I need this function to print out. There's an 8x8 grid of sprites, and I'm getting the coordinates correctly, but I get an error that I can't convert an int to a char* in the marked line. What can I do to get this to work?
Thanks in advance!
char* RowLetters(int row)
{
char* pointer;
for( int i = 0; i < 8; i++)
{
Sprite* selectedSprite = SpriteAtPosition(row*50, i * 50);
if(selectedSprite != NULL)
{
char* temp = (char)(selectedSprite->Frame() + 97); //error here
pointer = strcat(pointer, temp);
}
else
{
pointer = strcat(pointer, "test");
}
}
return pointer;
}
Upvotes: 0
Views: 223
Reputation: 1165
Try this:
char temp = (char)(selectedSprite->Frame() + 97);
pointer = strcat(pointer, &temp);
I've changed the variable into a standard char
rather than a pointer and then passed a reference to strcat()
with the &
operator.
EDIT:
As pointed out in the comments, this doesn't work because &temp
isn't NULL terminated. I used to get around this when I programmed more C by doing the following.
char temp[2];
temp[0] = (char)(selectedSprite->Frame() + 97);
temp[1] = '\0';
pointer = strcat(pointer, temp);
Of course, the temp
array could be declared outside the for()
loop for a little better performance (in theory).
None of this addresses the other problems with the code like pointer
never being declared. I think a broader understanding of the calling function would be in order to determine whether pointer
should be allocated within this function or passed in by the caller.
Upvotes: 3
Reputation: 19052
Your code as written, will have undefined behavior because pointer
is not initialized, and does not point to any valid memory that you have allocated (to hold the appropriate length of letters in the row.
If this truly is C++, as you state, then you don't want to return a char*
from this function, as that implies that you have a static string already allocated within that function (yuck), or you will be dynamically allocating the string in that function and the caller must free it (yuck).
Neither of these options is ideal.
I'd suggest a very simple change to return a std::string
, like this:
std::string RowLetters(int row)
{
std::string pointer;
for( int i = 0; i < 8; i++)
{
Sprite* selectedSprite = SpriteAtPosition(row*50, i * 50);
if(selectedSprite != NULL)
{
pointer.push_back((char)(selectedSprite->Frame() + 97));
}
else
{
// ???
// pointer = strcat(pointer, "test");
}
}
return pointer;
}
Upvotes: 2