我一直在搜索并尝试运行简单的测试程序,但我仍然无法弄清楚这一点:
是否有可能在纯 C 中动态分配指向数组的指针?
我想要完成的是将一个字符串复制到一个 char[20] 数组,但是这些 char 数组的数量是未知的。我声明的变量是
char (*value)[20]
据我了解,这是一个指向 20 个字符数组的指针,这正是我所需要的
但是,如何为这个变量分配内存?在我不知道将存在的 char[20] 数量的情况下,如何动态地执行此操作?我是否认为这是解决我的设计问题的方法?
谢谢。
我一直在搜索并尝试运行简单的测试程序,但我仍然无法弄清楚这一点:
是否有可能在纯 C 中动态分配指向数组的指针?
我想要完成的是将一个字符串复制到一个 char[20] 数组,但是这些 char 数组的数量是未知的。我声明的变量是
char (*value)[20]
据我了解,这是一个指向 20 个字符数组的指针,这正是我所需要的
但是,如何为这个变量分配内存?在我不知道将存在的 char[20] 数量的情况下,如何动态地执行此操作?我是否认为这是解决我的设计问题的方法?
谢谢。
如果您想要一个大小增加的数组,您别无选择,只能动态分配内存,例如,如果您知道所有字符串将正好有20 个字符:
#define STR_SIZE 20
char* values = NULL;
int nb = 0;
...
// Called every time a string is received
// Here valuesPtr is a char** since we want to change values
void appendStr(char** valuesPtr, int* nb, char* string) {
if (*nb == 0) { // First item
*valuesPtr = malloc(STR_SIZE);
} else { // The size of the array changes : realloc it
*valuesPtr = realloc(*valuesPtr, STR_SIZE * (*nb + 1));
}
if (*valuesPtr == NULL) { // Something went wrong !
perror("malloc/realloc");
exit(1);
}
// Copy the new string at the right place
memcpy(*valuesPtr + STR_SIZE * (*nb), string, STR_SIZE);
*nb++;
}
在其余代码中,访问第 n 个字符串是这样完成的:
values + (STR_SIZE * nb)
通常你会使用一个字符串数组:
char *strings[256]; // or use malloc/realloc but 256 pointers is OK
int cnt = 0;
void add_string(const char *s) {
strings[cnt] = (char*)malloc(strlen(s)+1); // or 21
cnt++;
// you can also do circular buffers
}
num_arrays这是一个将常量字符串写入值时间指向的数组数组的示例。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void func(int num_arrays)
{
const char* s = "A string";
char (*value)[20];
value = (char (*)[20]) malloc(sizeof(*value) * num_arrays);
int i;
for(i = 0; i < num_arrays; i++) {
strncpy(value[i],s,20);
}
for(i = 0; i < num_arrays; i++) {
printf("%s\n", value[i]);
}
}