有多少种方法可以将char数组传递给C函数? [英] How many ways are there to pass char array to function in C?

查看:109
本文介绍了有多少种方法可以将char数组传递给C函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • foo(char *s)
  • foo(char *s[ ])
  • foo(char s[ ])
  • foo(char *s)
  • foo(char *s[ ])
  • foo(char s[ ])

所有这些有什么区别?

有什么方法可以修改作为参数传递的数组元素,就像我们使用&传递intfloat并修改实际参数的值一样? /p>

Is there any way in which I will be able to modify the elements of the array which is passed as argument, just as we pass int or float using & and value of actual arguments gets modified?

推荐答案

在C语言中,无法按值传递数组.您列出的每个有效解决方案(不幸的是不包括#2)将不仅让您使用,而且还会迫使您修改原始数组.

It is not possible in C to pass an array by value. Each working solution that you listed (which unfortunately excludes #2) will not only let you, but force you to modify the original array.

由于自变量衰减,foo(char* s)foo(char s[])彼此完全等效.在这两种情况下,都使用名称传递数组:

Because of argument decay, foo(char* s) and foo(char s[]) are exactly equivalent to one another. In both cases, you pass the array with its name:

char array[4];
foo(array); // regardless of whether foo accepts a char* or a char[]

在两种情况下,数组都将转换为指向其第一个元素的指针.

The array, in both cases, is converted into a pointer to its first element.

指针到数组的解决方案不太常见.它需要以这种方式进行原型设计(注意*s周围的括号):

The pointer-to-array solution is less common. It needs to be prototyped this way (notice the parentheses around *s):

void foo(char (*s)[]);

没有括号,您需要一个char指针数组.

Without the parentheses, you're asking for an array of char pointers.

在这种情况下,要调用该函数,您需要传递数组的地址:

In this case, to invoke the function, you need to pass the address of the array:

foo(&array);

每次访问数组元素时,还需要从foo解引用指针:

You also need to dereference the pointer from foo each time you want to access an array element:

void foo(char (*s)[])
{
    char c = (*s)[3];
}

就那样,并不是特别方便.但是,它是唯一的形式,它允许您指定一个数组长度,您可能会发现这很有用.这是我个人的最爱之一.

Just like that, it's not especially convenient. However, it is the only form that allows you to specify an array length, which you may find useful. It's one of my personal favourites.

void foo(char (*s)[4]);

然后,如果您尝试传递的数组不完全是4个字符,则编译器将警告您.此外,sizeof仍可以按预期工作. (明显的缺点是数组必须具有确切数量的元素.)

The compiler will then warn you if the array you try to pass does not have exactly 4 characters. Additionally, sizeof still works as expected. (The obvious downside is that the array must have the exact number of elements.)

这篇关于有多少种方法可以将char数组传递给C函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆