c++ - 将 C++ 代码转换为 C、结构数组

标签 c++ c arrays struct

我正在将 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[]));
}

这应该能让您了解我正在尝试做什么。问题:

  1. C++ 代码中的 sum 是 C++ sum 函数,还是Pointstruct`?
  2. 对于在 C 中分配内存,我认为我的方法不起作用。我应该做一个for循环来mallocA[]的每个索引吗? (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;

然后回到你的问题:

  1. Is sum in the c++ code the c++ sum function, or is it a Point struct?

它是一个Point类型变量。

  1. 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/

相关文章:

c++ - Qt中如何按区域填充不同颜色段的圆角矩形?

c - 搜索缺失号码 - 简单示例

c++ - MFC——圆形按钮

c++ - 生成库版本和构建版本

c++ - 结构成员内存布局

java - 寻找一种在 Java 中将 boolean 值更改为 boolean 数组的方法

c - 为什么我的 C 程序的输出不正确?

c++ - C++ 中具有十六进制值的数组

c++ - GUI 调试器和终端调试器之间的区别

c++ - 模板参数子类型的使用(进阶案例)