简体   繁体   中英

Using an “Array” of Strings in C

I need to store a large number of strings to be use by my program. I cannot statically allocate the memory - but I'm not sure how to design the code for the dynamic allocation such that I can access it as an array as each block won't be of the same size.

How should I proceed?

What is unknown, the number of strings, size of strings, or both?

You can dynamically allocate an array of char *'s to hold each string char **strings = (char**) malloc(NUM_OF_STRINGS * (sizeof(char*))); calling realloc() as necessary to allocate more strings. For each string you add to the array of strings, also dynamically allocate with malloc strings[index] = (char*) malloc(SIZE_OF_STRING); You'll need to keep track of the number of these strings you allocate and resize the strings array accordingly. Each string will need to be free'd by iterating over the array of strings:

for(unsigned int i = 0; i < stringCount; ++i)
{
    free(strings[i]);
}

Create an array of char * . These will be uninitialized to begin with. When you need to use one, use malloc() to allocate a buffer of the appropriate size (remember to leave space for the null character), or if you already have a string that you're copying from, use strdup() to allocate the memory and copy from it as necessary.

You can allocate each string in the dynamic memory by strdup(), and thereafer - just use pointer ti this string. don't forget free(ptr), after string is used.

Example:

char *strings[10000]; // array for 10, 000 string pointers
int ndx = 0;
char strbuf[1000];

while(fgets(strbuf, sizeof(strbuf), f)
  strins[ndx++] = strdup(strbuf);

Are you looking for something like this:-

const char *a[20];
a[0] = "abc";
a[1] = "xyz";
.
.
.
.
a[19] = "try";

您可以在程序的开头分配一个小数组,然后使用realloc对其进行扩展。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM