首页 > 解决方案 > C中连接变量和常量之间的区别

问题描述

我试图弄清楚为什么 C 会这样做。这是一个非常简单的字符串连接代码,但根据 strcat 中的内容,我会得到非常不同的输出。

有人可以对此有所了解吗?

// With all declared variables
char * hello = "HELLO";

char * world = "WORLD";

char * space = " ";

char * say_hello(){
  char * out = "";
  strcat(out,hello);
  strcat(out,space);
  strcat(out,world);
  return out;
}

main(){
   puts(say_hello()); 
}

// outputs "HELLO WORLD"
// With all hello as declared variable

char * hello = "HELLO";

char * say_hello(){
  char * out = "";
  strcat(out,hello);
  strcat(out," ");
  strcat(out,"WORLD");
  return out;
}

main(){
   puts(say_hello()); 
}

// outputs "HELLOELLOLOELLO"
// With all hello and world as declared variable

char * hello = "HELLO";

char * world = "WORLD";

char * say_hello(){
  char * out = "";
  strcat(out,hello);
  strcat(out," ");
  strcat(out,world);
  return out;
}

main(){
   puts(say_hello()); 
}

// outputs "HELLOELLOWORLD"
// With all constants

char * say_hello(){
  char * out = "";
  strcat(out,"HELLO");
  strcat(out," ");
  strcat(out,"WORLD");
  return out;
}

main(){
   puts(say_hello()); 
}

// outputs "HELLO WORLD"

标签: c

解决方案


所有代码都是无效且危险的。

首先,禁止修改字符串文字,并且尝试这样做会调用未定义的行为strcat将修改作为第一个参数传递的字符串,因此您不能在那里传递字符串文字(或指向字符串文字的指针)。

其次,""是单元素数组{'\0'}。它无法存储由连接创建的字符串。您必须分配足够的空间。

请注意,非静态本地数组的生命在从函数返回时结束,因此您必须动态或静态分配。

动态分配:

#include <stdlib.h>

char * say_hello(){
  char * out = calloc(32, sizeof(*out)); /* allocate */
  if (out == NULL) exit(1); /* check if allocation succeeded */
  strcat(out,hello);
  strcat(out,space);
  strcat(out,world);
  return out;
}

静态分配(警告:这不是线程安全的):

char * say_hello(){
  static char out[32];
  out[0] = '\0';
  strcat(out,hello);
  strcat(out,space);
  strcat(out,world);
  return out;
}

推荐阅读