这些指针语句有什么区别

时间:2020-03-31 06:33:37

标签: c pointers

int main(){
  char *c = "testando"; // how i can declare an array of characters at the same time of a char pointer statement
  int *i = {1,3,5,7,9}; // and here i can't declare an array of integers at the same time of a integer pointer statement
  return 0;
}

有什么区别?

3 个答案:

答案 0 :(得分:2)

初始化字符串的指针是原始C语言中的一种特殊情况。

C99添加了compound literals,您可以使用它们来初始化指向其他类型数组的指针。

int *i = (int[]){1, 3, 5, 7, 9};

答案 1 :(得分:2)

这只是语法。诸如"hello"之类的字符串文字会作为特殊类型提供char[]的只读数组。同样,字符串文字可以用作数组初始化器。

{1,3,5,7,9}不是数组,而是初始化列表。

您可以使用复合文字创建具有本地范围的任何类型的临时数组:

int *i = (int[]){1,3,5,7,9};

这几乎等同于声明一个命名数组然后指向它:

int arr[] = {1,3,5,7,9};
int *i = arr;

答案 2 :(得分:0)

首先,c是指向字符串常量的指针。 与指向数组的指针不同。

c是指向以只读内存中的空字符终止的字符列表的指针。可以重新分配指针,使其指向另一个字符或字符串。

由于多种原因,它很有用,因此包含在ANSI和GNU C标准中。通常,更好的做法是在只读内存中指向整数列表的指针不如枚举或预处理器 #define 有用。 / p>

它的行为不会像更改字符值的数组未定义一样-尝试调用:*c = 2*(c+1) = 4

下面是一个函数如何使用字符串常量的示例:

File *openPipeToProgram(int flag){
        char *programname;
        if(flag == PROGRAM1)
                programname = "program1"
        else if(flag == PROGRAM2)
                programname = "program2"
        else
                return NULL;
        return popen(programname, "w");
}

请注意,PROGRAM1和PROGRAM2是符号常量,用于代替只读数字数组。