我是C的初学者,任何人都可以帮我输出

时间:2012-12-11 13:11:53

标签: c

我需要在结构中提到的行数组中添加数字。 例如,我需要行的输出= [4 5 6] 和年龄= 25,我怎么能用上面提到的结构? 请帮忙!

#include<stdio.h>

typedef struct person
{
    int row[1];
    int age;
} PERSON;

int main()
{
    PERSON p;
    PERSON *pptr=&p;

    pptr->row[1] = 4;
    pptr->age = 25;
    printf("%d\n",pptr->row[1]);
    printf("%d\n",pptr->age);
    return 0;
}

5 个答案:

答案 0 :(得分:2)

你问为什么行

printf("%d\n",pptr->row[1]);

返回age的值?这是因为int row[1];声明了一个包含一个元素的数组,但pptr->row[1]尝试访问数组的第二个元素(数组索引基于零)。换句话说,您正在写入超出已分配数组末尾的内存。

这样做的效果是未定义的,但如果pptr->row[1]指向的内存实际上是pptr->age

,那就不足为奇了

答案 1 :(得分:1)

在C中,数组从0开始:

int row[1]; 

表示只有一个int的数组。

第一个位置是:

pptr->row[0] = 4;

答案 2 :(得分:1)

请记住,在C中,N元素数组的索引从0到N-1。例如:

int arr[5];

arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;

由于您已将row的{​​{1}}成员声明为1元素数组 1 ,因此行

struct

pptr->row[1] = 4;

正在访问数组范围之外的内存;这样做的行为是 undefined ,所以几乎任何事情都可能发生。

<小时/> 1。目前还不清楚这里的目的是什么。除非您希望在大多数情况下将printf("%d\n", pptr->row[1]); 视为指针,否则1元素数组有什么用?

答案 3 :(得分:1)

I need to add the numbers in the row array mentioned in the structure. for example I need the output of row=[ 4 5 6] and age= 25, how can i do with the above mentioned structure?? Please help !

基于此更新:

将要存储的元素数量放入数组定义中:

int row[1]; // This stores 1 element of type int

// you want to store 3 elements: 4, 5, 6, so...

int row[3];  // This is what you're looking for

记住一个数组:

int row[X];

row[0]转到row[X-1]。因此,在您的情况下X=3表示您的数组的最小值/最大值为:

min = row[0]
max = row[3-1] = row[2]

这意味着您的代码应该执行以下操作:

pptr->row[0] = 4;
pptr->row[1] = 5;
pptr->row[2] = 6;
pptr->age = 25;
printf("%d\n",pptr->row[0]);
printf("%d\n",pptr->row[1]);
printf("%d\n",pptr->row[2]);
printf("%d\n",pptr->age);

答案 4 :(得分:0)

在您的所有代码中使用

pptr->row[0]

而不是

pptr->row[1]

行数组的大小为1,C中的数组索引从0开始,而不是从1

开始
相关问题