Array von Stack auf Heap kopieren



  • Hallo zusammen,

    warum funktioniert folgender Code nicht?

    int main() {
            int i;
            int array[] = {1, 2, 3, 4, 5};
            int count = sizeof(array)/sizeof(int);
            int *a = malloc(count);
            memcpy(a, &array, count);
            for (i = 0; i < count; ++i)
                    printf("%d %d   ", array[i], a[i]);
            printf("\n");
            return 0;
    }
    

    Ausgabe:

    1 1   2 2   3 0   4 135153   5 0
    

    Danke!



  • sizeof(array) = 20 Byte (durch vier geteilt == 5)
    Du reservierst mit malloc 5 Bytes.



  • zuzu12 schrieb:

    warum funktioniert folgender Code nicht?

    Was funktioniert denn an dem Code nicht? 😮



  • 1. da ist kein free ! böse 😡

    int main()
    {
        int i;
        int array[] = {1, 2, 3, 4, 5};
        int count = sizeof(array)/sizeof(int);
        int *a = malloc(count * sizeof(int));   // malloc zählt in bytes !
        memcpy(a, &array, count * sizeof(int)); // memcpy auch
        for (i = 0; i < count; ++i)
            printf("%d %d   ", array[i], a[i]);
        printf("\n");
        free(a);
        return 0;
    }
    

Anmelden zum Antworten