gpt4 book ai didi

c - C 中的二维数组和双指针

转载 作者:太空宇宙 更新时间:2023-11-04 04:05:42 25 4
gpt4 key购买 nike

<分区>

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.)

为了与某些现有代码兼容,我需要将二维数组作为指向指针的指针传递给函数。我简化了下面的代码。在它打印结构中的第一个值和函数 printvalues 中的 newptr 之后,即“我的值是 123 并且在结构 123 中”,我得到了一个段。过错。我错过了什么?

#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 );
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com