复制字符串文字时地址不同
我是编程新手。
我们知道 iar是指向第一个元素的指针,即。它指向 1 的基数,我们将此指针存储到第 5 行中的另一个指针 p。它们现在都指向 int 数组的第一个元素。当打印它们存储的地址时,它是相同的,即0x7ffe3b93f660。
我们还知道字符串文字也是指向字符串第一个字符的指针,而 ar 也将是指向字符串第一个字符的指针。如果它们都指向相同的元素,那么为什么它们返回不同的地址,即 0x5565b94e700f 和 0x7ffe3b93f66c。
为什么会发生这种情况,为什么在第二种情况下也不使用相同的地址?
#include <stdio.h>
int main()
{
int iar[]={1,2,3};
int *p=iar;
printf("\n%p and %p",iar,p);
char ar[]="Kurukshetra";
printf("\n%p and %p","Kurukshetra",ar);
printf(" %c ",*ar);
printf(" %c ",*"Kurukshetra");
return 0;
}
我还附上了一张图像,该问题显示了执行时的不同地址。
I am new to programming.
We know that iar is a pointer to the first element ie. it points to base of 1 and we stored this pointer to another pointer p in line 5. They both now point to the first element of int array. When the address they are storing is printed it is same i.e. 0x7ffe3b93f660.
We also know the string literal also is a pointer to the first character of the string and ar will also be a pointer to the first character of the string. If both of them are pointing to the same element than why they are returning different address i.e. 0x5565b94e700f and 0x7ffe3b93f66c.
Why is this happening why not the same address in second case also?
#include <stdio.h>
int main()
{
int iar[]={1,2,3};
int *p=iar;
printf("\n%p and %p",iar,p);
char ar[]="Kurukshetra";
printf("\n%p and %p","Kurukshetra",ar);
printf(" %c ",*ar);
printf(" %c ",*"Kurukshetra");
return 0;
}
I have also attached an image with this question showing different address on execution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,将转换说明符
%d
与指针一起使用是无效的。而不是
and ,
你必须写成
and
数组
ar
和字符串文字占用不同的内存范围。所以他们的地址是不同的。数组 ar 是通过将字符串文字的字符复制到数组占用的内存范围中来初始化的。
您可以按照以下方式想象这一点,
正如您所看到的,每个数组都有其一个内存范围。
另请注意,即使相同的字符串文字也可以具有不同的地址。也就是说,编译器可以将相同的字符串文字存储为具有静态存储持续时间的一个字符数组或单独的数组。这取决于编译器选项。
因此,例如,如果编译器将相同的字符串文字存储为单独的数组,那么这些调用
可能会产生不同的值。
形成 C 标准(6.4.5 字符串文字)
First of all using the conversion specifier
%d
with pointers is invalid.Instead of
and
you have to write
and
The array
ar
and the string literal occupy different extents of memory. So their addresses are different.The array
ar
was initialized by characters of the string literal by means of copying them in the extent of memory occupied by the array.You may imagine this the following way
As you see each array has its one extent of memory.
Also pay attention to that even identical string literals can have different addresses. That is the compiler can store identical string literals as one character array with static storage duration or as separate arrays. This depends on compiler options.
So for example if the compiler stores identical string literals as separate arrays then these calls
can produce different values.
Form the C Standard (6.4.5 String literals)