Lucas Seran
Lucas Seran

Reputation: 11

Getting an assignment from incompatible pointer type error in C

I have to make a code that declares and initalizes three variables, a double, int, and string (5 bits including null char) then print the size address, and value using printf and sizeof

#include <stdio.h>
#include <stdlib.h>

int main() {

    int number = 5, *pI;
    pI = &number; // Assigning Integer variable to integer pointer
    double number2 = 10.5, *pD;
    pD = &number2; // Assigning Double variable to Double pointer
    char arry[] = "dogs", *pc;
    pc = &arry; // Assigning Char Array variable to Char Array Pointer

    // Size, Address and Value stored in each Integer Variable, Double Variable and Character Variable
    printf("Integer Size is = %d , Address is = 0x%p and Value is = %d: \n",
            sizeof(number), &number, number);
    fflush(stdout);
    printf("Double Size is = %d, Address is = 0x%p and Value is = %lf: \n",
            sizeof(number2), &number2, number2);
    fflush(stdout);
    printf(
            "Character Array Size is = %d, Address is = 0x%p and Value is = %s: \n",
            sizeof(arry), &arry, arry);
    fflush(stdout);

    // Pointers Size, Address and Value stored in each Integer Pointer, Double Pointer and Charecter pointer
    printf(
            "Pointer Integer Size is = %d , Address is = 0x%p and Value is = %d: \n",
            sizeof(pI), &pI, *pI);
    fflush(stdout);
    printf(
            "Pointer Double Size is = %d, Address is = 0x%p and Value is = %lf: \n",
            sizeof(pD), &pD, *pD);
    fflush(stdout);
    printf(
            "Pointer Character Array Size is = %d, Address is = 0x%p and Value is = %s: \n",
            sizeof(pc), &pc, pc);
    fflush(stdout);

    return 0;
}

Upvotes: 0

Views: 697

Answers (1)

Osiris
Osiris

Reputation: 2823

char arry[] = "dogs", *pc;
pc = &arry;

arry is of type char[5], it is an array of char, therefore &arry is a pointer to and array of char. Since pc is of type char * the pointers are incompatible.

pc = arry;

Here arry decays to a pointer to its first element, and this assignment is valid.

On the other side if you really want a pointer to a char array, as written in your comments, you have to declare it like this:

char (*pc)[5];

Also you should use the proper identifiers in printf and cast the pointers to void *. For size_t you should use %zu.

Upvotes: 0

Related Questions