打印数组元素

时间:2021-03-23 18:27:28

标签: arrays c

我有以下代码:

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

struct sArray {
    int *arr;
    int index; // ultimo indice riempito 
    int prev_index; // penultimo indice
    int lenght;
};

typedef struct sArray arr;  // structArray with type arr

void init(arr *a, int initSize) {
    a->arr = malloc(initSize * sizeof(int));
    a->lenght = initSize;
    a->index = 0;
    a->prev_index = 0;
}

void insert(arr *a, int value) {
    int index = a->index;
    int length = a->lenght;
    int prev_index = a->prev_index;
    if (index < length) {
        a->arr[index] = value;
    } else {
        a->arr = malloc(1 * sizeof(int));
        a->arr[index] = value;
        a->lenght += 1;
    }
    a->index += 1;
    if (index > 0){
       a->prev_index += 1; 
    };
}

int main(void) {
    arr a;

    // init array with 10 elements
    init(&a, 10);

    // try to add 20 elements
    for (int i = 0; i < 20; i++) {
        insert(&a, i);
        printf("Valore: %d\n", a.arr[i]);
    }
    printf("Lenght a: %d\n", a.lenght);
    // the left operand of -> must be a pointer;
    // the . operator is used if it is not a pointer

    for (int i = 0; i < 20; i++) { // PROBLEM HERE
        printf("Valore: %d\n", a.arr[i]);
    }

    return 0;
}

我不明白为什么我不能在 a.arr[i] 函数的第二个 for 循环内打印数组的元素 (main)。特别是,元素在第一个循环中正确打印,其中有一个 insert() 函数,但在第二个循环中元素完全随机打印,而我希望元素应该来自 019

1 个答案:

答案 0 :(得分:2)

您在 insert() 中的分配有误。

        a->arr = malloc(1 * sizeof(int));

只为一个新元素分配一个缓冲区。

而不是这个,你必须

  • 分配足够的大小(可以容纳 a->lenght + 1 int 个)
  • 存储之前添加的数据

您可以通过 realloc() 这样做:

        a->arr = realloc(a->arr, (a->lenght + 1) * sizeof(int));