我在一个练习中被难住了几个小时,我必须使用函数在结构内构建一个数组并打印它。在我当前的程序中,它可以编译,但在运行时崩溃。
#define LIM 10
typedef char letters[LIM];
typedef struct {
int counter;
letters words[LIM];
} foo;
int main(int argc, char **argv){
foo apara;
structtest(apara, LIM);
print_struct(apara);
}
int structtest(foo *p, int limit){
p->counter = 0;
int i =0;
for(i; i< limit ;i++){
strcpy(p->words[p->counter], "x");
//only filling arrays with 'x' as an example
p->counter ++;
}
return;
我确实相信这是由于我错误地使用/组合了指针。我尝试过调整它们,但要么产生“不兼容类型”错误,要么数组看起来是空白的
}
void print_struct(foo p){
printf(p.words);
}
我尚未成功进入 print_struct 阶段,但我不确定 p.words 是否是要调用的正确项目。在输出中,我希望函数返回 x 的数组。 如果我犯了某种严重的“我应该已经知道这个”C 错误,我提前道歉。感谢您的帮助。
最佳答案
structest() 的第一个参数被声明为 foo 类型的指针。
int structtest(foo *p, int limit)
在 main 中,您没有传递指向 foo 变量的指针,您只是传递了 foo 变量。
structtest(apara, LIM);
尝试将指针传递给 foo 变量,如下所示:
structtest(&apara, LIM);
关于c - 从结构打印数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12540388/