如何用字符串替换宏? [重复]

时间:2020-12-08 19:16:55

This question already has an answer here:

这个问题在这里已有答案:

#include <stdio.h>
#include <stdarg.h>
#define ammo "full"

int main()
{
  char a[100];
  a = ammo;
  printf("%s",a);
  return 0;
}

I am trying to replace #define ammo with "full" (string) and want to print it on the screen to check if it works but the code is not compiling.

我试图用“full”(字符串)替换#define ammo,并希望在屏幕上打印它以检查它是否有效但代码没有编译。

2 个解决方案

#1


2  

Instead of a=ammo; you should use strcpy(a,ammo); you should not use a direct assignment when you have strings, but use the C method strcpy to copy a string to another. it will work

而不是a = ammo;你应该使用strcpy(a,ammo);如果有字符串,则不应使用直接赋值,而是使用C方法strcpy将字符串复制到另一个字符串。它会工作

#2


2  

It's invalid to assign a C-string to an array (except when initializing, see below). You must "copy" the string to the array because the space is already allocated:

将C字符串分配给数组是无效的(初始化时除外,见下文)。您必须将字符串“复制”到数组,因为已分配空间:

strcpy(a, ammo);

Better yet, use a safer version of copy function:

更好的是,使用更安全的复制功能版本:

strncpy(a, ammo, sizeof(a) / sizeof(char));

Or directly assign it when initializing:

或者在初始化时直接指定它:

char a[100] = ammo;

Or, don't use array. Use a pointer instead:

或者,不要使用数组。改为使用指针:

char *a;
a = ammo;

Note you can't change the content of the string if you use a pointer.

请注意,如果使用指针,则无法更改字符串的内容。

#1


2  

Instead of a=ammo; you should use strcpy(a,ammo); you should not use a direct assignment when you have strings, but use the C method strcpy to copy a string to another. it will work

而不是a = ammo;你应该使用strcpy(a,ammo);如果有字符串,则不应使用直接赋值,而是使用C方法strcpy将字符串复制到另一个字符串。它会工作

#2


2  

It's invalid to assign a C-string to an array (except when initializing, see below). You must "copy" the string to the array because the space is already allocated:

将C字符串分配给数组是无效的(初始化时除外,见下文)。您必须将字符串“复制”到数组,因为已分配空间:

strcpy(a, ammo);

Better yet, use a safer version of copy function:

更好的是,使用更安全的复制功能版本:

strncpy(a, ammo, sizeof(a) / sizeof(char));

Or directly assign it when initializing:

或者在初始化时直接指定它:

char a[100] = ammo;

Or, don't use array. Use a pointer instead:

或者,不要使用数组。改为使用指针:

char *a;
a = ammo;

Note you can't change the content of the string if you use a pointer.

请注意,如果使用指针,则无法更改字符串的内容。