|
From: Per W. <pw...@ia...> - 2005-05-02 05:37:51
|
As you notice, it isn't so common to use only string literals, so most
often, dynamic memory is used.
It is a bad idea to create an array where some items are dynamically
allocated followed by a string-copy, and some entries are assignments of
pointers to string literals. The problem will be how to - in a portable
way - know which entries that requires release of dynamic memory.
However, the string literal method do have it's uses. Think for example
keywords for a computer language. All the keywords are know before, and to
speed up operation, the compiler may convert from a list of keywords to a
heavily optimized construct to maximize search time - for example a
perfect hash, where no keyword bin collides with any other keyword bin.
/Per W
On Mon, 2 May 2005, Rafael Charnovscki wrote:
> Per Westermark wrote:
> >
> > However, the above two alternatives may not be combined into:
> > array[1] = malloc(strlen(sentence)+1);
> > array[1] = "sentence";
> > since the second assign will loose the reference to the memory previously
> > allocated.
> >
> Per,
> Thank you for remind us that!
> Do you think it's safe using array[n]="string_literal" inside
> functions?
>
> <snip>
> void foo (char *array[]){
> array[0]="string_literal_1";
> ...
> array[n]="string_literal_n";
> }
> </snip>
>
> IMHO, for C code I'd use dynamic allocation with strings, since
> it's not very common having only string literals. I mean, you don't
> know exactly what you'll have, so you'll have to allocate memory.
>
> Regards,
> Rafael
>
>
> --
> No virus found in this outgoing message.
> Checked by AVG Anti-Virus.
> Version: 7.0.308 / Virus Database: 266.11.0 - Release Date: 29/04/05
>
|