Question

I am talking about using char* and dynamic arrays. Specifically I want to use a 2d array to break up a line of commands and options into their components

For example:

char *dynamicArr = malloc(1 * sizeof(char));//allocate first letter
int i = 0;
while(string[i] != '\0'){
    dynamicArr[i] = string[i];
    //would I be able to allocate more memory onto the end of dynamicArr here?
}

Obviously I could just use strlen and strcpy in this case, but I am trying to parse a line of commands using various tokens, ' ' '\"' and '\''. So the individual strings are not null terminated. I have written it using Static 2d arrays but I want to make it dynamic so that it can handle commands of any size.

Was it helpful?

Solution

Will successive calls to malloc allocate space directly after the previous call in c?

No. Not necessary. malloc allocates contiguous chunk of memory but it doesn't guarantee that the next call to malloc will allocate the chunk just after the previous one.

I have written it using Static 2d arrays but I want to make it dynamic so that it can handle commands of any size.

Use realloc() function.

OTHER TIPS

//would I be able to allocate more memory onto the end of dynamicArr here?

Yes. The size of dynamicArr can be expanded using realloc().

No. Definitely not.

A block of memory allocated by malloc comes with no guarantees as to its location or its relationship with other blocks. There could be free space immediately after it, but just as likely there is not. There is no way to extend it, and no way to determine whether it could be extended.

What you can do instead is to use realloc(). A call to realloc will return a pointer to a block of memory just like malloc, while preserving the contents of the block passed in, but not necessarily in the same location. Depending on the size requested (smaller, same size, or bigger) and the availability of space in the heap, realloc may return the original block adjusted in size as needed, or it may return a new block in a different location. In the latter case realloc will copy the old contents into the new block.

The important thing to remember is that the pointer returned by realloc could be different, so you must assume that it will be and code accordingly.

However, realloc is relatively expensive and should not be called character by character. A typical solution to your problem is to read into a large enough temporary buffer, allocation memory of the correct size and copy the data. In C++ you would use strings or vector of char and save yourself a lot of grief.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top