在下面的代码中,我应该如何在C中使用一系列结构的指针?
我有一个更复杂的项目,我(尽可能多地)将我的问题简化为您可以在此处看到的代码。
我怀疑问题是围绕文件BC中的函数create_b()和/或从文件AC调用此函数时。 还是我的X和Y也应该是指针? 如您所知,我只是在学习C编程,任何帮助/解释都将不胜感激。
BH:
#ifndef B_H
#define B_H
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct B B;
typedef B *B_ptr;
struct B
{
int x;
int y;
};
B_ptr create_B(int x, int y);
#endif
BC:
#include "B.h"
B_ptr create_B(int x, int y) {
B_ptr b = (B_ptr)malloc(sizeof(B));
b->x;
b->y;
return b;
}
AH:
#ifndef A_H
#define A_H
#include "B.h"
typedef struct A A;
typedef A *A_ptr;
struct A
{
B_ptr *list_of_10_pointers;
};
A_ptr create_A();
#endif
AC:
#include "A.h"
A_ptr create_A()
{
A_ptr a = (A_ptr)malloc(sizeof(A));
if (!a)
return NULL;
B_ptr *list = (B_ptr *)malloc(10 * sizeof(B_ptr));
if (!list)
return NULL;
a->list_of_10_pointers = list;
for (size_t i = 0; i < 10; i++)
{
// list[i] = (B_ptr)malloc(sizeof(B));
list[i] = create_B(i+1, i+2);
}
return a;
}
MAIN.C:
#include <stdio.h>
#include "A.h"
int main(int argc, char **argv)
{
A_ptr a = create_A();
for (size_t i = 0; i < 10; i++)
{
printf("x=%d\n", a->list_of_10_pointers[i]->x);
printf("y=%d\n", a->list_of_10_pointers[i]->y);
}
return 0;
}
编译: GCC Main.C AC BC -O
输出输出:
x=0
y=0
x=0
y=0
.
.
.
x=0
y=0
I have a more complex project, I simplified (as much as I could) my problem into the code you can see here.
I suspect the problem is around the function create_B() in file B.c, and/or when I call this function from the file A.c .
Or maybe my x and y also should be pointers?
As you can tell I am just learning C programming, any help/explanation would be greatly appreciated.
B.h:
#ifndef B_H
#define B_H
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct B B;
typedef B *B_ptr;
struct B
{
int x;
int y;
};
B_ptr create_B(int x, int y);
#endif
B.c:
#include "B.h"
B_ptr create_B(int x, int y) {
B_ptr b = (B_ptr)malloc(sizeof(B));
b->x;
b->y;
return b;
}
A.h:
#ifndef A_H
#define A_H
#include "B.h"
typedef struct A A;
typedef A *A_ptr;
struct A
{
B_ptr *list_of_10_pointers;
};
A_ptr create_A();
#endif
A.c:
#include "A.h"
A_ptr create_A()
{
A_ptr a = (A_ptr)malloc(sizeof(A));
if (!a)
return NULL;
B_ptr *list = (B_ptr *)malloc(10 * sizeof(B_ptr));
if (!list)
return NULL;
a->list_of_10_pointers = list;
for (size_t i = 0; i < 10; i++)
{
// list[i] = (B_ptr)malloc(sizeof(B));
list[i] = create_B(i+1, i+2);
}
return a;
}
Main.c:
#include <stdio.h>
#include "A.h"
int main(int argc, char **argv)
{
A_ptr a = create_A();
for (size_t i = 0; i < 10; i++)
{
printf("x=%d\n", a->list_of_10_pointers[i]->x);
printf("y=%d\n", a->list_of_10_pointers[i]->y);
}
return 0;
}
To compile:
gcc Main.c A.c B.c -o out
Output:
x=0
y=0
x=0
y=0
.
.
.
x=0
y=0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编译发出这些警告:
几乎直接导致更改
bc
:然后输出变为:
Compiling gives these warnings:
That leads almost directly to changing
B.c
to this:Then the output becomes: