[英]Passing a string array to a function using pointers
So I am trying to a pass a char array into a function and print it out and then return the array back. 因此,我试图将char数组传递给函数并打印出来,然后将数组返回。
Below is my main function. 下面是我的主要功能。 I am doing Binary Search Trees however Im just stuck on passing a char array.
我正在执行二进制搜索树,但是我只是停留在传递char数组。
int main()
{
BST tree = new_bst();
int noRecords;
int tfn;
char name[10];
char *test;
FILE *fileptr;
fileptr = fopen("welfare1.txt", "r");
fscanf(fileptr, "%d", &noRecords);
fscanf(fileptr, "%s", name);
fscanf(fileptr, "%d", &tfn);
insert_bst(&tree, tfn, &name);
}
And here is the insert BST function so far. 到目前为止,这里是insert BST函数。 I haven't implemented it yet as I can't pass the name field to my function, im using the printf as a test to see if it worked.
我还没有实现它,因为我无法将name字段传递给我的函数,我使用printf作为测试来查看它是否有效。
BSTNodePtr insert_bst_node(BSTNodePtr self, int n, char *name)
{
if (self == NULL)
{
TaxRecordPtr newRecord = new_record();
self = malloc(sizeof *self);
self->data = newRecord;
self->left = self->right = NULL;
printf("%c", name[0]);
}
Change 更改
insert_bst(&tree, tfn, &name);
to 至
insert_bst(&tree, tfn, name);
Except when it is the operand of the sizeof
or unary &
operators, or is a string literal used to initialize a character array in a declaration, an expression of type "N-elemement array of T
" will be converted ("decay") to an expression of type "pointer to T
", and the value of the expression will be the address of the first element of the array. 除非它是
sizeof
或一元&
运算符的操作数,或者是用于在声明中初始化字符数组的字符串文字,否则类型为“ T
N个元素数组”的表达式将被转换(“衰变”)为类型为“指向T
指针”的表达式,该表达式的值将是数组第一个元素的地址。
When you call 你打电话时
insert_bst(&tree, tfn, name);
the expression name
isn't the operand of the sizeof
or unary &
operators, so it "decays" to type char *
, which matches the type of the argument in the function definition. 表达式
name
不是sizeof
或一元&
运算符的操作数,因此它会“拒绝”键入char *
,该char *
与函数定义中参数的类型匹配。
When you call 你打电话时
insert_bst(&tree, tfn, &name);
the expression name
is the operand of the unary &
operator, so the conversion doesn't happen; 表达式
name
是一元&
运算符的操作数,因此不会发生转换; instead, the type of the expression is char (*)[10]
, or "pointer to 10-element array of char
", which doesn't match the type of the argument in the function definition. 相反,表达式的类型为
char (*)[10]
或“指向char
10个元素的数组的指针”,它与函数定义中的参数类型不匹配。
A char array is equivalent to a pointer to char. 一个char数组等效于一个指向char的指针。 So when referencing a char array, the desired type would be a double pointer to char
因此,在引用char数组时,所需的类型将是指向char的双指针
BSTNodePtr insert_bst_node(BSTNodePtr self, int n, char **name)
Anyway, there is no point to pass a pointer to the char array, you could just pass the char array itself 无论如何,没有必要将指针传递给char数组,您可以只传递char数组本身
insert_bst(&tree, tfn, name);
You won't be passing the char array by value, since an array is equivalent to a pointer. 您不会按值传递char数组,因为数组等效于指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.