cpointersaddress-operator

C Pointer To Array; To Primitive


I am using Visual Studio 2015 that isn't displaying compiler warnings related to my use of pointers. If I am referring for a moment to a pointer char* p that points to an array char name[] = "My Name", I don't have any guidance that the following are not all equal; i.e. result in a pointer to the first character of an array

char* pname = name; // points to first char in array

printf("\n%c\n", *pname);

pname = &name; // points to first char in array

printf("\n%c\n", *pname);

pname = &name[0]; // this explicitly points to the first char in the array

printf("\n%c\n", *pname);

The result of each printf is the same value and, because I don't see compiler warnings, I need guidance on which is the correct form.

This is the same for pointer to int whereby I do not see compiler warnings so I assume the following are equivalent

int age = 45;
int* page = &age; // point to age
page = age // pointer to age

Can someone please clarify this or perhaps help me turn on compiler warnings in Visual Studio 2015 without having to switch to TDM GCC + Eclipse Oxygen.

Point - Be syntactically specific and correct all warnings


Solution

  • char* pname = name; // points to first char in array
    

    Correct. When you evaluate an array, you get a pointer to its first element.

    pname = &name; // points to first char in array
    

    Incorrect. &name is a pointer to the whole array, not just its first element. The assignment is a type error: pname is a char *, but &pname is a char (*)[8].

    pname = &name[0]; // this explicitly points to the first char in the array
    

    Correct. The reason this works is because a[b] is defined as *(a + b). So &name[0] really means &*(name + 0). As before, the array evaluates to the address of its first element. Adding 0 doesn't change it. * dereferences the pointer, but & goes back to the address (they cancel each other out).

    int age = 45;
    int* page = &age; // point to age
    

    Correct.

    page = age; // pointer to age
    

    Incorrect. This is a type error: age is an int but page is an int *.

    What source are you learning C from?

    Unfortunately I can't tell you how to configure Visual Studio 2015 as I've never used it before. Have you tried reading its manual?