【问题标题】:C program crash after first scanf第一次scanf后C程序崩溃
【发布时间】:2016-04-09 22:30:20
【问题描述】:

这个函数导致我的程序崩溃:

void input_data(int** data, int* data_size)
{
    int i;
    char c;

    //input with error handling
    do
    {
        printf("Write, how many integers you want to input: ");
    }
    while (((scanf("%d%c", data_size, &c) != 2 || c != '\n') && clear_stdin()));

    //memory reallocation
    *data = (int *) realloc(*data, *data_size * sizeof(**data));

    printf("\nInput %d integers\n", *data_size);

    for (i = 0; i < *data_size; i++)
    {
        while ((scanf("%d%c", data[i], &c) != 2 || c != '\n') && clear_stdin());
    }
}

在我的 main() 中,我得到了

int* numbers = (int *) malloc(1 * sizeof(*numbers));
int input_size;
input_data(&numbers, &input_size);

我的程序在第一次输入整数后崩溃,我相信这是由 scanf 引起的,但我不知道为什么。 如果您需要,我可以提供我的程序的完整源代码。

【问题讨论】:

  • 考虑共享堆栈跟踪!
  • scanf("%d%c", data[i], &amp;c) --> scanf("%d%c", &amp;(*data)[i], &amp;c)scanf("%d%c", *data + i, &amp;c)
  • “我可以提供我的程序的完整源代码” - 是的,请 - 包含该代码的 ideone 或其他在线编译器的链接会很有用

标签: c scanf realloc


【解决方案1】:

这不是你所期望的:

scanf("%d%c", data[i], &c)

data[i] 不是数组中第 i' 个元素的地址。此表达式转换为 *(data + i)。该表达式实际上将data 视为int * 的数组,但data 是指向int * 变量的指针,因此这会导致未定义的行为。

您想先取消引用data,然后获取数组元素。所以你想要的表达式是(*data + i),或者等价的&amp;((*data)[i])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多