简体   繁体   English

C将char数组传递给函数和指针

[英]C passing char array to a function and pointers

So, I'm having a difficult time wrapping my head around using arrays and pointers in functions.所以,我很难在函数中使用数组和指针。 I want to print the following array of chars using a function.我想使用函数打印以下字符数组。 I can print them outside the function with the for loop but when I pass the same code to the function, the function returns NULLS.我可以使用 for 循环在函数外打印它们,但是当我将相同的代码传递给函数时,函数返回 NULLS。 Could I get some insight on this?我可以对此有所了解吗?

#include <stdio.h>

void printNames(char arr[], int size);

int main()
{
    
    char *names[4] = {"Bruce", "Clark", "Barry", "Diana"};

    //changed a typo
    for(int i = 0; i < 4; i++)
    {
        printf("%s ", *(names + i));
    }

    printNames(names, 4);

    return 0;


}

void printNames(char arr[], int size)
{
    for(int i = 0; i < size; i++)
    {
        printf("%s ", *(arr + i));
    }


}

You're passing a variable of type char *[] , ie an array of pointers to char to a function expecting char * , ie a pointer to char.您正在传递一个char *[]类型的变量,即指向char的指针数组到期望char *的函数,即指向 char 的指针。 Also, inside of printNames , you're passing a single char to printf when the %s format specifier expects a char * .此外,在printNames内部,当%s格式说明符需要char *时,您将单个char传递给printf Your compiler should have warned you about both of these.您的编译器应该已经就这两种情况向您发出警告。

You need to change the definition of printNames to have the parameter type match what is passed in and to match what you want to pass to printf .您需要更改printNames的定义以使参数类型匹配传入的内容并匹配您想要传递给printf

void printNames(char *arr[], int size);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM