Re: difference between string literal declarations
- From: David R Tribble <david@xxxxxxxxxxx>
- Date: Mon, 17 Aug 2009 09:51:11 -0700 (PDT)
Daniel Molina Wegener wrote:
What is main difference between:
char *s = "hello world";
and:
char t[] = "hello world";
As answered previously, the first declaration 's' is a pointer
and the second declaration (renamed to 't' for clarity) is
an array of characters. Both behave as null-terminated strings.
What is optimal declaration for literal strings according
to the C99 standard semantics?
The only optimizations to consider depend entirely on the
compiler and machine you are using. However, some things
to consider:
1. The definition for 's' allocates a pointer in addition to the
storage of the character string "hello, world". The definition of
't' only allocates the string characters. Your memory requirements
for 's' are slightly higher.
2. There may be differences in access times between 's' and 't'
because of paging. In principle, accessing 's' requires accessing
the pointer variable 's' and then using its value to access the
character of the string. Accessing the characters in 't' might be
more efficient since (on most systems) the address of 't' is a
runtime constant (computed by the linker) instead of a variable,
which could mean one less memory access.
3. Optimizing compilers might eliminate these differences, so
that using 's' or 't' yields exactly the same performance.
These issues are not addressed by the ISO C standard, though,
because it deals with an idealized abstract machine that executes
C code, which may not reflect your actual implementation.
FWIW, I tend to prefer the second form ('t') for allocating large
amounts of string constants (or arrays of strings) to avoid the
overhead of the extra pointers. But that's based on my experience
with the particular compilers I use. Your mileage may vary.
Unless you're constrained on memory (e.g., embedded applications),
the time/space differences are probably not noticeable enough
to matter.
-drt
.
- Follow-Ups:
- Re: difference between string literal declarations
- From: Keith Thompson
- Re: difference between string literal declarations
- From: Eric Sosman
- Re: difference between string literal declarations
- From: Lew Pitcher
- Re: difference between string literal declarations
- References:
- difference between string literal declarations
- From: Daniel Molina Wegener
- difference between string literal declarations
- Prev by Date: Re: negative zero and i-d result
- Next by Date: Re: difference between string literal declarations
- Previous by thread: Re: difference between string literal declarations
- Next by thread: Re: difference between string literal declarations
- Index(es):
Relevant Pages
|