如何通过引用将结构数组传递给函数?
问题描述:
#include <stdio.h>
void changeValues(struct ITEM *item[]);
struct ITEM
{
int number;
};
int main(void)
{
struct ITEM items[10];
for (int i = 0; i < 10; i++)
{
items[i].number = i;//initialize
printf("BEFORE:: %d\n", items[i].number);
}
changeValues(items);
for (int i = 0; i < 10; i++)
{
items[i].number = i;
printf("AFTER:: %d\n", items[i].number);
}
return 0;
}
void changeValues(struct ITEM *item[])
{
for (int i = 0; i < 10; i++)
item[i] -> number += 5;
}
我想将一个结构数组传递给一个函数。我需要通过引用而不是值来更改函数内结构成员的值。由于某些奇怪的原因,当我在调用该函数后打印结果时,值与函数调用之前的值保持不变。如何通过引用将结构数组传递给函数?
答
在C中,你不能通过引用传递(如C++)。您只能通过值传递,或通过指针传递。
在这种情况下,看起来你想要传递一个结构数组来作用changeValues
。这就是你在main
中所做的。但是,您实际尝试将changeValues
的指针数组传递给struct ITEM
的原型和实现。
一个可能的解决方法是将指针数组更改为结构ITEM
只是结构数组。
void changeValues(struct ITEM item[])
{
for (int i = 0; i < 10; i++)
{
item[i].number += 5;
}
}
编辑:实际上,你必须在你的代码中的其他两个错误:
1)结构ITEM
的定义必须是前changeValues
原型:
struct ITEM
{
int number;
};
void changeValues(struct ITEM item[]);
2)您的main()
您实际上重置了changeValues
中的所有值 - 基本上,您已使该功能中完成的所有操作都失效:
for (int i = 0; i < 10; i++)
{
items[i].number = i; // <-- Remove this line as you are resetting the value again here
printf("AFTER:: %d\n", items[i].number);
}
struct ITEM
{
int number;
};
void changeValues(struct ITEM item[]);
int main(void)
{
struct ITEM items[10];
for (int i = 0; i < 10; i++)
{
items[i].number = i;//initialize
printf("BEFORE:: %d\n", items[i].number);
}
changeValues(items);
for (int i = 0; i < 10; i++)
{
// items[i].number = i; // <-- Remove this line as you are resetting the value again here
printf("AFTER:: %d\n", items[i].number);
}
return 0;
}
void changeValues(struct ITEM items[])
{
for (int i = 0; i < 10; i++)
{
items[i].number += 5;
}
}
答
可以 '通过作为参考' 通过使指针地址。
下面是一个例子:
调用我的主要它看起来像功能时int main(void)
{
char *pA; /* a pointer to type character */
char *pB; /* another pointer to type character */
puts(strA); /* show string A */
pA = strA; /* point pA at string A */
puts(pA); /* show what pA is pointing to */
pB = strB; /* point pB at string B */
putchar('\n'); /* move down one line on the screen */
while(*pA != '\0') /* line A (see text) */
{
*pB++ = *pA++; /* line B (see text) */
}
*pB = '\0'; /* line C (see text) */
puts(strB); /* show strB on screen */
return 0;
}
“changeValues(项目);” ? –
谢谢。最佳答案。我的程序正在工作,我按时提交了作业。 –