【问题标题】:C: How to store 2d Char array in a struct?C:如何将二维字符数组存储在结构中?
【发布时间】:2011-07-04 16:25:06
【问题描述】:

我想要一个二维字符数组,当我不使用结构时,我可以遍历数组并打印出字符串。但是,如果我将 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;

【问题讨论】:

  • 你能提供你得到的确切错误吗?

标签: c arrays struct char malloc


【解决方案1】:

你真的应该在这里动态分配你的数组。您在这里尝试做的事情有很多问题。

  • 您的数组已初始化为指向堆栈上的内存。
  • 您正在存储指向字符串文字的指针并尝试修改它们。
  • 您正在访问超出数组边界的内存。
  • 以及介于两者之间的一切。

碰巧我有一些实用函数可以使用单个分配动态分配二维数组。随意在您的代码中使用它们。

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;

【讨论】:

    【解决方案2】:

    您不应该在尝试访问它们之前为您的数组分配内存吗?

    编辑:

    names[2] = "something else" 让你脱离索引。你只声明了一个 2 字符串数组。

    既然你说内存是自动声明为常量,那你应该注意到了:

    char *tmp;
    tmp = "test";
    
    strcpy(tmp, "something"); //something is longer than test
    

    【讨论】:

    • 据我所知,在执行 char *s = "something" 时,内存会自动声明为常量
    • 问题不是更长。这是通过修改支持字符串文字的数组调用的未定义行为。在这种情况下,未定义意味着段错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-06
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 1970-01-01
    相关资源
    最近更新 更多