简体   繁体   中英

reading an input(int) and storing it into an array with malloc and realloc

I'm trying to read ints from stdin, but i don't know the length. I tried this but I have no idea why it doesn't work

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

int main()
{
    int *arr = (int *) malloc(sizeof(int));


    int sizeCounter = 0;
    int tmp = 0;
    while(scanf("%d", &tmp) != EOF)
    {   

        arr = (int *) realloc(arr, sizeof(arr)+sizeof(int));
        arr[sizeCounter] = tmp;     
        sizeCounter++;          

    }
}

Error - realloc(): invalid pointer: 0xb76d8000 *

This line is wrong.

    arr = (int *) realloc(arr, sizeof(arr)+sizeof(int));

sizeof(arr)+sizeof(int) is a constant. It is equal to sizeof(int*)+sizeof(int) .

What you need is:

    arr = (int *) realloc(arr, (sizeCounter+1)*sizeof(int));

R Sahu gave the correct answer on why this is not working.

However, seeing your code I cannot help but cringe at the inefficiency of reallocating the memory block on each read. If you want to use a memory block/dynamic array to store the read-in integers, allocate a reasonable amount of memory (this depends on how much input you expect in a typical case and is entirely application specific) to start. Then reallocate the block when it is full. Memory allocation is a very expensive operation and reallocating the block on each read is incredibly wasteful and therefore should never be done.

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