Talk About Network

Google


Register and Login
Nick
Password
Register create new account Sign up is FREE and you can post replies, new topics, bookmark posts and more!
Recover lost password


Programming > C Moderated > Re: Length of S...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 3 of 3 Topic 1092 of 1134
Post > Topic >>

Re: Length of Strings in an Arrray (at compile-time)

by Jack Klein <jackklein@[EMAIL PROTECTED] > May 7, 2008 at 01:39 AM

On Mon, 5 May 2008 16:01:45 -0500 (CDT), "Paul" <-@[EMAIL PROTECTED]
> wrote
in comp.lang.c.moderated:

> How do I find the length of strings within an array at compile time?
> 
> The following is not safe:
> 
> const char* MyStrings[] =
> {
>     "one",
>     "two",
>     "three",
>     "end marker"
> }
> 
> #define StringLength(index) MyStrings[index+1] - MyStrings[index]
> 
> Since the strings may not be placed consecutively, or in order, within
> memory.
> 
> Also
> 
> #define String1 "one"
> #define String2 "two"
> #define String3 "three"
> 
> const char* MyStrings[] =
> {
>     String1,
>     String2,
>     String3
> }
> 
> int StringLengths[] =
  ^^^ much better size_t, that's what it's for.

> {
>     size(String1),
>     size(String2),
>     size(String3)
> }
> is a bit too ***bersome.
> 
> Any better suggestions?

static const char mys1 [] = "one";
static const char mys2 [] = "two";
static const char mys3 [] = "three";
static const char mys4 [] = "eleventy-two";
static const char mys5 [] = "end marker";

const char* MyStrings [] =
{
   mys1, mys2, mys3, mys4, mys5
};

const size_t MySizes [] =
{
   sizeof mys1, sizeof mys2, sizeof mys3, sizeof mys4, sizeof mys5
};

If you want the equivalent of what strlen() would return, subtract 1
from the sizeof value, either in the array initialization or when
using the values.

-- 
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.para****ft.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html
-- 
comp.lang.c.moderated - moderation address: clcm@[EMAIL PROTECTED]
 -- you must
have an appropriate newsgroups line in your header for your mail to be
seen,
or the newsgroup name in square brackets in the subject line.  Sorry.
 




 3 Posts in Topic:
Length of Strings in an Arrray (at compile-time)
"Paul" <-@[E  2008-05-05 16:01:45 
Re: Length of Strings in an Arrray (at compile-time)
=?ISO-8859-1?Q?Hans-Bernh  2008-05-07 01:38:05 
Re: Length of Strings in an Arrray (at compile-time)
Jack Klein <jackklein@  2008-05-07 01:39:25 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
tan12V112 Fri Jul 25 15:54:00 CDT 2008.