0

I read here: C: differences between char pointer and array that char pointers and char arrays are not the same. Therefore, I would expect these to be overloading functions:

#include <iostream>
using namespace std;

int function1(char* c)
{
    cout << "received a pointer" << endl;
    return 1;
}
int function1(char c[])
{
    cout << "received an array" << endl;
    return 1;
}

int main()
{
    char a = 'a';
    char* pa = &a;
    char arr[1] = { 'b' };

    function1(arr);
}

Yet upon building I get the error C2084: function 'int function1(char *)' already has a body. Why does the compiler seem to consider a char pointer to be the same as a char array?

Community
  • 1
  • 1
Ushwald
  • 73
  • 1
  • 8
  • 8
    See http://stackoverflow.com/questions/6567742/passing-an-array-as-an-argument-to-a-function-in-c. Note function parameters are a special case. – chris Apr 30 '15 at 19:36

1 Answers1

0

Because when you pass an array into a function, it magically becomes a pointer.

Your two functions, then, are the same.

The following are literally* identical:

void foo(int arr[42]);
void foo(int arr[]);
void foo(int* arr);

(* not lexically, of course :P)

This historical C oddity is the major reason lots of people mistakenly think that "arrays are pointers". They're not: this is just a bit of an edge case that causes confusion.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055