-4

ive done extensive research and found out that the usual method to initialize a 2D array of chars is

    char *strings[2][50];

But isnt this the same as,

    char strings[2][50]; //not a pointer.

What is the difference between this two lines of code? I know one is pointer and the other is not. However, practically, if you know the size of the array bound ([boundX][boundY]), why would u use a pointer instead? Which code is more practical, and why? Thank you.

EDIT: I am trying to create an array of Strings.

user859385
  • 607
  • 1
  • 6
  • 23

2 Answers2

-1

First expression gives you two pointers to strings of length 50.

The second gives you two strings if length 50.

It all depends what you want to do with these strings: are they known in advanced, fixed or variable, do you want to use character or string operations on them.

If you are using any of the string functions defined in string.h it is better to use the pointer form, as they only take string pointers as arguments.

Arif Burhan
  • 507
  • 4
  • 12
-1

A 2D array of chars (A) is not the same as an array of strings (B).

In the first line: char *strings[2][50]; you will need to allocate the memory for those chars. You only are declaring 2 pointers.

In the second line: char strings[2][50] you are already allocating the memory.

Be careful because in any of those case you will obtain null terminated strings. You will need to properly initialise the values before using them. In addition, in the second case, it is likely that if you make a mistake, the first string can overrun over the second one.

In modern C++, it is preferable to use std::string and std::array. It will make your code safer. I would suggest the following:

First case: std::array< std::array<char, 50>, 2> case1 is and array of arrays

Second case: std::array< std::string, 2> case2 is an array of strings

Juan Leni
  • 6,982
  • 5
  • 55
  • 87