从C中不兼容的指针类型错误获取分配

时间:2018-10-30 03:59:37

标签: c eclipse pointers

我必须编写一个代码,声明并初始化三个变量,即double,int和string(5位,包括null char),然后使用printf和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;
}

1 个答案:

答案 0 :(得分:0)

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

arry的类型为char[5],它是char的数组,因此&arrychar的指针和数组。由于pc的类型为char *,因此指针不兼容。

pc = arry;

此处arry衰减到指向其第一个元素的指针,并且此分配有效。

另一方面,如果您真的想要一个指向char数组的指针(如注释中所写),则必须这样声明:

char (*pc)[5];

还应该在printf中使用适当的标识符,并将指针转换为void *。对于size_t,您应该使用%zu