将数组、固定大小的数组和数组的基地址作为函数参数传递的区别 [英] Difference between passing array, fixed-sized array and base address of array as a function parameter

查看:47
本文介绍了将数组、固定大小的数组和数组的基地址作为函数参数传递的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想将已知或未知大小的数组作为函数参数传递,我对使用哪种语法感到困惑.

I am confused about which syntax to use if I want to pass an array of known or unknown size as a function parameter.

假设我有这些变体:

void func1(char* str) {
    //print str
}

void func2(char str[]) {
    //print str
}

void func3(char str[10]) {
    //print str
}

使用其中每一种的优缺点是什么?

What are the pros and cons of using each one of these?

推荐答案

所有这些变体都是相同的.C 只是让您使用替代拼写,但即使是最后一个使用数组大小​​显式注释的变体也会衰减为普通指针.

All these variants are the same. C just lets you use alternative spellings but even the last variant explicitly annotated with an array size decays to a normal pointer.

也就是说,即使使用最后一个实现,您也可以使用任意大小的数组调用该函数:

That is, even with the last implementation you could call the function with an array of any size:

void func3(char str[10]) { }

func("test"); // Works.
func("let's try something longer"); // Not a single f*ck given.

不用说这应该被使用:它可能会给用户一种错误的安全感(哦,这个函数只接受长度为 10 的数组,所以我不需要检查我自己的长度").

Needless to say this should not be used: it might give the user a false sense of security ("oh, this function only accepts an array of length 10 so I don’t need to check the length myself").

正如 Henrik 所说,在 C++ 中的正确方法是使用 std::stringstd::string&std::string const&(取决于是否需要修改对象,以及是否要复制).

As Henrik said, the correct way in C++ is to use std::string, std::string& or std::string const& (depending on whether you need to modify the object, and whether you want to copy).

这篇关于将数组、固定大小的数组和数组的基地址作为函数参数传递的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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