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?

4

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.