gpt4 book ai didi

在堆中分配内存以保存指向字符的指针数组时,代码崩溃

转载 作者:行者123 更新时间:2023-11-30 21:07:00 25 4
gpt4 key购买 nike

#define MAX_STRING_SIZE 256

#include <stdio.h>
#include <stdlib.h>


static void getList(char ***pppclist)
{
int n=0;
int i =0;

printf("Enter the number of items in the List: ");
scanf("%d", &n);

//Array of Pointers to characters
*pppclist = (char **)malloc(n * sizeof(char *)); //X50, x51, x52

for( i=0; i<=n; i++)
{
*(pppclist[i]) = (char *)malloc(MAX_STRING_SIZE * sizeof(char)); //*X50 = X100

printf("Enter the %d items in the List: ", i);
scanf("%s", pppclist[i]);
}

}

main(int argc, char *argv[])
{


char **ppclist = NULL; //array of Pointer to Pointer to character

getList(&ppclist); //X1

printf("The Entered List is:%s", ppclist);



for(;;);
}

大家好...请帮忙调试上面程序中的错误。我想在 get list 函数中获取一个字符串列表,并将其打印在 main 堆栈中。我已经在堆中分配了内存,用于保存指向字符和字符的指针数组。出了问题。有人可以帮助我吗?PS:不要标记为重复

最佳答案

首先,在getList函数中,当要访问数组中的第n项时,必须将*pppclist括在括号内,而不是*pppclist[i] 因为您应该首先取消引用指针,然后再访问第 n 项。

接下来,当您分配数组时,您应该再分配一项并将其设置为NULL。这对于稍后浏览您的数组很有用。

这是更正后的代码:

#define MAX_STRING_SIZE 256

#include <stdio.h>
#include <stdlib.h>


static void getList(char ***pppclist)
{
int n=0;
int i =0;

printf("Enter the number of items in the List: ");
scanf("%d", &n);

//Array of Pointers to characters
*pppclist = (char **)malloc((n + 1) * sizeof(char *)); //X50, x51, x52
(*pppclist)[n] = NULL;

for( i=0; i<n; i++)
{
(*pppclist)[i] = (char *)malloc(MAX_STRING_SIZE * sizeof(char)); //*X50 = X100

printf("Enter the %d items in the List: ", i);
scanf("%s", (*pppclist)[i]);
}

}

int main(int argc, char *argv[])
{


char **ppclist = NULL; //array of Pointer to Pointer to character
int index;

getList(&ppclist); //X1

index = 0;
while (ppclist[index]) {
printf("The Entered List is:%s\n", ppclist[index]);
index += 1;
}

return (0);
}

关于在堆中分配内存以保存指向字符的指针数组时,代码崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46113825/

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