我正在将C++代码转换为C进行练习(我们现在只是在学习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 function, or is it a
点struct`?
- 为了在C中分配内存,我不认为我的方法有效。我应该做一个for循环哪里它是
malloc
s A []的每个索引? (A应该是数组Point
struct
s)。
任何援助将不胜感激。
编辑:得到了代码的上下文。
这里是整个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++代码不完整,没有多大意义。你能发布一些(最小的)真实代码吗? – juanchopanza 2014-09-19 15:54:15