2

I have multi-dimentional arr[3][4].

Then I allocate the memory for newArr[4][3] and change arr's rows into columns and columns into rows saving it to the newArr.

Is it possible to dynamically replace arr with newArr? A little example to clarify the situation:

#include <stdio.h>

void change(int[][4], int, int);

int main()
{
    int arr[][4] = {
        {1, 3, 2, 4},
        {3, 2, 4, 5},
        {9, 3, 2, 1},
    };
    change(arr, 4, 3);
    // now, there should be arr[4][3] = newArr

    getchar();
}

void change(int arr[][4], int cols, int rows)
{
    // create newArr array.
}
1
  • You need to use malloc and create a dynamic array. Commented Jan 19, 2013 at 13:30

2 Answers 2

2

No. You cannot change the size of a true array.

You would need to use dynamic allocation throughout in order to make this work. If you're unclear on how to dynamically allocate a multidimensional array, then please see e.g. http://c-faq.com/aryptr/dynmuldimary.html.

Sign up to request clarification or add additional context in comments.

Comments

0

Sure you can do that but in a slightly different way. With fixed size arrays you cannot do that. You have to do dynamic memory allocation and after that you can use the subscripts as you want. You just need to keep track what subscripts you are using currently to avoid errors.

#include <stdio.h>
#include<string.h>

void change(int **, int, int);

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

    // Fill this memory in whatever way you like. I'm using your previous array
    // to fill arr.
    // Note that initial_arr is not your working arr. Its just for initialization
    int initial_arr[][4] = {
        {1, 3, 2, 4},
        {3, 2, 4, 5},
        {9, 3, 2, 1},
    };

    memcpy(arr, initial_arr, sizeof(int)*3*4);

    // You can access arr in the same way as you do previously. for example 
    // to print arr[1][2] you can write
    // printf("%d", arr[1][2]);


    change(arr, 4, 3);

    // now, simply copy newArr in arr. and you can subscript arr as arr[4][3]
    memcpy(arr, newArr, sizeof(int)*3*4);

    getchar();
}

void change(int **arr, int cols, int rows)
{
    // create newArr array.
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.