简体   繁体   English

使用指向结构的指针的两个函数(读取和显示数组)

[英]two functions (read and display an array) using pointers to structures

I just start to learn pointers to structures and I'm confused.I have to create a type of data ARRAY (which is associated with an array which contains integers.) like a structure which contains: numbers of array's elements and the array's elements stored in a part of memory(heap), dynamically allocated.我刚开始学习指向结构的指针,我很困惑。我必须创建一种数据 ARRAY(它与包含整数的数组相关联。)就像一个结构,它包含:数组元素的数量和存储的数组元素在内存(堆)的一部分中,动态分配。

So I wrote:所以我写道:

typedef struct ARRAY
{
        int nrElem; // number of elements
        int *v[100];
};

Now I need to create 2 functions, one for reading an array from keyboard and the second one to display it using the structure I declared.现在我需要创建 2 个函数,一个用于从键盘读取数组,第二个用于使用我声明的结构显示它。

I tried but I get stuck.我试过了,但我被卡住了。

void arrayDisplay(ARRAY *ps)
{
        int i;
        for(i=0;i<pd->nrElem;++i)
        {
                printf("%d",)
        }
}

void readArray(ARRAY *ps)
{
        int i;
        for(i=0;i<pd->nrElem;++i)
        {
                printf("%d",)
                scanf("%d",&);
        }
}

How to continue?如何继续?

Instead of an array of pointers int *v[100];而不是指针数组int *v[100]; you need an array of ints int v[100];你需要一个整数数组int v[100]; in your data structure.在您的数据结构中。

See code below:见下面的代码:

#include <stdio.h>
#include <stdlib.h>

typedef struct ARRAY
{
        int nrElem; // number of elements
        int v[100];
} ARRAY;

void arrayDisplay(ARRAY *ps)
{
        int i;
        for(i=0;i<ps->nrElem;++i)
        {
                printf("%d\n", ps->v[i]);
        }
}

void readArray(ARRAY *ps)
{
        int i;
        for(i=0;i<ps->nrElem;++i)
        {
                printf("%d: ", i);
                scanf("%d",&ps->v[i]);
        }
}

int main()
{
    ARRAY a;

    a.nrElem = 5;
    readArray(&a);
    arrayDisplay(&a);

    return 0;
}

If you really want to use an array of int pointers you need to allocate the array first.如果你真的想使用一个 int 指针数组,你需要先分配这个数组。 And a different level of redirection for printf and scanf. printf 和 scanf 的重定向级别不同。 But I'm not sure why you want to allocate memory for an integer array like this.但是我不确定为什么要为这样的整数数组分配内存。

typedef struct ARRAY
{
        int nrElem; // number of elements
        int *v[100];
} ARRAY;

void arrayDisplay(ARRAY *ps)
{
        int i;
        for(i=0;i<ps->nrElem;++i)
        {
                printf("%d\n", *ps->v[i]);
        }
}

void readArray(ARRAY *ps)
{
        int i;
        for(i=0;i<ps->nrElem;++i)
        {
                printf("%d: ", i);
                scanf("%d",ps->v[i]);
        }
}

int main()
{
    ARRAY a;
    int i;

    a.nrElem = 5;
    for(i=0;i<a.nrElem;++i) {
        a.v[i] = (int*)malloc(sizeof(a.v[i]));
    }
    readArray(&a);
    arrayDisplay(&a);

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM