gpt4 book ai didi

c - 使用指针作为数组?

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

所以我有这段代码

int *userInput; //array place holder
//int max; //Max variable for later use in comparisons
int start = 0; //inital starting point value for loops
int endUserInput; //used to find the total number input




printf("You may enter up to a max of 50 integer values, Please enter the first value: ");

//loop collects the user inputs
/* Using a while loop to check for data to be true in what is entered
to spot when the data becomes false when a letter is entered*/
while (scanf("%d", &userInput[start]) == 1) {
//If statement entered to catch when the total is met
if (start == 49) {
break;
}
start = start + 1;
//Print statement to let user know what value they are at and how to end input
printf("Enter next value %d or enter C to calculate: ", start + 1);

}

它在我的 MBP 编译器上运行,但在 PC 上的 Dev 上它会因内存错误而崩溃?错误是 int *userInput 声明。在不为数组分配细节的情况下,我该怎么做才能解决这个问题。

最佳答案

您正在覆盖未分配的内存,其中可能包含非常重要的内容。您需要分配足够的空间来存储 50 个整数并将 userInput 设置为该值。

int *userInput = malloc(sizeof(*userInput)*50);

不要忘记在使用完后调用 free(userInput)

关于c - 使用指针作为数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22084502/

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