-3
char array[] = "string";

or

char array[10] = "string";

what's the difference in C and which is a better way?

Since both works then why limiting the array by putting a value inside the []

Never mind, thanks

Sumon
  • 45
  • 1
  • 3
  • 1
    I think the question is more, why didn't you do any research?! This question was asked many times before! – Rizier123 Jan 16 '15 at 18:00
  • And what have you found? If you didn't found anything, i think you want to learn how to use google – Rizier123 Jan 16 '15 at 18:07
  • [How to initialize an array in C](http://stackoverflow.com/questions/201101/how-to-initialize-an-array-in-c), though not a duplicate, lists both. – Deduplicator Jan 16 '15 at 18:13

1 Answers1

2

what's the difference in C and which is a better way?

char array[]="string"; declares array as an array of 7 chars and initialize it with string.

char array[10]="string"; declares array as an array of 10 chars and initialize it with string.

You can use either depending as per the requirements. For ex: If you go with first, then string concatenation is not possible. If you go with second then a string of length 3 (including '\0') can be concatenated to it.

haccks
  • 104,019
  • 25
  • 176
  • 264
  • @; Gopi; In `char array[] = "string";`, `"string"` is an initializer. If the length of array is not specified, then compiler uses the length of initializer to calculate the length of the array. – haccks Jan 16 '15 at 18:23
  • You can't use this syntax without initializer. – haccks Jan 16 '15 at 18:24
  • @Gopi; Your welcome. One thing I would like to mention that you can use `char array[]` in a function parameter. – haccks Jan 16 '15 at 18:27
  • Since both works then why limiting the array by putting a value inside the [] – Sumon Jan 16 '15 at 18:39
  • @Sumon; May be the initializer is long enough to calculate its length correctly and you want to avoid that sudden accident caused by the wrong array length specified. – haccks Jan 16 '15 at 18:44