我想要一个2d字符数组,当我不使用结构时,我可以遍历数组并打印出字符串。但是,如果我将2d char数组分配给struct成员,我无法访问该数组,为什么?
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;
答案 0 :(得分:2)
你真的应该在这里动态分配你的数组。你想在这里做的事情有很多问题。
实际上,我有一些实用程序函数可以使用单个分配动态分配二维数组。您可以在代码中使用它们。
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;
答案 1 :(得分:1)
在尝试访问数组之前,不应该为数组分配内存吗?
编辑:
names[2] = "something else"
让你脱离索引..你只声明了一个2字符串数组。
既然你说内存被自动声明为常量,那么你应该注意到:
char *tmp;
tmp = "test";
strcpy(tmp, "something"); //something is longer than test