0

I have learned that the traditional way of declaring a character array is as follows:

char c[] = "John";

However, I have also noticed that you can declare it as:

char *c = "John";

How exactly does this work? I know that it has something to do with pointers, but could someone please elaborate? Any help would be greatly appreciated.

RadicalOne
  • 67
  • 1
  • 4
  • 1
    Read section 6 of the [comp.lang.c FAQ](http://www.c-faq.com), and ignore anyone who tries to tell you that arrays are "really" pointers. – Keith Thompson Aug 19 '13 at 22:16
  • @RadicalOne, you can also read Kernighan and Ritchie (K&R) which is NOT a self-published polemic. They will explain how pointers are used and in what ways they are used to reference arrays. – JackCColeman Aug 19 '13 at 22:41
  • I saw you question, you should read complete answer: [What does sizeof(&arr) return?](http://stackoverflow.com/questions/15177420/what-does-sizeofarr-return/15177499#15177499) – Grijesh Chauhan Aug 24 '13 at 05:09

3 Answers3

0

In your first example, c is an array of char. But in:

 char *c = "John";

c here is not an array but a pointer (type char *) to a string literal. Pointers and arrays are different types in C.

Below is a good link if you want to learn about pointers and arrays:

http://www.torek.net/torek/c/pa.html

ouah
  • 142,963
  • 15
  • 272
  • 331
0

"A string literal (the formal term for a double-quoted string in C source) can be used in two slightly different ways..." http://c-faq.com/decl/strlitinit.html

Arzaquel
  • 1,412
  • 2
  • 11
  • 16
0

Okay.. I hope I will not messed thing up here, however I see it Like this.

What you do by writing ="John" is that you put a string somewhere in your program memory, which is terminated by '\0'.

That's why there is no difference in your calls. Both create a char pointer pointing at the beginning of your string in the program memory.

If you would allocate this memory e.g. with malloc(). The pointer would point towards your runtime memory and not somewhere inside the program memory.

Stefan
  • 157
  • 9