不明白为什么我得到异常抛出错误

  • 本文关键字:异常 出错 错误 明白 c
  • 更新时间 :
  • 英文 :

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int* createArr(int len);
/*
Convantional problem in Code:
There is no descreption to main.
Bugs:
1.line 32 - in scanf there is no & to the variable that'll stor the user input, scanf("%d,size") -> scanf("%d,&size")
2.line 33 - should be getchar(); and then the rest of the code. 
3.In createArr:
    1)line 48 - the parameters that malloc is getting is wrong - the function needs the total amout of bytes, so for int you need to mul the inputed amount by 4
      and the casting is to int and not a int type pointer. int * pArr = (int*)malloc(size) -> int * pArr = (int)malloc(sizeof(int) * size).
    2)line - in scanf() the storing variable is wrong,the storing variable should be the index in the array, scanf("%d",size) -> scanf("%d",*(arr + i)). (Another thing is that you didnt use & for the integer size)
    3)line 54 - should be getchar() after scanf() and then the rest of the code.
    4)line 57 - using the function free() in the wrong way, the function is realising spesific places in the computer memory and the function is used only when you dont need the memory the you allocated your self to the array.

*/
int main(void)
{
    int size = 0;
    int* pArr = 0;
    printf("Enter a number of cells: ");
    scanf("%d",&size);
    getchar();
    pArr = createArr(size);
    printf("The array is at address %p: ", pArr);
    free(pArr);
    getchar();
    return 0;
}
/*
Function creates an array
input: number of cells in the array
output: pointer to the new array
*/
int* createArr(int size)
{
    int * pArr = (int)malloc(sizeof(int) * size);
    int i = 0;
    for(i = 0; i < size; i++)
    {
        printf("Please enter a number for index %d: ",i);
        scanf("%d",*(pArr + i));
        getchar();
    }
    return pArr;
}

代码是我在课堂上得到的家庭作业,我需要在代码中找到错误修复它们并解释它们。

问题:当 im 执行代码时,im 收到以下错误:在 q5 中0x0FE98E2E (ucrtbased.dll( 引发异常.exe: 0xC0000005:发生访问冲突写入位置0xCDCDCDCD。

使用断点后,我发现问题出现在代码的这一部分:

int i = 0;
for(i = 0; i < size; i++)
{
    printf("Please enter a number for index %d: ",i);
    scanf("%d",*(pArr + i));
    getchar();
}

在函数中创建Arr

我想了解为什么我会收到此错误,以便我可以修复它。

这里有两个问题:

触发您提到的错误的那个在这里:

scanf("%d",*(pArr + i));

对于scanf,您需要提供指向希望输入进入的变量的指针,但您提供了变量的值。

你需要

scanf("%d", pArr + i);

scanf("%d", &pArr[i]);

第二个问题比较微妙:

在这一行中,您将 malloc 的结果强制转换为 int ,但您可能希望将其转换为 int*(malloc返回一个指针(。

int * pArr = (int)malloc(sizeof(int) * size);

但无论如何,在 C 中你不会从 malloc 中转换返回值,只需编写:

int * pArr = malloc(sizeof(int) * size);

但最佳做法是编写:

int * pArr = malloc(sizeof *pArr * size);

这样,sizeof的参数总是与类型的大小匹配(int这里(。

如果您不使用难以阅读的指针算术语法*(pArr + i)而是使用索引pArr[i],那么该错误更容易发现。

SCANF 需要一个地址,但您传递了一个值。将代码更改为以下内容:

scanf("%d", &pArr[i]);

也永远不要施放 malloc 的结果,因为这会隐藏错误。在您的情况下,它创建了一个新错误,因为您不小心投射到 int .编译器必须在此处提供诊断消息。

拖曳重大错误。

malloc 返回的结果是一个void*不要将其强制转换为int(不要强制转换它或至少将其转换为int*(。

*(pArr + i)这是取消引用指针。 scanf期待一个指针,在您的情况下,您正在给出一个int.您可以删除"*"和括号,甚至更好的是,使用&pArr[i]

相关内容

最新更新