4

I want to make a dynamic 2D array that stores strings in this fashion -

a[0][0] = "element 1"
a[0][1] = "element 2"

But I have no idea how to go about doing this.

1

3 Answers 3

4

Create an array of string pointers. Each element in your 2D array will then point to the string, rather than holding the string itself

quick and dirty example :) (Should realy init the elements)

#include <stdio.h>

int main(void)
{
  char * strs[1][3];   // Define an array of character pointers 1x3

  char *a = "string 1";
  char *b = "string 2";
  char *c = "string 3";

  strs[0][0] = a;
  strs[0][1] = b;
  strs[0][2] = c;

  printf("String in 0 1 is : %s\n", strs[0][1]);
  printf("String in 0 0 is : %s\n", strs[0][0]);
  printf("String in 0 2 is : %s\n", strs[0][2]);

  return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

2

A two dimensional array of strings in c can be represented by a three dimensional array of character pointers.

// allocate space for the "string" pointers 
int size  = height + (height * length);

char*** a = malloc (size * sizeof (char*));

//setup the array
for (i= 0; i< height; i++)
{
    a [i] = a + (height + (length * i));
}

Now a [x][y] resolves to char *. You can assign string literals to it or allocate an array of chars to hold dynamic data.

Comments

2

use this code

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
  char * strs[0][3];   

  strs[0][0] = "string 1";
  strs[0][1] = "string 2";
  strs[0][2] = "string 3";

  printf("String in 0 0 is : %s\n", strs[0][0]);
  printf("String in 0 1 is : %s\n", strs[0][1]);
  printf("String in 0 2 is : %s\n", strs[0][2]);
  system("pause");
  return 0;
}

or if you want variable number of rows :

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
  char * strs[][3] = {
      {"string 11", "string 12", "string 13"},
      {"string 21", "string 22", "string 23"}
      };  

    printf("String in 0 0 is : %s\n", strs[0][0]);
    printf("String in 0 1 is : %s\n", strs[0][1]);
    printf("String in 0 2 is : %s\n", strs[0][2]);

    printf("String in 1 0 is : %s\n", strs[1][0]);
    printf("String in 1 1 is : %s\n", strs[1][1]);
    printf("String in 1 2 is : %s\n", strs[1][2]);
    system("pause");
    return 0;
}

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.