Hiruni Nimanthi
Hiruni Nimanthi

Reputation: 65

Initializing strings using pointers

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?

Upvotes: 0

Views: 409

Answers (3)

Vivek Singh
Vivek Singh

Reputation: 114

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".

Upvotes: 2

user7860670
user7860670

Reputation: 37549

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.

Upvotes: 1

OmG
OmG

Reputation: 18838

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.

Upvotes: 1

Related Questions