读指针

时间:2019-05-23 09:42:33

标签: c

我有一个向量 int a[100]。 我已经阅读了向量,并为其指定了值1,2,3。 现在我想使用一个指针 int *pa=&a[100]。 我的问题是我可以通过scanf读取指针并为vector a[100]提供一些新值吗?

我尝试这样做:

for(i=0;i<n;i++)
{
    scanf("%d",&a[i])
}

向量和指针:

for(i=0;i<n;i++)
{
    scanf("%d",&pa)
}

这是我的主要爱好

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int a [100],n,i;
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    for(i=0;i<n;i++)
    {
        printf("%d",a[i]);
    }
    for(i=0;i<n;i++)
    {
        scanf("%d",&pa);
    }
    for(i=0;i<n;i++)
    {
        printf("%d",pa);
    }
    return 0;
}

{printf("%d",pa)给我999,向量a仍具有值1,2,3

1 个答案:

答案 0 :(得分:1)

以下代码说明pa指向一个对象,而*pa则指定了该对象。

#include <stdio.h>


int main(void)
{
    //  Set size of array.
    static const int N = 100;

    //  Define array.
    int a[N];

    //  Initialize array.
    for (int i = 0; i < N; ++i)
        a[i] = i+1;

    //  Define a pointer and initialize it to point to element a[0].
    int *pa = &a[0];

    /*  Scan as if "34" were in the input.  Observe that we pass pa, not &pa.
        &pa is the address of pa.  pa is the value of pa.  Its value is the
        address of a[0].
    */
    sscanf("34", "%d", pa);

    //  Print a[0].  This will be "34".
    printf("%d\n", a[0]);

    /*  Print *pa.  Note that we use *pa, which is the object pa points to.
        That objects is a[0], so the result is "34".
    */
    printf("%d\n", *pa);

    /*  Change pa to point to a different element.  Note that we use "pa =
        address" to set the value.  This is different from the initialization,
        which had "int *pa = value".  That is because declarations need the
        asterisk to describe the type, but an assignment just needs the name;
        it does not need the asterisk.
    */
    pa= &a[4];

    //  Print *pa.  Since pa now points to a[4], this will print "5".
    printf("%d\n", *pa);
}