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;
}
5
  • 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 Commented Apr 27, 2015 at 3:33
  • It depends on what you want to do. It's basically the same as with one dimensional arrays. See here and here. Commented Apr 27, 2015 at 3:38
  • 2
    Some people will insist that it's more correct to use the const keyword, i.e. const char *bdato[rows][colu]={ Commented Apr 27, 2015 at 3: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: Commented Apr 27, 2015 at 3:49
  • For your code you don't even need to include string.h... Commented Apr 27, 2015 at 6:55

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

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.