本文介绍了Ç - 字符数组和字符指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我无法定义
数组

 的char ** PP = {123,456,789};

不过,我可以把它定义为一个char * [],并将其发送到将接受它作为一个char功能**

 的char * PP [] = {123,456,789};
有趣(PP);无效的乐趣(字符** pointerToPointer)
{
    // +(** pointerToPointer); //错误
    的printf(%S,* pointerToPointer);
}
//输出::123

和我为什么不能增加

  ++(** pointerToPointer);


解决方案

要回答第一个问题,如果我们用指针的一个深度的原则可能会更清晰。这code是非法出于同样的原因:

 为int * PTR = {1,2,3};

在C,一个支撑初始化列表是不是一个对象(尤其不是一个数组)。它只能被视为物品从其中一个对象时被初始化读取初始化的列表。

PTR 是一个对象,所以最多有一个初始化可以采取,而初始的预期形式是指针(其中 1 不是)。

事实上,这code是在C11明确非法6.7.9 / 11:

However, there is a gcc bug/feature where it permits excess initializers for a scalar and ignores them. Further, some compilers may "be helpful" and "only" issue a warning, and initialize ptr to point to address 1, wherever that might be.

"scalar" means an object that's not a struct or an array.


Since C99 you can write:

int *ptr = (int []){1, 2, 3};

which creates an array (using the same storage duration as ptr) and points ptr at its first element.

This array is mutable; for a non-mutable one use int const *ptr = (int const[]){1, 2, 3}; instead.


Replacing int by char *, we see that you could write:

char **p = (char *[]){ "123", "456", "789" };

in which case the pointers in the array are mutable, but the things they point to (i.e. the string literals) still aren't.

Note that you should always use char const * when dealing with string literals, because they are not mutable. The fact that string literals have type char [N] is a historical hangover from before const was added to C. So:

char const **pp = (char const *[]){ "123", "456", "789" };

or with non-mutable pointers to strings:

char const *const *pp = (char const *const []){ "123", "456", "789" };

这篇关于Ç - 字符数组和字符指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:36