如何在函数中为指针数组分配内存和赋值?

时间:2016-11-29 04:30:26

标签: c arrays pointers malloc pointer-to-pointer

我无法弄清楚如何为函数中的指针数组分配内存。在同一个函数中,我试图用另一个数组中的值初始化数组。我已经尝试了一段时间不同的事情,我无法弄清楚我在哪里做,也不需要。

#include <stdio.h>
#include <stdlib.h>

void allocate();
void print();

int main() {

    int array_length = 10;

    int array[array_length] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    int **ascending;
    int **descending;

    allocate(&ascending, &descending, array, array_length);

    print(&ascending, &descending, array, array_length);

}

void allocate(int ***ascending, int ***descending, int array[], int array_length) {

    *ascending = (int **)malloc(array_length * sizeof(int *));
    *descending = (int **)malloc(array_length * sizeof(int *));

    int i, first_index = 0;

    for (i = 0; i < array_length; i++) {

        (*ascending)[i] = &(array[i]);
        (*descending)[i] = &(array[i]);

    }

}

void print(int **ascending, int **descending, int array[], int array_length) {

    int i;

    printf("\nAscending\tOriginal\tDescending\n\n");

    for (i = 0; i < array_length; i++) {

        printf("%d\t\t", ascending[i]);
        printf("%d\t\t", array[i]);
        printf("%d\t\t", descending[i]);

        printf("\n");

    }

    printf("\n");

}

1 个答案:

答案 0 :(得分:0)

首先,无法初始化可变大小的数组。你应该使用MACRO array_length

然后,根据您的函数定义,对print()的调用需要int **作为前两个参数,而不是int ***。将函数调用更改为

  print(ascending, descending, array, array_length);

此外,ascending[i]descending[i]在这种情况下属于int *类型,您还需要一个级别的引用来获取int

那就是说,

void allocate();
void print();

错误的转发声明。您应该使用函数的确切签名进行声明和定义。

示例工作版本可能看起来像

//gcc 4.9.3

#include <stdio.h>
#include <stdlib.h>

#define arraysize 10

void allocate(int ***ascending, int ***descending, int array[], int array_length);
void print(int **ascending, int **descending, int array[], int array_length);

int main(void) {

    int array_length = arraysize;

    int array[arraysize] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    int **ascending;
    int **descending;

    allocate(&ascending, &descending, array, array_length);

    print(ascending, descending, array, array_length);

    return 0;

}

void allocate(int ***ascending, int ***descending, int array[], int array_length) {

    *ascending = (int **)malloc(array_length * sizeof(int *));
    *descending = (int **)malloc(array_length * sizeof(int *));

    int i = 0;//, first_index = 0;

    for (i = 0; i < array_length; i++) {

        (*ascending)[i] = &(array[i]);
        (*descending)[i] = &(array[i]);

    }

}

void print(int **ascending, int **descending, int array[], int array_length) {

    int i;

    printf("\nAscending\tOriginal\tDescending\n\n");

    for (i = 0; i < array_length; i++) {

        printf("%d\t\t", *(ascending[i]));
        printf("%d\t\t", array[i]);
        printf("%d\t\t", *(descending[i]));

        printf("\n");

    }

    printf("\n");

}