且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将多个字符串传递给函数C.

更新时间:2023-02-12 16:20:13

一些事情,首先如果你打算这样做,

A few things, first of all if you are going to do this,
void print_array(char *arr,int8_t cnt);
void print_array(char *arr,int8_t cnt) {}



***只做后一个,删除声明语句并保持定义(和声明)仅。其次,因为您已经知道如何传递字符串(这是字符数组)。像这样,


It is better to just do the later one, remove the declaration statement and keep the definition (and declaration) on only. Secondly, since you already know how to pass strings (which are array of characters). Like this,

print_array(char *arr, int8_t cnt) { }



是什么阻止你这样做?


What stops you from doing this?

print_arrays(char **arr, int8_t cnt) { } // cnt won't make much sense now.



请注意,我使用了指向指针的指针 [ ^ ]。这意味着,或者至少我可以说,在C语言上下文中,是一个数组数组。您可以在其上执行以下操作,然后,


Notice that I used a pointer to pointer[^] here. Which means, or at least I can say, in the C language context, an array of array. You can do the following on it, then,

char **array = { "Afzaal", "Ahmad", "Zeeshan" };
// print_arrays(array, 3);



最后,我实际上没有得到你想要的部分将指针分配给数组,因为你实际上得到指向数组的指针 。但是,这将使我们进入C ++领域,其中支持引用,并且据我所知,C不支持pass-by-reference,只传递值,这正是C函数看起来的原因像这样,


Finally, I didn't actually get the part where you wanted to assign the pointer to the array, because you actually get the pointer to the array. However, that would now take us in the realm of C++ where references are supported and as far as I can conclude, C doesn't support pass-by-reference, only pass-by-value and that is exactly why the C functions look like this,

void func(char *obj) {
   // Do something
}

int main() {
   int a = 25;
   func(&a);
} 



我会让你继续学习,不断尝试。我个人的建议是使用GCC编译器。这是一个很好的,我个人喜欢它。



在C和C ++中通过引用传递价值 - C ++论坛 [ ^ ]

C中的字符串 [ ^ ]

C Strings - Cprogramming.com [ ^ ]


I would move you onwards to learn something, keep trying. My personal recommendation is to use GCC compiler. That is a good one and I personally like it.

Passing value by reference in C and C++ - C++ Forum[^]
Strings in C[^]
C Strings - Cprogramming.com[^]


非常感谢您的回答,我昨晚因为正在搜索并查看有关此特定操作的练习或示例的电子书而感到害怕。我不能,然后今天早上我告诉了培训师,他马上解决了!这很简单。



Thank you very much for the answer, I freaked out last night because I was searching and looking into the eBooks for the exercise or example about this specific action. And I couldn't, then this morning I told the trainer about it and he solve it right away! It's very simple.

    void print_array(char *arr[],int8_t cnt);
    void print_array(char *arr[],int8_t cnt)
    {
        int8_t i;
        printf("Number of elements is: %d\n",cnt);
        for (i=0;i<cnt;i++)
        {
            printf("Elements of array: %s\n",arr[i]);
        }
    }

print_array(array_5,cnt5);