【发布时间】:2015-01-14 10:35:33
【问题描述】:
我在初始化第一个动态指针数组中的值时遇到问题
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char*** GetIndexes()
{
int n = 0;
char ***index;
printf("please insert the number of words you want to add to dictionary\n");
scanf("%d", &n);
index = (char***)calloc(n, sizeof(char));
if (index == NULL)
{
printf("allocation Failed");
return;
}
return index;
}
char** GetDefinitions()
{
int n = 0;
char **definition;
printf("please insert the number of defintions you want to add to the word\n");
scanf("%d", &n);
definition = (char**)calloc(n+1, sizeof(char));
if (definition == NULL)
{
printf("allocation failed");
return;
}
return definition;
}
int main()
{
char *** dptr = GetIndexes();
if (dptr == NULL)
{
printf("memory Allocation failed");
}
int indexcount = sizeof(dptr) / sizeof(char),i;
for (i = 0; i < indexcount; i++)
{
printf("word number %d\n", i + 1);
*dptr[i] = GetDefinitions();
}
printf("%p",dptr);
}
我尝试在 VS2013 中运行调试器,在我输入定义的数量后,我希望它崩溃并显示以下消息:
ConsoleApplication1.exe 中 0x01103FB0 处未处理的异常:0xC0000005:访问冲突写入位置 0x00000000。
我错过了一些东西的分配,但我无法弄清楚我错过了什么,
提前致谢
【问题讨论】:
-
不管什么原因你有
char ***这很可能是个坏主意,而且空间不足,应该是calloc(n, sizeof(char **));甚至calloc(n, sizeof(char *));或calloc(n, sizeof(void *));即n指针,但不是calloc(sizeof(char));。另外,不要投射calloc/malloc,它可能会隐藏程序中的错误。 -
你认为这个
*dptr[i] = GetDefinitions();会做什么? -
你认为
int indexcount = sizeof(dptr) / sizeof(char)的结果是什么?
标签: c pointers dynamic-allocation