C指针和阵列 [英] c pointers and array
问题描述
的#include<&stdlib.h中GT;
#包括LT&;&stdio.h中GT;INT主要(无效)
{
诠释一个[] = {1,2,3,4,5};
INT B〔] = {0,0,0,0,0};
INT * P = B; 的for(int i = 0;我小于5;我++)
{
B〔I] = A [I] +1;
* P = A [I] +1;
p ++;
}
的for(int i = 0;我小于5;我++)
{
的printf(%I \\ T%I \\ T%I \\ N,* P +,B [I],一个[I]);
}
返回0;
}
有关此code我知道为什么输出为a和b,但为什么指针有一个相同的值?
* p是B [0] = a [0] +1,是不是?
因此P ++意味着下一个地址在对B,因此'S B [1] = A [1] +1。
即
* P B A
1 2 1
2 3 2
3 4 3
4 5 4
5 6 5
您也越来越的未定义行为的。在第一循环结束 P
点一过去到底乙
。如果没有重置它,你再取消对它的引用,并继续增加它,这两者造成的未定义行为的
它的可以的是,在你执行数组 A
的数组后,立即存储 B
和 p
已开始指向到数组 A
。这将是一种可能的未定义bahaviour
#include <stdlib.h>
#include <stdio.h>
int main (void)
{
int a[] = {1,2,3,4,5};
int b[] = {0,0,0,0,0};
int *p = b;
for (int i =0; i < 5; i++)
{
b[i] = a[i]+1;
*p = a[i]+1;
p++;
}
for (int i = 0; i < 5; i++)
{
printf (" %i \t %i \t %i \n", *p++, b[i], a[i]);
}
return 0;
}
For this code I get why the output for a and b but why does the pointer have the same value of a?
*p is b[0] = a[0]+1, isn't it? So p++ means next address over for b so it's b[1]=a[1]+1.
ie
*p b a
1 2 1
2 3 2
3 4 3
4 5 4
5 6 5
You are getting undefined behavior. At the end of the first loop p
points to "one past the end" of b
. Without resetting it, you then dereference it and continue to increment it, both of which cause undefined behavior.
It may be that on your implementation the array a
is stored immediately after array b
and that p
has started to point into array a
. This would be one possible "undefined" bahaviour.
这篇关于C指针和阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!