yet another pointer question

Started by
4 comments, last by mightypigeon 15 years, 2 months ago
I want to create an indeterminate array of strings with a length of 80 characters like so:
char *text[80];
but this would create an array of 80 pointers which I dont need. whats the solution? would it be
char text[][80];
if so, why? (no this isnt homework or anything like that - I finished school 10 years ago).
Advertisement
My first thought is, why?

But anyway...

Why not create a std::vector or std::list of std::strings and just truncate them when you put them into the list.

Overall it would seem more elegant and less fraught with pitfalls.
Feel free to 'rate me down', especially when I prove you wrong, because it will make you feel better for a second....
Warning: I have not tested this code, and honestly it looks potentially deadly [wink]

typedef struct iArr {        char str[][80] ;} ;int main(){    int num = 4 ;    iArr * arr = (iArr*)malloc( sizeof(iArr) * sizeof(char) * num) ;    }


I think the malloc is incorrect, but something like this may "work". You should now be able to do something like:

arr->str[3][27]


EDIT: This 'works' on gcc 4.2

[Edited by - smc on February 18, 2009 12:45:28 AM]
∫Mc
Quote:Original post by scratt
Why not create a std::vector or std::list of std::strings and just truncate them when you put them into the list.


because I like to be difficult! hehe nah just joking. well, almost. because I'm using C, not C++ and also because I want to understand the problem better.
you could use the suggested solution above, otherwise, if you would like to stick to c - strings, heres what to do (i think this is what you want):

//first [] is the amount of strings (given a value at compile time, i think).//[80] is the possible/allocated length for each string in the array.char text[][80] = {	"Hello "	,	"world! "	,	"My "		,	"name is"	,	"Reegan!"	,};


Then, you can access those strings in the 2d array above by doing the following:

std::cout << text[0] << std::endl; //string 0 = Hellostd::cout << text[1] << std::endl; // string 1 = World!std::cout << text[2] << std::endl; // string 2 = Mystd::cout << text[3] << std::endl; // and so on ...std::cout << text[4] << std::endl; // ...


i might not being doing it right, but give it a go (i dont often use 2d arrays)
Hope that helps!

~Reegan

EDIT: Confirmed, i just tested the code and it works for me.
Try this:

#define NUMSTRINGS 8char ( *text )[80];text = new char[ NUMSTRINGS ][80];// or call malloc with NUMSTRINGS * 80


Hopefully that does the trick!
[size="1"]

This topic is closed to new replies.

Advertisement