Can a char array be used with any data type?

前端 未结 3 1091
遇见更好的自我
遇见更好的自我 2020-12-31 18:32

The malloc() function returns a pointer of type void*. It allocates memory in bytes according to the size_t value passed as argument t

3条回答
  •  感动是毒
    2020-12-31 19:05

    The declared type of the static object Array is char. The effective type of this object is it's declared type. The effective type of a static object cannot be changed, thus for the remainder of the program the effective type of Array is char.

    If you try to access the value of an object with a type that is not compatible with, or not on this list1, the behavior is undefined.

    Your code tries to access the stored value of Array using the type int. This type is not compatible with the type char and is not on the list of exceptions, so the behavior is undefined when you read the array using the int pointer p:

    printf("%d ", p[n]);
    

    1 (Quoted from: ISO:IEC 9899:201X 6.5 Expressions 7 )
    An object shall have its stored value accessed only by an lvalue expression that has one of the following types:
    — a type compatible with the effective type of the object,
    — a qualified version of a type compatible with the effective type of the object,
    — a type that is the signed or unsigned type corresponding to the effective type of the object,
    — a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,
    — an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or
    — a character type.

提交回复
热议问题