C指针和阵列 [英] c pointers and array

查看:120
本文介绍了C指针和阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 的#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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆