我正在将 C++ 代码转换为 C 代码以进行练习(我们现在刚刚学习 C++),但我对这部分感到困惑。
首先,C++代码:
Point()
{
x = y = 0;
}
main()
{
const int N = 200;
Point *A = new Point[N], sum;
}
这是我的 C 版本:
struct Point //constructor
{
int x;
int y;
} Point;
main()
{
int N = 200;
Point* A = malloc(N * sizeof(*Point[]));
}
这应该能让您了解我正在尝试做什么。问题:
- C++ 代码中的
sum
是 C++sum 函数,还是
Pointstruct`?
- 对于在 C 中分配内存,我认为我的方法不起作用。我应该做一个for循环来
malloc
A[]的每个索引吗? (A 应该是一个Point
struct
数组)。
任何帮助将不胜感激。
编辑:被询问代码的上下文。
这是整个 C++ 程序:
#include <iostream>
// a point on the integer grid
struct Point
{
// constructor
Point()
{
x = y = 0;
}
// add point componentwise
void add(const Point &p)
{
x += p.x;
y += p.y;
}
// print to standard output
void print() const
{
std::cout << "[" << x << "," << y << "]" << std::endl;
}
// data
int x, y;
};
int main()
{
const int N = 200;
Point *A = new Point[N], sum;
for (int i=0; i < N; ++i) {
sum.print();
A[i].x = i; A[i].y = -i;
sum.add(A[i]);
}
sum.print();
delete [] A;
}
最终,我必须在 C 中模拟这一点。目前停留在我提出的问题上:回复:该行的作用是什么。从那时起,我发现我需要创建一个名为 sum 的 Point 结构,并在对其所有成员运行 add 函数后打印该结构。
最佳答案
在您的 C 版本中:
struct Point //constructor
{
int x;
int y;
} Point;
应该是:
typedef struct //constructor
{
int x;
int y;
} Point;
因为在您的例子中,您定义了一个名为 Point
的全局变量。
而且,C 编程语言也像 C++ 一样具有 const
关键字,因此您可以在 C 语言中执行此操作:
const int N = 200;
以及 C++ 代码:
Point *A = new Point[N], sum;
在C版本中,应该是:
Point *A = malloc(N * sizeof(Point)), sum;
但在此版本中,内存未初始化为零。
您可以使用calloc
函数而不是malloc
来分配内存并将其初始化为零:
Point *A = calloc(N, sizeof(Point)), sum;
然后回到你的问题:
- Is sum in the c++ code the c++ sum function, or is it a Point struct?
它是一个Point
类型变量。
- For allocating the memory in C, I don't think my method works. Should I do a for loop where it mallocs each index of A[]? (A should be an array of Point structs).
不,没有必要编写for
循环。 malloc
函数将完全按照您的要求执行。
关于c++ - 将 C++ 代码转换为 C、结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25937840/