0

I am trying to write up a string container for my string struct but it's not working. I feel like I've been showing everyone my code and expecting a simple answer to get me going but what I'd like is a tip or a few pointers to get me going. Right now I don't want this container to be able to hold anything else except a custom string that I wrote earlier, which is working fine by the way.

All the code is a simplified version of my real string struct because there's no need to post it; all we're dealing with is the string container.

header.h

typedef struct string string;

source.c

struct string {
    char *buffer;
    unsigned int size;
};

Would I do:

string ** array_of_strings;

or

string * array_of_strings;

then I want to do something like:

client.c

array_of_strings = (string *) malloc(0);

When I call malloc(0), I am wanting there to be array_of_strings[0] and if I realloc(1) I would like it to be array_of_strings[1].

Is there a better way to do this, because this isn't working?

4
  • 1
    malloc(0) will allocate 0 bytes of memory. Commented Nov 27, 2011 at 2:15
  • 1
    When you say malloc(0) you are saying: "Allocate 0 bytes of space on the heap." You want to allocate at least sizeof(string). You also want to allocate the buffer that the string struct points to. Commented Nov 27, 2011 at 2:16
  • This is a duplicate, see stackoverflow.com/questions/2575921/array-of-structs-in-c Commented Nov 27, 2011 at 2:37
  • You cannot use the standard malloc() and realloc() functions as you show; you could write your own with the non-standard semantics you request (but you would have to use different names, such as str_malloc() and str_realloc()). Note that names starting with str and a lower-case letter are reserved for future extensions of the standard C library. Commented Nov 27, 2011 at 3:06

1 Answer 1

1

If you want to have an array of one string, you should allocate memory for one string:

string * array_of_strings;
array_of_strings = malloc(sizeof(string));

and then you may access array_of_strings[0].

If you will declare it as string ** you actually declare a pointer to pointer to string, not a pointer to string.

Sign up to request clarification or add additional context in comments.

6 Comments

how would i realloc and be able to access array_of_strings[1]?
array_of_strings = realloc(sizeof(string)*2);
what if im doing char string = (char) malloc(strlen(string) + 1) am i reserving bytes or array slots?
I does not fit to the struct at all.
btw when i use my string struct it has to be a pointer does that mean i use 2 pointers or still use 1 like mbyd said to? i need an array of pointer structs
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.