Reputation: 1405
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?
Upvotes: 5
Views: 3490
Reputation: 83
Maybe you could start with something like this:
size1 = abs(a[0] - a[1]);
That will give you the difference between the beginning address of the first string and the beginning address of the second string. Therefore the size of the first string.
Then you could use some loop and array to get all the sizes.
It is not statically but maybe you could try it.
Upvotes: 0
Reputation: 363807
The only safe way to know the length of strings statically is to declare them all individually.
char foo[] = "foo";
char foobar[] = "foobar";
char *a[] = {foo, foobar};
You might be able to use a macro to eliminate some of the drudgery, depending on the strings' contents. sizeof(a[0])
will still be sizeof(char*)
, though.
Upvotes: 3
Reputation: 108988
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
Upvotes: 4
Reputation: 1638
if you use char*a[] = {"foo", ...} style of decleration, then you can use strlen(a[0]), strlen(a[1]) etc to find the length of each string.
Upvotes: 0
Reputation: 75439
You can't. sizeof
doesn't return the length of the string, but the size of the array, which in your second case is much larger than the length of the string. You need to use strlen
or, perhaps, a more featured string type:
struct {
size_t len;
char data[];
} string;
But it'd be a bit more complicated to make an array of them in that case.
Upvotes: 1
Reputation: 272687
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]
.
Upvotes: 4
Reputation: 68992
You can't statically initialize a data structure with the result of strlen(), you could loop over your strings and store the string length in an initialization function.
Upvotes: 1