0

Why is that strcpy() accepting char array pointer even though the definition of strcpy is char * strcpy( char * , const char * ) ??

#include <stdio.h>
#include <string.h>

main()
{
    char str[] = "Have A Nice Day";
    char ptr[17];

    strcpy(ptr, str);
    printf("%s", ptr);

}
n0p
  • 3,399
  • 2
  • 29
  • 50
Rabi
  • 19
  • 2

3 Answers3

4

An array is not a pointer (although they are similar in behavior and usage), but it transparently decays to one in a context where a pointer is needed (like in the case where it's passed as a parameter to a function that expects a pointer).

A more in-depth description can be found in the C FAQ 6.3.

Sander De Dycker
  • 16,053
  • 1
  • 35
  • 40
-1

An char[n] gives an address which can be used in place of a const pointer with memory allocated at time of declaration.

Soren
  • 14,402
  • 4
  • 41
  • 67
  • A `char[]` is not a const pointer, it is an incomplete array type. The two are not equivalent. Try compiling `extern char a[]; char f() { return a[0]; }` vs `extern char* const a; char f() { return a[0]; }` and looking at the difference. – CB Bailey Jul 30 '11 at 08:17
-4

In C/C++ arrays are pointers as well. http://www.cplusplus.com/forum/articles/9/ See here for more explanation.

rgngl
  • 5,353
  • 3
  • 30
  • 34
  • Arrays are not pointers. But an array identifier can be implicitly converted to a pointer to the first array element. – gnud Jul 30 '11 at 08:05
  • From the linked article: "The difference between pointers and arrays I have seen in many places that an array is introduced as a pointer. This is technically not correct. Arrays are not pointer. So what is it? It is like any other variable in C++." – GEOCHET Oct 05 '15 at 18:00