1

这是代码

    int main
    {
    char s[]="prady";
    char **p;

    p=(char **)&s;

    printf("%u %u\n",p,*p);
    printf("%u %u\n",&s,s); 

    printf("%s\n",s);
    printf("%s\n",&s);
    printf("%u %u\n",s+1,&s+1);


    printf("%s\n",p);
    printf("%s\n",*p);
    }

o/p:

3217062327 1684107888
3217062327 3217062327
prady
prady
3217062328 3217062336
prady
Segmentation fault

我的疑惑如下

  1. s和&s的地址如何相同?

  2. 如果两者相同,那么在添加 1 时它们如何显示不同?

  3. 我如何在 *p 中出现分段错误?

4

3 回答 3

2

首先,数组不是指针。指针不是数组。数组衰减为指针。

1.How both the address is same of s and &s?

char s[]="prady";

   --------------------------
s: | p | r | a | d | y | \0 |
   --------------------------

该数组s是一个要求留出 6 个字符的请求。换句话说,s有 6 个字符。's` 是一个“东西”,它不指向任何东西,它只是。

char *ptr = "prady";

------         --------------------------
|*ptr|    -->  | p | r | a | d | y | \0 |
------         --------------------------

指针ptr请求一个存放指针的地方。指针可以指向任何字符或任何字符串文字(连续字符)。

另一种思考方式:

int b;   //this is integer type 
&b;      //this is the address of the int b, right?  

int c[]; //this is the array of ints 
&c;      //this would be the address of the array, right? 

所以这是可以理解的:

*c;   //that's the first element in the array 

那行代码告诉你什么?如果我尊重 c,那么我会得到一个 int。这意味着只是简单的 c 是一个地址。由于它是数组的开头,它是数组的地址,因此:

c == &c;

2. If both are same then how they show different when adding 1 to it.

从我对#1的回答中,我假设您明白为什么它们不一样。那么为什么你会得到不同的值呢?看看你得到的值:

s    = 0x3217062327 
s+1  = 0x3217062328  // It's 1 bigger, why? Because a char takes 1 byte, s holds chars
                     // so s (address of a char) + 1 (sizeof char) gives you one more than s
&a + 1 //This is adding 1 (sizeof array) which is bigger than the size of a char  

3. How I got segmentation fault in *p.

我想你可以从我之前的两个答案中得到这个......但是:

  1. p 是指向字符的指针
  2. 您将 p 设置为数组的地址(记住,是数组本身)
  3. 对 p 的尊重是指向 char (另一个地址)的指针,但是您不能对数组执行此操作。

当您进行类型转换时,您告诉编译器“我比您更了解,所以只需让这两个工作”。当你出现段错误时......那是因为你真的不知道更好。

于 2012-09-28T21:58:36.480 回答
1

1.s和&s的地址如何相同。

s是一个字符数组。但是,数组被转换为指针,保存在少数情况下:当它们用于初始化数组时(例如:你的char s[]="prady"; 行),当它们是一元运算&符的操作数时(你的代码中有很多情况),当它们是运算符的操作数sizeof

2.如果两者相同,那么在向其添加 1 时它们如何显示不同。

他们不一样。

2.我是如何在 *p 中得到分段错误的。

p包含 的地址"prady"*p包含"prady". 尝试将"prady"其用作字符串的地址会导致段错误。

于 2012-09-28T21:38:15.380 回答
1

在您的情况下, s 不是指针。这是一个数组!

一个小小的改变将解决一个问题:

char *s = "prady";
于 2012-09-28T21:18:03.353 回答