我想要一个二维字符数组,当我不使用该结构时,我可以遍历数组并打印出字符串。但是,如果我将 2d char 数组分配给结构成员,我无法访问该数组,为什么?
typedef struct {
int num;
char **names;
} test;
test t;
t.num = 2;
char *names[t.num];
char *tmp;
tmp = "test";
names[0] = "something";
strcpy(tmp,names[0]);
strcat(tmp,"appendedtext");
names[1] = tmp;
names[2] = "something else";
t.names = names;
最佳答案
你真的应该在这里动态分配你的数组。你在这里尝试做的事情有很多问题。
- 您的数组已初始化为指向堆栈上的内存。
- 您正在存储指向字符串文字的指针并试图修改它们。
- 您正在访问超出数组范围的内存。
- 以及介于两者之间的一切。
碰巧我有一些实用函数可以使用单个分配动态分配二维数组。请随意在您的代码中使用它们。
static size_t getsize(size_t rows, size_t cols, size_t size)
{
size_t ptrsize = rows*sizeof(void *);
if (ptrsize%size != 0)
ptrsize += size - ptrsize%size;
return ptrsize + rows*cols*size;
}
static void init2d(void *mem, size_t rows, size_t cols, size_t size)
{
int i;
char **ptr = mem;
char *base = (char *)(ptr + rows);
size_t rowsize = cols*size;
size_t ptrsize = rows*sizeof(char *);
if (ptrsize%size != 0)
base += size - ptrsize%size;
for (i = 0; i < rows; i++)
ptr[i] = base + i*rowsize;
}
void *malloc2d(size_t rows, size_t cols, size_t size)
{
size_t total_size = getsize(rows, cols, size);
void *mem = malloc(total_size);
init2d(mem, rows, cols, size);
return mem;
}
void *calloc2d(size_t rows, size_t cols, size_t size)
{
size_t total_size = getsize(rows, cols, size);
void *mem = calloc(total_size, 1U);
init2d(mem, rows, cols, size);
return mem;
}
然后你的代码看起来像这样:
#define MAXWIDTH 100
int num = 3;
test t;
t.num = num;
/* dynamically allocate the memory for t.name */
t.names = calloc2d(t.num, MAXWIDTH, sizeof(char));
/* do your thing here */
const char *tmp = "test";
strcpy(t.names[0], tmp);
strcat(t.names[0], "appendtext"); /* just be careful not to go past MAXWIDTH */
strcpy(t.names[1], tmp);
strcpy(t.names[2], "something else");
/* free the memory that was allocated when done */
free(t.names);
t.names = NULL;
关于C:如何在结构中存储二维字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5123980/