英文:
How to print variable name in function in C
问题
I want to print the name of a 2D matrix I take as input in a function.
I tried using this I found on the internet:
#include <stdio.h>
#define VariableName(var) #var
void saddle(int a[][100], int m, int n)
{
printf("The saddle points of the matrix %s are: \n", VariableName(a));
}
But on every function call I get the name as a
instead of the matrix I
entered, eg. A
, B
, or C
.
How to get past this?
英文:
I want to print the name of a 2D matrix I take as input in a function.
I tried using this I found on the internet:
#include <stdio.h>
#define VariableName(var) #var
void saddle(int a[][100], int m, int n)
{
printf("The saddle points of the matrix %s are: \n", VariableName(a));
}
`
But on every function call I get the name as a
instead of the matrix I
entered, eg. A
, B
, or C
.
How to get past this?
答案1
得分: 4
VariableName(var)
函数在您的代码中始终生成字符串"a"
。矩阵的名称仅在调用处知道,因此您应该将其作为额外参数传递,并且您可以在那里使用相同的宏来创建字符串:
void saddle(int a[][100], int m, int n, const char *name)
{
printf("矩阵 %s 的鞍点为:\n", name);
}
void print_matrix(int a[][100], int m, int n, const char *name)
{
printf("矩阵 %s 的内容为:\n", name);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; i++)
printf(" %3d", a[i][j]);
printf("\n");
}
}
int main(void)
{
int matrix1[10][100] = { 0 };
int matrix2[10][100] = { 0 };
saddle(matrix1, 10, 10, VariableName(matrix1));
saddle(matrix2, 10, 10, VariableName(matrix2));
print_matrix(matrix1, 10, 10, VariableName(matrix1));
print_matrix(matrix2, 10, 10, VariableName(matrix2));
return 0;
}
英文:
VariableName(var)
always produces the string "a"
in your code. The name of the matrix is only known at the calling site, so you should pass it as an extra argument and you can use the same macro there to create the string:
#include <stdio.h>
#define VariableName(var) #var
void saddle(int a[][100], int m, int n, const char *name)
{
printf("The saddle points of the matrix %s are:\n", name);
}
int main(void)
{
int matrix[100][100];
saddle(matrix, 100, 100, VariableName(matrix));
return 0;
}
Using "matrix"
instead of VariableName(matrix)
seems simpler, but here is a more advanced version where the matrix name or expression is passed implicitly:
#include <stdio.h>
#define VariableName(var) #var
#define saddle(a,m,n) (saddle)(a, m, n, VariableName(a))
#define print_matrix(a,m,n) (print_matrix)(a, m, n, VariableName(a))
void (saddle)(int a[][100], int m, int n, const char *name)
{
printf("The saddle points of the matrix %s are:\n", name);
}
void (print_matrix)(int a[][100], int m, int n, const char *name)
{
printf("Contents of matrix %s:\n", name);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; i++)
printf(" %3d", a[i][j]);
printf("\n");
}
}
int main(void)
{
int matrix1[10][100] = { 0 };
int matrix2[10][100] = { 0 };
saddle(matrix1, 10, 10);
saddle(matrix2, 10, 10);
print_matrix(matrix1, 10, 10);
print_matrix(matrix2, 10, 10);
return 0;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论