char 数组可以用于任何数据类型吗?
malloc()
函数返回一个 void*
类型的指针.它根据作为参数传递给它的 size_t
值以字节为单位分配内存.结果分配是原始字节,可用于 C 中的任何数据类型(无需强制转换).
The malloc()
function returns a pointer of type void*
. It allocates memory in bytes according to the size_t
value passed as argument to it. The resulting allocation is raw bytes which can be used with any data type in C(without casting).
可以在返回 void *
的函数中声明类型为 char
的数组与任何数据类型一起使用,例如 malloc
的结果分配>?
Can an array with type char
declared within a function that returns void *
, be used with any data type like the resulting allocation of malloc
?
例如
#include <stdio.h>
void *Stat_Mem();
int main(void)
{
//size : 10 * sizeof(int)
int buf[] = { 1,2,3,4,5,6,7,8,9,10 };
int *p = Stat_Mem();
memcpy(p, buf, sizeof(buf));
for (int n = 0; n < 10; n++) {
printf("%d ", p[n]);
}
putchar('\n');
return 0;
}
void *Stat_Mem()
{
static char Array[128];
return Array;
}
静态对象Array
的声明类型为char
.这个对象的有效类型是它的声明类型.静态对象的有效类型不能改变,因此对于程序的其余部分,Array
的有效类型是 char
.
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
.
如果您尝试访问类型与此列表不兼容或不在此列表中的对象的值1,则行为未定义.
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.
您的代码尝试使用 int
类型访问 Array
的存储值.此类型与类型 char
不兼容且不在异常列表中,因此当您使用 int
指针 p 读取数组时,行为未定义代码>:
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(引用自:ISO:IEC 9899:201X 6.5 Expressions 7)
对象的存储值只能由左值访问具有以下类型之一的表达式:
- 一种与对象的有效类型兼容,
— 一个合格的与对象有效类型兼容的类型版本,
— 一种类型,它是与对应的有符号或无符号类型对象的有效类型,
— 有符号或无符号的类型对应于有效类型的限定版本的类型对象,
— 一个聚合或联合类型,包括以下之一其成员之间的上述类型(包括递归地,子聚合或包含联合的成员),或
— 一种字符类型.
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.