简体   繁体   中英

Pointer value changing unexpectedly when passed to function

So I'm trying to implement an arrayList in C but I'm getting some errors. When i is 4 in the for loop in the main function, insertArrayList is called to insert the number 4. After inserting 4 into my contents array, the first 5 elements of my array are 0,1,2,3,4. But then after my call to PrintArray, the first element in my array changes 6422016. I can not figure out why this is happening. Any help would be appreciated. Thanks.

#include <stdlib.h>
#include <math.h>

struct ArrayList{
    int numItemsInserted;
    int size;
    int *contents;
};

void initializeArrayList(struct ArrayList *a, int size){
    (*a).numItemsInserted= floor(size / 2);
    (*a).size = size;
    (*a).contents = malloc(sizeof(int) * size);
}

void PrintArray(struct ArrayList *a){
    for (int i = 0 ; i < (*a).numItemsInserted; i++){
        printf("%i ", (*a).contents[i]);
    }
    printf("\n");
}
struct ArrayList insertArrayList(struct ArrayList *a, int num){
    if((*a).numItemsInserted == (*a).size){
        int newContents[(*a).size * 2];
        for (int i = 0; i < (*a).size; i++){
            newContents[i] = (*a).contents[i];
        }


        (*a).contents = newContents;
        (*a).size *= 2;

    }
    (*a).contents[(*a).numItemsInserted] = num;
    (*a).numItemsInserted += 1;
    PrintArray(a);
}


int main() {
    struct ArrayList a1;
    initializeArrayList(&a1, 1);
    for (int i =0; i < 10; i ++){
        if (i == 1){
            printf("a");

        }
        insertArrayList(&a1, i);
    }

    return 0;
}```

(*a).contents = newContents; assigns the address of (the first element of) the local array newContents to (*a).contents . Once ArrayList returns, newContents ceases to exist in the C model of computing.

A proper way to grow an array is to use realloc to request a larger allocation. First, request more memory:

int *NewContents = realloc(a->contents, NumberOfElementsDesired * sizeof *NewContents);

Then, test whether the request succeeded or failed:

if (NewContents == NULL)
{
    fprintf(stderr, "Error, failed to allocate memory.\n");
    exit(EXIT_FAILURE);
}

Then, record the address of the new memory:

a->contents = NewContents;

After that, fill in the new items.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM