简体   繁体   English

在C中使用字符串的“数组”

[英]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*))); 您可以动态分配一个char *数组,以容纳每个字符串char **strings = (char**) malloc(NUM_OF_STRINGS * (sizeof(char*))); calling realloc() as necessary to allocate more strings. 根据需要调用realloc()以分配更多字符串。 For each string you add to the array of strings, also dynamically allocate with malloc strings[index] = (char*) malloc(SIZE_OF_STRING); 对于添加到字符串数组中的每个字符串,还使用malloc strings[index] = (char*) malloc(SIZE_OF_STRING);动态分配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. 您需要跟踪分配的这些字符串的数量,并相应地调整strings数组的大小。 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 * . 创建一个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. 当您需要使用一个时,请使用malloc()分配适当大小的缓冲区(请记住为空字符留出空间),或者如果您已经有要复制的字符串,请使用strdup()进行分配内存并根据需要从中复制。

You can allocate each string in the dynamic memory by strdup(), and thereafer - just use pointer ti this string. 您可以通过strdup()在动态内存中分配每个字符串,然后使用-将该字符串用作指针。 don't forget free(ptr), after string is used. 使用字符串后,不要忘记free(ptr)。

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对其进行扩展。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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