0

I would like to now if this is a correct way to declare an array of strings in C, something like this:

#include <stdio.h>
#include <string.h>
#define rows 6
#define colu 2

char* bdato [rows][colu]={/*here using the pointer, I'm not sure*/
{"tc","Torta Cubana  "},
{"th","Torta Huatulco"},
{"tm","Torta Mexicana"},
{"tr","Torta Rusa    "},
{"r ","Refresco      "},
{"a ","Agua sabor    "}};

int impri(){
  int x;
  for (x=0;x<6;x+=1) {
    printf("%s %s \n",bdato[x][0],bdato[x][1]);
  }
  return 0;
}
Lundin
  • 195,001
  • 40
  • 254
  • 396
user2461687
  • 173
  • 1
  • 13
  • I was looking in the internet and read somthing like this is no a proper way to declare it, cause I'm not reading the data only the direction, and it's better using malloc, but Im learning, so I'm not sure. This is my first week I learning programing – user2461687 Apr 27 '15 at 03:33
  • It depends on what you want to do. It's basically the same as with one dimensional arrays. See [here](http://stackoverflow.com/questions/11241014/malloc-or-normal-array-definition) and [here](http://stackoverflow.com/questions/3269627/c-local-array-definition-versus-a-malloc-call?rq=1). – Axalo Apr 27 '15 at 03:38
  • 2
    Some people will insist that it's more correct to use the `const` keyword, i.e. `const char *bdato[rows][colu]={` – user3386109 Apr 27 '15 at 03:47
  • Thanks everybody, I'm this weekend I try to learn everything I could from this language, It's the first I'm trying to learn, I'm so happy C: – user2461687 Apr 27 '15 at 03:49
  • For your code you don't even need to include `string.h`... – urzeit Apr 27 '15 at 06:55

1 Answers1

1

Syntax-wise it is correct. Although whenever you declare a pointer to a string literal, you should declare it as const, because attempting to modify the memory location of a string literal is undefined behavior (a bug).

It may also be wise to make it a habit to name your variables and functions in English, if you would ever need someone else to look at your code (when asking a question on SO for example).

As for whether it is correct to store the data like this or not, it depends on what you are trying to do with the data. If you intend the strings to be related to each other, like in a simple database, it may be better to create a one-dimensional arrays of structs, to show that the pair of strings are related:

typedef struct
{
  const char* something;
  const char* something_else;
} my_struct_t;

my_struct_t  data [X] = 
{
  {"tc","Torta Cubana  "},
  {"th","Torta Huatulco"},
  ...
};

(Of course in a real application you'd give the variables more meaningful names)

Lundin
  • 195,001
  • 40
  • 254
  • 396