M Luffy
M Luffy

Reputation: 53

Multidimensional array of strings in C

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.

Upvotes: 4

Views: 14707

Answers (3)

saeed_m
saeed_m

Reputation: 175

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;
}

Upvotes: 2

Pemdas
Pemdas

Reputation: 543

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.

Upvotes: 2

Graeme
Graeme

Reputation: 1698

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;
}

Upvotes: 4

Related Questions