字符数组和指针的区别 [英] Difference between character array and pointer
问题描述
我做同样的事情在这两个codeS。
在code 1:我使用了一个的char *
并使用分配空间的malloc
在主
。
在code 2:我使用了一个字符
数组为同一目的。但是,为什么是输出不同呢?
code 1:
结构节点2
{
int数据;
炭P [10];
} A,B;主要()
{
A.数据= 1; 的strcpy(A.P,堆栈);
B = A;
的printf(%d个%S \\ n,b.data,沸点); //输出1栈
的strcpy(沸点,溢出);
的printf(%d个%S \\ n,b.data,沸点); //输出1溢出
的printf(%d个%S \\ n,A.数据,A.P); //输出1栈
}
code 2:
结构节点1
{
int数据;
字符* P;
} A,B;主要()
{
A.数据= 1;
A.P = malloc的(100);
的strcpy(A.P,堆栈);
B = A;
的printf(%d个%S \\ n,b.data,沸点); //输出1栈
的strcpy(沸点,溢出);
的printf(%d个%S \\ n,b.data,沸点); //输出1溢出
的printf(%d个%S \\ n,A.数据,A.P); //输出1溢出(为什么不一样previous一个?)
}
在你指定的第二个例子 A
到 B
,这意味着 AP
(的char *
)被分配给了基点
。因此,修改内存指向 BP
也修改存储器指向 AP
,自的他们'重新两者指向同一位置在存储器的
在第一个例子,你的两个独立的阵列的。分配 A
到 B
的拷贝每个字符
的阵列中的 AP
到 BP
- 内存的这些块的一部分结构
,他们不是指向内存中的特定部分。在这种情况下,任何修改沸点
可以在不影响 A.P
因为他们是完全无关的。
I am doing the same thing in both the codes.
In code 1: I have used a char *
and allocate the space using malloc
in main
.
In code 2: I have used a char
array for the same purpose. But why is the output is different ?
Code 1:
struct node2
{
int data;
char p[10];
}a,b;
main()
{
a.data = 1;
strcpy(a.p,"stack");
b = a;
printf("%d %s\n",b.data,b.p); // output 1 stack
strcpy(b.p,"overflow");
printf("%d %s\n",b.data,b.p); // output 1 overflow
printf("%d %s\n",a.data,a.p); // output 1 stack
}
Code 2:
struct node1
{
int data;
char *p;
}a,b;
main()
{
a.data = 1;
a.p = malloc(100);
strcpy(a.p,"stack");
b = a;
printf("%d %s\n",b.data,b.p); //output 1 stack
strcpy(b.p,"overflow");
printf("%d %s\n",b.data,b.p); // output 1 overflow
printf("%d %s\n",a.data,a.p); // output 1 overflow(why not same as previous one?)
}
In the second example you're assigning a
to b
, which means that a.p
(char*
) is being assigned to b.p
. Therefore modifying the memory pointed to by b.p
is also modifying the memory pointed to by a.p
, since they're both pointing to the same location in memory.
In the first example, you have two separate arrays. Assigning a
to b
copies each char
in the array a.p
to b.p
- these blocks of memory are part of the struct
, they're not pointers to a specific part in memory. Any modification to b.p
in this case can't affect a.p
since they're completely unrelated.
这篇关于字符数组和指针的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!