我需要一些帮助。当我尝试输入数据并将其保存到指针时,我的程序崩溃了。我可以成功地将数据输入到动态数组的第一个元素,我什至可以打印该数据。然而,之后,当我尝试输入第二个元素时,我的程序崩溃了。调试器不会显示任何错误或警告。
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
static const char SPRTR[] = "//---------------------------------------------------------------------------//";
static const char ERR_MSG[] = "ERROR! Try again.";
void create_array(int **data, int *n, int *arr_max)
{
int i;
int err;
char temp;
do
{
err = 0;
printf("\nMaximum number of array elements: ");
if (((scanf("%d", arr_max)) < 1) || (*arr_max <= 0))
{
printf("%s\n", ERR_MSG);
err = 1;
}
printf("\n%s\n", SPRTR);
while ((temp = getchar()) != '\n' && temp != EOF);
} while (err != 0);
do
{
err = 0;
printf("\nNumber of array elements (max. %d): ", *arr_max);
if (((scanf("%d", n)) < 1) || (*n > *arr_max) || (*n <= 0))
{
printf("%s\n", ERR_MSG);
err = 1;
}
printf("\n%s\n", SPRTR);
while ((temp = getchar()) != '\n' && temp != EOF);
} while (err != 0);
*data = (int *) malloc(sizeof(int) * (*n));
for (i = 0; i < *n; i++)
{
do
{
err = 0;
printf("\nValue of %d array element: ", i);
if (((scanf("%d", *(data + i))) < 1) || (*(*(data + i)) < 0))
{
printf("%s\n", ERR_MSG);
printf("\n%s\n", SPRTR);
err = 1;
}
while ((temp = getchar()) != '\n' && temp != EOF);
} while (err != 0);
}
}
int main()
{
int n;
int arr_max;
int *data;
create_array(&data, &n, &arr_max);
return 0;
}
最佳答案
你的编译器(还有我的编译器)没有发现错误,因为你使用了正确的类型,但此语句中有两个错误(实际上是相同错误的两倍):
if (((scanf("%d", *(data + i))) < 1) || (*(*(data + i)) < 0))
data
是指向 int *
的指针(地址),其中保存 malloc
的结果。
因此,您可以访问的 int
是 (*data)[i]
,它们的地址是 *data + i
。所以这一行应该替换为:
if (((scanf("%d", *data + i)) < 1) || ((*data)[i] < 0))
至少对我有用。
关于c - 函数中的指针问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36522037/