2011-02-25 68 views
1

我想要一個2d字符數組,並且當我不使用結構時,我可以遍歷數組並打印出字符串。但是,如果我將2d char數組分配給結構成員,我無法訪問該數組,爲什麼?C:如何將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; 
+0

你能提供你所得到的確切的錯誤? – maerics 2011-02-26 00:33:46

回答

1

在嘗試訪問它們之前不應該爲您的陣列分配內存嗎?

編輯:

names[2] = "something else"讓你出指數的..你宣佈只有2字符串數組。

既然你說該內存爲常數自動聲明,那麼你應該已經注意到:

char *tmp; 
tmp = "test"; 

strcpy(tmp, "something"); //something is longer than test 
+0

是的,他應該:) – svens 2011-02-25 23:59:42

+1

據我所知,內存是在做char * s =「something」時自動聲明的一個常量 – Marcus 2011-02-26 00:09:47

+2

這並不是說它就是更長時間的問題。這是通過修改支持字符串文字的數組調用的未定義行爲。在這種情況下,未定義表示段錯誤。 – aaz 2011-02-26 01:24:58

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; 
相關問題