[英]Crashes after printing elements
我的程序在運行時崩潰並出現以下錯誤:
“在 caza.exe 中的 0x777433D5 (ntdll.dll) 處拋出異常:0xC0000005:訪問沖突讀取位置 0x00000003。”
什么地方出了錯?
我已經在 main 和沒有它的情況下嘗試使用該免費功能,但遇到了同樣的錯誤。
#include <stdio.h>
#include <malloc.h>
typedef struct Dreptunghi
{
int x1, y1, x2, y2;
}Dreptunghi;
void readElements(Dreptunghi* pDreptunghi, int nDreptunghi)
{
for (int i = 0; i < nDreptunghi; ++i)
{
printf("Introduceti valorile pentru dreptunghiul %d \n", i + 1);
scanf("%d %d %d %d",
&pDreptunghi[i].x1,
&pDreptunghi[i].y1,
&pDreptunghi[i].x2,
&pDreptunghi[i].y2);
}
printf("\n");
}
void printElements(Dreptunghi* pDreptunghi, int nDreptunghi)
{
for (int i = 0; i < nDreptunghi; ++i)
{
printf("%d %d %d %d\n",
pDreptunghi[i].x1,
pDreptunghi[i].y1,
pDreptunghi[i].x2,
pDreptunghi[i].y2);
}
}
int main()
{
Dreptunghi* pDreptunghi = NULL;
int n=0;
scanf("%d", &n);
pDreptunghi = (Dreptunghi*)malloc(n+1);
readElements(pDreptunghi, n);
printElements(pDreptunghi, n);
free(pDreptunghi);
return 0;
}
改變
pDreptunghi = (Dreptunghi*)malloc(n+1);
到
pDreptunghi = malloc( (sizeof(*pDreptunghi)*n) + 1);
您沒有在這里分配足夠的內存,您需要分配等於結構大小乘以元素數的內存:
pDreptunghi = (Dreptunghi*)malloc((sizeof(*pDreptunghi)*n)+1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.