displaying 2d char array

SGDK only sub forum

Moderator: Stef

Post Reply
orlanrod
Very interested
Posts: 99
Joined: Fri Sep 25, 2015 7:46 pm

displaying 2d char array

Post by orlanrod » Thu Oct 15, 2015 12:05 am

Having trouble displaying the contents of a 2D char array. I can make it work with a single array, but not 2D.

This is the code. i get random data in entitydata[0][1] for some reason.

intToStr(entitydata[0][0], convertint[0], 0);
intToStr(entitydata[0][1], convertint[0][1], 0);
VDP_drawText(convertint[0], 1, 0);
VDP_drawText(convertint[0][1], 5, 0);

Stef
Very interested
Posts: 3131
Joined: Thu Nov 30, 2006 9:46 pm
Location: France - Sevres
Contact:

Re: displaying 2d char array

Post by Stef » Thu Oct 15, 2015 7:57 am

I don't know how you declare your char* array but seeing some others parts of your sources :

Code: Select all

const char *mytxt[50][50];
int loc;

char* getGameTxt(int txtnum, int txtnumtwo)
{
   mytxt[0][0] = "PLAY";
   mytxt[1][0] = "OPTIONS";
...
}
You cannot do that.
You have to declare your string array this way :

Code: Select all

// declare 50 string of 50 characters max (49+terminator actually)
char mytxt[50][50];
then affect it that way :

Code: Select all

// copy "PLAY" in string[0]
strcpy(mytxt[0], "PLAY");
// copy "OPTIONS" in string[1]
strcpy(mytxt[1], "OPTIONS");
you always have to use the strcpy method to copy a value into a string (char[]).
Look inside the string.h file to learn more about the available string methods :)

matteus
Very interested
Posts: 336
Joined: Mon Feb 04, 2008 1:41 pm

Re: displaying 2d char array

Post by matteus » Thu Oct 15, 2015 5:32 pm

Lol I'd not noticed the const on his code!

mikejmoffitt
Very interested
Posts: 86
Joined: Fri Sep 25, 2015 4:16 pm

Re: displaying 2d char array

Post by mikejmoffitt » Thu Oct 15, 2015 6:17 pm

You can do this:

Code: Select all

const char *strings[] = {
  "A C String",
  "Another C string",
  "A final C string"
};
You can then refer to strings[0], strings[1], strings[2], etc and do

Code: Select all


VDP_drawText(strings[0], 1, 0);
VDP_drawText(strings[1], 5, 0);

// etc

When I use static arrays like this, I like to null terminate the last element (make the last one a zero) so I can easily iterate through at the start and establish the length of the array. Of course, if you need a zero in there, you can create your own unique terminator, or just know the size and be careful.

Post Reply