Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to use Direct initialization of a 2d array, which is dynamically created using given function.

int** allocate2D(int m, int n) {
    int **a = (int **)malloc(m * sizeof(int *) + (m * n * sizeof(int)));
    int *mem = (int *)(a + m);
    for(int i = 0; i < m; i++)
        a[i] = mem + (i * n);
    return a;
}

I have a function that allocates the memory and returns the base address and I have random list of numbers that should be assigned to that dynamically allocated memory.

For Example, here in this, I have assigned directly,

int a_11[2][2] = { a[1][1], a[1][2], a[2][1], a[2][2]};

but I want to assign these values like

int **a_11 = allocate2D(n, n);
a_11 = { a[1][1], a[1][2], a[2][1], a[2][2]};

but it's giving an error. How can I solve this? Is there any explicit way to assign values?

I just started learning C and it would be very kind if your help would be descriptive enough for me to understand and in the simplest form.
Thank You :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
292 views
Welcome To Ask or Share your Answers For Others

1 Answer

等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...