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.

Below is my main function. I am doing Binary Search Trees however Im just stuck on passing a char array.

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

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.

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.

When you call

insert_bst(&tree, tfn, &name);

the expression name is the operand of the unary & operator, so the conversion doesn't happen; 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.


A char array is equivalent to a pointer to char. So when referencing a char array, the desired type would be a double pointer to 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

insert_bst(&tree, tfn, name);

You won't be passing the char array by value, since an array is equivalent to a pointer.

链接地址: http://www.djcxy.com/p/72158.html

上一篇: 打印字符串填充循环在C?

下一篇: 使用指针将字符串数组传递给函数