C字符串函数调用,按值传递还是引用?

Pau*_*ate 3 c string parameter-passing

我无法弄清楚发生了什么,我认为C是值得传递但是这个简单的功能让我对它的工作方式感到困惑.

 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>

 void testFunc(char string1[])
 {
   char string2[50] = "the end";
   strcat(string1, string2);
   printf("in func %s \n", string1);
 }

 void main()
 {
    char string1[50] = "the start";
    printf("%IN MAIN %s \n", string1);
    testFunc(string1);
    printf("IN MAIN %s \n", string1);
 }
Run Code Online (Sandbox Code Playgroud)

令人困惑的输出是:

在主要开始

在FUNC开始

在主要开始

那么这里发生了什么?C是否真的传递了char数组的地址而不是复制它的值?我以为这就是char*表现不怎么样char[]

nos*_*nos 9

您无法将数组的副本传递给函数.当您使用数组的名称时,它将计算为指向数组中1.元素的指针(或者通常所说的,它会衰减为指针.).除非在sizeof&运算符中使用数组名称,否则会发生这种情况.

所以,你将指向数组的1.元素的指针传递给你 testFunc()

 testFunc(string1);
Run Code Online (Sandbox Code Playgroud)

与做完全一样

 testFunc(&string1[0]);
Run Code Online (Sandbox Code Playgroud)

此外,在函数参数列表中,char[]实际上意味着char *

这3个声明完全相同

void testFunc(char *string1);
void testFunc(char string1[]);
void testFunc(char string[111]);
Run Code Online (Sandbox Code Playgroud)

如果您不想更改传入的字符串,请使用以下内容:

例如

void testFunc(char string1[])
{  
  char string2[50]; 
  const char *end = "the end"; 
  strcpy(string2, string1); 
  strcat(string2, end);
Run Code Online (Sandbox Code Playgroud)

(并且在使用strcpy/strcat时要清醒,很容易溢出数组这样做)


Tho*_*thy 5

C 总是按值传递参数,但字符串与其他数组一样,被转换为指向其第一个元素的指针,然后传递该指针。按价值。