c - 函数中的指针问题

标签 c arrays function pointers dynamic

我需要一些帮助。当我尝试输入数据并将其保存到指针时,我的程序崩溃了。我可以成功地将数据输入到动态数组的第一个元素,我什至可以打印该数据。然而,之后,当我尝试输入第二个元素时,我的程序崩溃了。调试器不会显示任何错误或警告。

#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/

相关文章:

c - Kochan Book : Programming in C i + j - i % j 中的一项练习遇到问题

swift - 函数有返回,返回到哪里?谁拿着它?它能活多久?

sql - 多次执行的 PostgreSQL 触发器函数

node.js - 如何使用sails.js 为模型定义实例方法

c++ - 如何从指针转换为 int?

以优于 O(n^2) 的时间复杂度构造 count 数组

c - C 中的 FORWARD_NULL 与 UNINIT Coverity 错误

PHP/MySQL - 在数据库中存储数组

java - 意外的 NullPointerException 从构造函数分配数组

java - 在 Java 中合并 double 类型数组