[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 233
  • Last Modified:

Multiple Indirection

Hi,
     I'm writing a program and I want to set up a variabel to hold dynamic length strings(char *), and I'm thinking
that I should use char ** for that variable? But then here comes my real question, since that will hold a variable ammount of those char * strings(accessed via char **foo[0] char **foo[1] etc.) how do I allocate dynamic memory for that? foo = (char **) malloc(sizeof(char) * 500) (Obviously in the real code I'd have something more dynamic than a flat 500, but).

       thanks, Jason
0
jwilcox
Asked:
jwilcox
1 Solution
 
imladrisCommented:
If you wish to declare a variable to hold one dynamic length
string it would indeed be a char *; e.g.

char *foo;

foo=malloc(500);

foo is pointer to character, and it now points at a block of
memory containing 500 bytes. Or to put another way, it is a pointer
to an array of characters. Or foo could be a string (if the
memory will be null terminated.

To get a variable number of these you could indeed declare:

char **foo;

To allocate memory for this, you would need two steps:

foo=malloc(10*sizeof(char *));

This has allocated a block of memory that will hold 10 pointers
to character. To access it you can write foo[0] (or its
equivalent *foo). This references the first pointer to character
in the array. foo[1] would access the second one etc.

To actually allocate a string you now write:

foo[0]=malloc(20);

This makes pointer to character in foo[0] point to a block of
memory that contains twenty bytes. It can, of course, be
considered an array, or a string. foo[1], foo[2], foo[3] etc.
can be initialized the same way.

So you see, in this case, where you have a dynamic number of
dynamic sized objects, char **foo really is pointer to pointer to
character. The code will literally follow the pointer in foo to
find something that is a pointer to another block of memory.

0
 
jwilcoxAuthor Commented:
Alright, that is what I thought, but just wanted to make sure, thankyou!
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now