c - 我如何概括这个我用来指定 vector 长度的宏?

标签 c

我有两个代码:vector_add.cvector_print.c .两者都要求我分配 vector 长度 N,作为使用 #define N (3) 的宏,其中 3 是长度。我同意 vector_add.c ,但我不想一概而论 vector_print.c适用于任何 vector 长度,然后稍后在另一个代码中分配 vector 长度。我尝试使用 #undef N以不同的方式,但我无法让它工作。

有没有人对我如何概括我的 vector_print 有任何建议?函数适用于任何 vector 长度,N?现在,我只是在使用 #define N (3)对于这两个文件,这对于长度为 3 的 vector 都适用。但我不想在 vector_print.c 中显式分配 vector 长度.我希望它适用于任何 N!

这是 vector_add.c :

#include <vector_print.h>
#include <stdio.h>

// vector length (fixed)

#define N (3)

// ----------------------------------------------------------------------
// vector_add
//
// returns the linear sum of the two vectors and puts them in another
// x: first vector
// y: second vector
// z: solution vector

void
vector_add(double *x, double *y, double *z)
{
  for (int i = 0; i < N; i++) {
    z[i] += x[i] + y[i];
  }
}

// ----------------------------------------------------------------------
// main
//
// test the vector_add() function

int
main(int argc, char **argv)
{
  double x[N] = { 1., 2., 3. };
  double y[N] = { 2., 3., 4. };
  double z[N] = {0.,0.,0.};
  vector_add(x, y, z);

  printf("x is ");
  vector_print(x);
  printf("y is ");
  vector_print(y);
  printf("z is ");
  vector_print(z);

  return 0;
}

这是 vector_print.c :

#include <stdio.h>

// vector length (fixed)

#define N (3)

// ----------------------------------------------------------------------
// vector_print
//
// prints the elements of an N-element array
// name: name of vector to print

void
vector_print(double *name)
{
  for (int i = 0; i < N; i++) {
    printf("%g ", name[i]);
  }
  printf("\n");
}

如有必要,这里是 vector_print.h :

#ifndef VECTOR_PRINT_H
#define VECTOR_PRINT_H

void vector_print(double *name);

#endif

最佳答案

只是在评论中传达解决方案。

你可以做的是像这样将长度传递给那些函数:

void vector_print(double *name, int len);
void vector_add(double *x, double *y, double *z, int len);

这将允许您像这样控制循环:

  for (int i = 0; i < len; i++) { // Note: i < len now, not N
    printf("%g ", name[i]);
  }

关于c - 我如何概括这个我用来指定 vector 长度的宏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54719485/

相关文章:

如果位置更改,代码会出现错误段错误(核心已转储)

c - 调用该函数时显示相同的随机数

c++ - 为 shell 输出重定向创建文件

c - 您如何获得具有 HID 的复合 USB Linux 设备来唤醒挂起的主机?

c++ - 转换 .wav 文件中的 RTP 序列负载

java - 在循环中使用 > 和 >= 之间是否存在任何性能差异

c - 生成c的函数调用

c - 从 C 文件中读取 64 位十六进制值

c - 作业 - 二叉搜索树 C

为 GTK+ 配置 Qt Creator