C语言 将字符串传递给 C 中的函数 - 带或不带指针?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17131863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:42:34  来源:igfitidea点击:

Passing string to a function in C - with or without pointers?

cstringfunction

提问by Zen Cicevic

When I'm passing a string to the function sometimes I use

当我将字符串传递给函数时,有时我会使用

char *functionname(char *string name[256])

and sometimes I use it without pointers (for example:

有时我在没有指针的情况下使用它(例如:

char functionname(char string[256])

My question is,when do I need to use pointers ? Often I write programs without pointers and it works,but sometimes it doesn't.

我的问题是,我什么时候需要使用指针?我经常编写没有指针的程序并且它可以工作,但有时却没有。

回答by Adam Zalcman

The accepted convention of passing C-strings to functions is to use a pointer:

将 C 字符串传递给函数的公认约定是使用指针:

void function(char* name)

When the function modifies the string you should also pass in the length:

当函数修改字符串时,您还应该传入长度:

void function(char* name, size_t name_length)

Your first example:

你的第一个例子:

char *functionname(char *string name[256])

passes an array of pointers to strings which is not what you need at all.

传递一个指向字符串的指针数组,这根本不是你需要的。

Your second example:

你的第二个例子:

char functionname(char string[256])

passes an array of chars. The size of the array here doesn't matter and the parameter will decay to a pointer anyway, so this is equivalent to:

传递一个字符数组。此处数组的大小无关紧要,参数无论如何都会衰减为指针,因此这等效于:

char functionname(char *string)

See also this questionfor more details on array arguments in C.

有关C 中数组参数的更多详细信息,另请参阅此问题

回答by Nicola Musatti

Assuming that you meant to write

假设你打算写

char *functionname(char *string[256])

Here you are declaring a function that takes an array of 256 pointers to charas argument and returns a pointer to char. Here, on the other hand,

在这里,您声明了一个函数,该函数将一个包含 256 个指针的数组char作为参数并返回一个指向 char 的指针。在这里,另一方面,

char functionname(char string[256])

You are declaring a function that takes an array of 256 chars as argument and returns a char.

您正在声明一个函数,该函数将 256 chars的数组作为参数并返回 a char

In other words the first function takes an array of strings and returns a string, while the second takes a string and returns a character.

换句话说,第一个函数接受一个字符串数组并返回一个字符串,而第二个函数接受一个字符串并返回一个字符。

回答by Anickyan

An array is a pointer. It points to the start of a sequence of "objects".

数组是一个指针。它指向一系列“对象”的开始。

If we do this: ìnt arr[10];, then arris a pointer to a memory location, from which ten integers follow. They are uninitialised, but the memory is allocated. It is exactly the same as doing int *arr = new int[10];.

如果我们这样做:ìnt arr[10];,然后arr是一个指向内存位置的指针,后面跟着十个整数。它们未初始化,但已分配内存。这和做完全一样int *arr = new int[10];