2D阵列和双指针用C

问题描述:

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); 
} 
+0

@lostinpointers:请不要简单地转发同样的问题。如果你认为这是一个不同的问题,你应该(1)承认先前的问题,(2)说明你从那时起做了什么,(3)具体说明这个问题是如何新的。 – dmckee 2011-06-06 18:52:00

+1

行:'ptr = abc;'(从下到上第三个)给我一个错误: '警告:从不兼容的指针类型赋值。 – 2011-06-06 18:52:06

+0

值得指出的是,虽然你可以用'foo [] []'来访问存储在'char **'中的数据,但它与* char [] []'不是同一件事物。 – dmckee 2011-06-06 18:53:52

如果你有一个二维数组(像你这样做ABC),你只提领的尺寸之一,你不能诚实指望它解析为一个字符。它将解析为该行字符的地址。

char abc[4][5] = { "123", "456", "789" }; 

for (i = 0; i < 3; i++) 
{ 
    printf("My value is %s\n", abc[i]); 
} 

是没有意义的。你需要更多的东西:

char abc[4][5] = { "123", "456", "789" }; 

for (i = 0; i < 3; i++) 
{ 
    for (j = 0; j < 4; j++) 
    { 
    printf("My value is %c\n", abc[i][j]); 
    } 
}