Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Array of strings

Tags:

arrays

c

string

I want to create an array of strings. The problem is that I want to be able to access the length of each string statically. I tried this:

char *a[] = {"foo", "foobar"};

The array works fine except that I want to know the length of each element statically. I can't use sizeof(a[0]) because it returns the size of the char * pointer. What I want is the length of the size of the string (4 for a[0], 7 for a[1]).

Is there any way to do this?

like image 230
martinkunev Avatar asked Jun 06 '11 10:06

martinkunev


2 Answers

In short, no, not at compile-time (at least not for an arbitrary number of strings). There are various run-time initialization-like things you can do, as others have pointed out. And there are solutions for a fixed number of strings, as others have pointed out.

The type of a[0] must be the same as that of a[1] (obviously). So sizeof() must evaluate to the same for all values of a[i].

like image 52
Oliver Charlesworth Avatar answered Oct 05 '22 23:10

Oliver Charlesworth


Depending on your definition of "string", a is not an array of strings: it is an array of pointers (I define "string" as array of N characters including a null terminator).

If you want an array of lengths and strings (each capable of holding 999 characters and the null terminator), you may do something like

struct lenstring { size_t len; char data[1000]; };
struct lenstring a[] = {
      { sizeof "foo" - 1, "foo" },
      { sizeof "foobar" - 1, "foobar" },
};

Example with simplifying macro running at ideone

like image 45
pmg Avatar answered Oct 05 '22 23:10

pmg