Member Avatar for Rahul47

Which one of the following is the smart, efficient and safe way to declare a string array ? And if you have any other way do suggest.

char a[10]={'A','B','C'};
char a[10]="ABC";
char a[]="ABC";
char *a="ABC";

Please take into consideration the memory allocation and size, memory wasted, methods of retriving data etc.

Recommended Answers

All 4 Replies

The last two would be recommended for not wasting memory. However, there are two questions that determine which you use, or if you want to go with dynamic memory allocation instead:

  1. Do you intend to modify the string?
  2. Do you indend to grow the string or is the size fixed?
Member Avatar for Rahul47

I would prefer a way where memory is not wasted and can be shrinked or expanded according to use.
Is there any way to achieve it ?

malloc, realloc, and free. You have control over how much memory is used at any given point, but that control comes at the cost of managing allocations. The starting point would be:

char *p = malloc(4);
strcpy(p, "ABC");

"I would prefer a way where memory is not wasted and can be shrinked or expanded according to use. Is there any way to achieve it ?"

C was originally developed for the purpose of writing an operating system, so it hasn't got much in the way of fancy stuff - unless you implement it yourself. Languages which let you do things like:

s1 = "abc"
s2 = s1 + "def"

without reserving memory in advance, are doing a lot of memory allocations and releases behind the scenes. There is nothing equivalent to it in C.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.