DPRG
DPRG List  



[DPRG] ANSI C question

Subject: [DPRG] ANSI C question
From: Tommy Raz tr at tommyraz.com
Date: Fri Oct 29 15:18:10 CDT 2004

Rick,
Your code literally reads "allocate a 2D array of pointers to strings of any
size" and then you allocate the data afterwards and point each one to it.  The
compiler might have to allocate space for the array of pointers because you
could later reassign any pointer to a differerent memory area.

The code below explicitly makes them fixed length and contiguous and doesn't
allocate memory for pointers:

char text[2][5][11]=	{{ "Msg 0,0   ","Msg 0,1   ","Msg 0,2   ",
			"Msg 0,3   ","Msg 0,4   "} ,
			{ "Msg 1,0   ","Msg 1,1   ","Msg 1,2   ",
			"Msg 1,3   ","Msg 1,4   "}} ;

You'll still have a null added to the end of each string.  You can address each
string as text[x][y] which references an offset from the 1st address in the
buffer allocated.

Examples of data access syntax:
test()
{ char c, *s;
  c=text[0][0][0];
  text[0][0][0]=c;
  s=text[0][0];
  // text[0][0]=s;  this is not allowed because we didn't allocate pointers
}

--Tommy

Quoting "Rick J. Bickle" <rbickle at swbell.net>:

> Hey all you C gurus:
>
> I'm working on a programming project and have a question.
> What is the correct syntax to declare a multidimensional array of fixed
> length strings?
>
> If you declare an array of char pointers like:
>
> Char *text [2][5];
>
> text[0][0] = "Msg 0,0   ";
> text[0][1] = "Msg 0,1   ";
> text[0][2] = "Msg 0,2   ";
> text[0][3] = "Msg 0,3   ";
> text[0][4] = "Msg 0,4   ";
> text[0][5] = "Msg 0,5   ";
>
> text[1][0] = "Msg 1,0   ";
> text[1][1] = "Msg 1,1   ";
> text[1][2] = "Msg 1,2   ";
> text[1][3] = "Msg 1,3   ";
> text[1][4] = "Msg 1,4   ";
> text[1][5] = "Msg 1,5   ";
>
> Will this leak memory? There is no declaration of the size of each
> string.
>
> If this is not right, what is the correct syntax?
>
> Rick
>



More information about the DPRG mailing list