我有两个代码:vector_add.c
和 vector_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/