0

What is the difference between:

char arr[20]="I am a string"

and

char *arr="I am a string"

How is it possible to initialize an array just by using a pointer?

Alex M
  • 2,756
  • 7
  • 29
  • 35
  • [Possible duplicate](https://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string-initialized-with-cha) – kocica Aug 27 '17 at 08:30
  • Possible duplicate of [Why do I get a segmentation fault when writing to a string initialized with "char \*s" but not "char s\[\]"?](https://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string-initialized-with-cha) –  Aug 27 '17 at 08:47
  • Possible duplicate of [how to initialize string pointer?](https://stackoverflow.com/questions/11859737/how-to-initialize-string-pointer) – Raghav Garg Aug 27 '17 at 08:50
  • Possible duplicate of [What is the difference between char s\[\] and char \*s?](https://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s) – autistic Aug 27 '17 at 09:42

3 Answers3

2

First one is clear, it is an array initialisation, whereas the second one means that character pointer *arr is pointing to the unnamed static array which will store the String " I am a string".

Vivek Singh
  • 114
  • 1
  • 8
1

One difference is in allocated storage size. First expression allocates 20 chars, but the second expression allocate the length of the string (13 chars).

The second difference is mentioned in this post. which is discussed on the way how these variables are allocated.

OmG
  • 18,337
  • 10
  • 57
  • 90
  • Thanks but I don't understand how the string is initialized to a pointer in second method since pointers are used to point another variable – Hiruni Nimanthi Aug 27 '17 at 08:42
1

In first case you are partially initializing stack allocated array with 14 chars taken from buffer represented by "I am a string" string literal.

In second case you are initializing stack allocated pointer with a pointer to a buffer with static storage duration represented by "I am a string" string literal. Also notice that in second case you should use const char *arr.

user7860670
  • 35,849
  • 4
  • 58
  • 84