如何使用字符串(字符数组)初始化 char 指针,而不使用整数数组初始化 int 指针? [英] How can a char pointer be initialized with a string (Array of characters) but an int pointer not with an array of integer?
问题描述
如何用字符串(字符数组)初始化char
指针而不用整数数组初始化int
指针?
How can char
pointer be initialized with a string (Array of characters) but an int
pointer not with a array of integer?
当我尝试这个时
int* a={1,2,3,4,5};
它给出了一个错误说
错误:标量对象‘a’需要初始化器中的一个元素
error: scalar object ‘a’ requires one element in initializer
但是,
char* name="mikhil"
完美运行.
推荐答案
如果您尝试使用
{1,2,3,4,5};
这是错误的,因为 {1,2,3,4,5};
按原样不是 整数数组.它是一个括号括起来的初始化程序列表.这可用于初始化 int
数组(数组的各个元素,具体而言),但不能用于初始化指针.数组不是指针,反之亦然.
it is wrong because {1,2,3,4,5};
, as-is, is not an array of integers. It is a brace enclosed list of initializer. This can be used to initialize an int
array (individual elements of the array, to be specific), but not a pointer. An array is not a pointer and vice-versa.
但是,您可以使用 复合文字 来初始化一个int *
,如
However, you can make use of a compound literal to initialize an int *
, like
int * a = (int []){1,2,3,4,5};
这篇关于如何使用字符串(字符数组)初始化 char 指针,而不使用整数数组初始化 int 指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!