1

How to fill a dynamically allocated 2D array? for example:

#define n 100
char **array;
array = new char*[n];
for(int i=0; i<n; i++)
{
    array[i] = new char[n];
}

How to fill this 2D array with * value?

3
  • You can always use a loop inside a loop. Commented Aug 15, 2020 at 9:35
  • 1
    you do not have a 2D array but an array of string, this is not the same thing Commented Aug 15, 2020 at 9:43
  • @bruno is right. array of string or vector of string. Commented Aug 15, 2020 at 9:50

3 Answers 3

1
  • Your code came very close to achieve what you wanted.
  • Just like you wrote, array[i] is an n length character array.
  • To write '*' to its j-th entry all you have to do is:
for (int i=0;i<n;i++)
{
    for (int j=0;j<n;j++)
    {
        array[i][j] = '*';
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

'a' is not '*'as expected by the OP, and why not using memset ?
@bruno I prefer a double nested loop, but of course there are other ways too ...
memset is faster, may be propose both ?
You must also warn the OP array is not a 2D array
1

Both the answers you got so far are correct. You can see it as an 2D array or as an array of strings. You can store data on it char by char or directly writing a string. Maybe using constants instead of define would be a better practise.

const int n = 100;
char **array;
array = (char **)malloc(sizeof(char *) * n);

bool storeString = true;

for(int i=0; i<n; i++)
{
    array[i] = (char *)malloc(sizeof(char) * n);
    
    if(storeString)
        array[i] = "Im striiinging in the rain";
    
    else
        for(int j = 0; j < n-1; j++)
        {
            array[i][j] = '0';
        }
}

I'm using C type memory allocation but that shouldn't be an issue, I just don't remember how to do it precisely on C++ type, just import <cstdlib>

Comments

0

As @Bruno mentioned in comments, it is not 2D array but an array of strings. You can directly store the string with 1 loop. Either assign string by using = operator, or use memset function.

    char **array;
    array = new char*[n];
    for(int i=0; i<n; i++)
    {
        array[i] = "whatever";
    }

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.