函数中指针的问题

时间:2016-04-09 20:04:18

标签: 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;    
}

2 个答案:

答案 0 :(得分:1)

您的编译器(以及我的编译器)找不到错误,因为您使用了正确的类型,但在此语句中有两个错误(实际上是同一错误的两倍):

if (((scanf("%d", *(data + i))) < 1) || (*(*(data + i)) < 0))

dataint *指向malloc结果的指针(地址)。 因此,您可以访问的int(*data)[i],其地址为*data + i。所以这一行应该替换为:

if (((scanf("%d", *data + i)) < 1) || ((*data)[i] < 0))

至少它对我有用。

答案 1 :(得分:0)

问题似乎与行

有关
if (((scanf("%d", *(data + i))) < 1) || (*(*(data + i)) < 0))

您应该取消引用数据以获取指向当前元素的指针 然后添加偏移量,而不是取消引用一个不是指向数组本身的指针的位置。

尝试更换 *(data + i)* data + i,if语句变为:

if (((scanf("%d", *data + i)) < 1) || ((*(*data + i)) < 0))

此外*(* data + i))只是获取数组的偏移量,因此可以用(* data)[i]替换,因此if语句变为:

if (((scanf("%d", *data + i)) < 1) || ((*data)[i] < 0))