Re: Help with code

From: E Harper (oxford_thames@on.aibn.com)
Date: 11/25/02


From: "Marcelus Trojahn" <mtrojahn@LAGOSNET.COM.BR>
> Consider de following variable:
>
> char *chmap[] {
>   "-----\r\n",
>   "-----\r\n",
>   "-----\r\n" };
>
> Well,  my  problem  is  that  sometimes  I  need  to  change some of the
> characters  on  that string to another one...
[snip]
> How can I do that by code?
> I had tryed something like "chmap[0][1]='A';" without success...

OK, here's the problem. What you made there was an array of *pointers to
char*. So you actually have chmap[0], [1]. and [2], each of which is
filled with some value like 0x0ce4a7002, a memory address. The actual
strings are off in memory somewhere. When you declare the variable as char
*string = "hello", six bytes of memory get allocated somewhere and a char
pointer gets allocated to them. Changing those bytes off in memory is
possible, but very bad to do.

If you need strings that can change for some reason, actually declare them
as a two-dimensional char array, like char chmap[3][7], and use them that
way. But I wonder, why do you need this at all?

Oh, and as for char blabla[] being variable-length, IT IS NOT. C does
*not* have variable length arrays. If you do array[] = { {1, 1}, {2 2},
{3, 3} }, you'll get a [3][2] array, and IT WILL STAY THAT SIZE. Almost
certainly you can get away by declaring the string as long as it would
possibly need to be. If you really need variable lengths strings you can
dynamically allocate them with malloc and manage them with pointers.

elh

--
   +---------------------------------------------------------------+
   | FAQ: http://qsilver.queensu.ca/~fletchra/Circle/list-faq.html |
   | Archives: http://post.queensu.ca/listserv/wwwarch/circle.html |
   | Newbie List:  http://groups.yahoo.com/group/circle-newbies/   |
   +---------------------------------------------------------------+



This archive was generated by hypermail 2b30 : 06/25/03 PDT