-1

I am reading two values from a text file and saving them into an array, lets call it array1. Now, is it possible to initialize a 2D array using the elements of arrays1 ? (i.e. char array2 [array[0]][array[1]]; )

I already tried this and the program started acting weird. I also tried moving the values of the elements in an integer and then use the integer as the array size. This method did not work either.

Any suggestions of how I can implement this please?

5
  • 1
    You can initialize arrays to variable sizes in functions because functions allocate the memory on the stack. However if things are acting weird, there might be a problem with pointers or going out of bounds. Need to see the code. Question is too vague and general Commented Apr 4, 2015 at 21:07
  • You haven't shown the faulty code. Commented Apr 4, 2015 at 21:10
  • possible duplicate of Dynamic 2D array allocation in C family Commented Apr 4, 2015 at 21:15
  • It is possible if C99 or later. Commented Apr 4, 2015 at 21:30
  • ideone.com/9glt6p Commented Apr 4, 2015 at 22:03

1 Answer 1

0

A 2D array can be initialized using the array initialization syntax only if second the dimension of the array is known at compile time.

Example:

// Create a 1 x 2 array.
char array2[][2] = {{array[0], array[1]}};

// Create a 2 x 2 array.
// Only array2[1][0] and array2[1][0] are initialized
// from array. Rest are zero initialized.
char array2[][2] = {{array[0]}, {array[1]}};

// Create a 3 x 2 array.
// Only array2[0][1] and array2[0][1] are initialized
// from array. Rest are zero initialized.
char array2[3][2] = {{array[0], array[1]}};
Sign up to request clarification or add additional context in comments.

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.