循环遍历struct中的数组

时间:2014-09-16 03:05:02

标签: c++ arrays pointers syntax struct

我是学生,第一次学习指针。我的赋值不允许使用字符串类,应该使用指针表示法来访问数组中的所有元素(没有[])。

为什么我无法通过指针访问结构内部的数组?我的语法是否关闭?

#include <iostream>

using namespace std;

struct person
{
    int favNums[4];
};

// Notation works here
void strCopy(char *from, char *to, int len)
{        
    for (int i = 0; i < len; i++)
    {
        *(to + i) = *(from + i);
    }
}

// But doesn't work here
void sayNumsPointerNotation(person peep)
{
    for (int i = 0; i < 4; i++)
    {
        //cout << peep.*(favNums + i) << endl;
    }
}

// Would like to accomplish this.
void sayNums(person peep)
{
    for (int i = 0; i < 4; i++)
    {
        cout << peep.favNums[i] << endl;
    }
}

int main() 
{
    // Array outside of struct
    char from[5] = "Word";
    char to[5];
    strCopy(from, to, 5);
    cout << to << endl << endl;

    // Array inside of struct non-pointer
    person peep;
    peep.favNums[0] = 0;
    peep.favNums[1] = 1;
    peep.favNums[2] = 2;
    peep.favNums[3] = 3;

    sayNums(peep);
    cout << endl;

    sayNumsPointerNotation(peep);
    cout << endl;
}

3 个答案:

答案 0 :(得分:1)

这应该有用,希望你能理解错误。

#include <iostream>

using namespace std;

struct person
{
    int favNums[4];
};

// Notation works here 
void strCopy(char *from, char *to, int len)
{        
    for (int i = 0; i < len; i++)
    {
        *(to + i) = *(from + i);
    }
}

// But doesn't work here (now it works)
void sayNumsPointerNotation(person* peep)
{
    for (int i = 0; i < 4; i++)
    {
        cout << *(peep->favNums + i) << endl;
    }
}

// Would like to accomplish this.
void sayNums(person peep)
{
    for (int i = 0; i < 4; i++)
    {
        cout << peep.favNums[i] << endl;
    }
}

int main() 
{
    // Array outside of struct
    char from[5] = "Word";
    char to[5];
    strCopy(from, to, 5);
    cout << to << endl << endl;

    // Array inside of struct non-pointer
    person peep;
    peep.favNums[0] = 0;
    peep.favNums[1] = 1;
    peep.favNums[2] = 2;
    peep.favNums[3] = 3;

    sayNums(peep);
    cout << endl;

    sayNumsPointerNotation(&peep);
    cout << endl;
}

答案 1 :(得分:0)

使用

cout << *(peep.favNums + i) << endl;
另一方面,

.*是&#34;成员指针&#34;,意味着不同的东西。

答案 2 :(得分:0)

而不是

cout << peep.*(favNums + i) << endl;

试试这个:

cout << *(peep.favNums + i) << endl;