Possible Duplicate:
2D arrays and pointers.
(This is not a duplicate of that question. In that question the OP was correctly passing a pointer-to-a-pointer, and the problem was with dereferencing an uninitialised pointer. This question is about passing trying to pass a pointer-to-array to a function that expects a pointer-to-a-pointer.)2D陣列和雙指針用C
對於一些現有的代碼兼容的,我需要一個二維數組傳遞給一個函數作爲指針到一個指針。我簡化了下面的代碼。在功能printvalues
中打印出結構中的第一個值並newptr
,即「我的值是123並在結構123中」後,我得到一個seg。故障。我錯過了什麼?
#include <stdio.h>
#include <stdlib.h>
typedef struct mystruct
{
char mychar [4][5];
} mystruct_t;
void printvalues(char** newptr)
{
int i;
mystruct_t * fd = (mystruct_t*)malloc(sizeof(*fd));
for (i = 0; i < 3; i++)
{
strcpy(fd->mychar[i], newptr[i]);
printf("My value is %s and in struct %s\n", newptr[i], fd->mychar[i]);
}
}
int main(int argc, char **argv)
{
int i;
char *ptr = malloc(4*sizeof(char));
char **pptr = (char **) malloc(5*sizeof(char *));
char abc[4][5] = { "123", "456", "789" };
for (i = 0; i < 3; i++)
{
printf("My value is %s\n", abc[i]);
}
ptr = abc;
printvalues(&ptr);
}
@lostinpointers:請不要簡單地轉發同樣的問題。如果你認爲這是一個不同的問題,你應該(1)承認先前的問題,(2)說明你從那時起做了什麼,(3)具體說明這個問題是如何新的。 – dmckee 2011-06-06 18:52:00
行:'ptr = abc;'(從下到上第三個)給我一個錯誤: '警告:從不兼容的指針類型賦值。 – 2011-06-06 18:52:06
值得指出的是,雖然你可以用'foo [] []'來訪問存儲在'char **'中的數據,但它與* char [] []'不是同一件事物。 – dmckee 2011-06-06 18:53:52