指针指针给出了分段错误?

时间:2012-09-28 21:13:10

标签: c

这是代码

    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 个答案:

答案 0 :(得分: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. 的指针
  3. 您将p设置为数组的地址(记住,是数组本身)
  4. p的顺序是指向char(另一个地址)的指针,但是你不能对数组这样做。
  5. 当你进行类型转换时,你告诉编译器“我知道的比你好,所以只需要让这两个工作”。当你发生段错误时......那是因为你真的不知道更好。

答案 1 :(得分:1)

在你的情况下,s不是一个指针。这是一个阵列!

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

char *s = "prady";

答案 2 :(得分:1)

  

1.地址是否与s和& s相同。

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

  

2.如果两者相同,则在向其添加1时它们的显示方式不同。

它们不一样。

  

2.如何在* p。

中出现分段错误

p包含"prady"的地址。 *p包含"prady"。尝试使用"prady"就像它是字符串的地址一样会导致段错误。

相关问题