【发布时间】:2021-05-07 23:55:31
【问题描述】:
我在https://en.cppreference.com/w/c/string/byte/strcpy找到了这个例子
#define __STDC_WANT_LIB_EXT1__ 1
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *src = "Take the test.";
// src[0] = 'M' ; // this would be undefined behavior
char dst[strlen(src) + 1]; // +1 to accomodate for the null terminator
strcpy(dst, src);
dst[0] = 'M'; // OK
printf("src = %s\ndst = %s\n", src, dst);
#ifdef __STDC_LIB_EXT1__
set_constraint_handler_s(ignore_handler_s);
int r = strcpy_s(dst, sizeof dst, src);
printf("dst = \"%s\", r = %d\n", dst, r);
r = strcpy_s(dst, sizeof dst, "Take even more tests.");
printf("dst = \"%s\", r = %d\n", dst, r);
#endif
}
使用 nvcc 编译器,我在char dst[strlen(src) + 1];“表达式必须有一个常量值”这一行得到一个错误。
使用 Visual C++,我得到了那个错误和另一个错误,“C++ 类型的值不能用于初始化类型的实体”,位于 char *src = "Take the test."; 行上
如果我在网站上编译并运行它,就可以了。
【问题讨论】:
-
你举的例子是C,不是C++。
-
这是标记为 C++,看起来您正在尝试使用 C++ 编译器,但您正在链接到 C 文档中的代码 sn-p。 C 和 C++ 不是同一种语言,并非所有有效的 C 都是有效的 C++。
-
无论如何,您看到的两个特定错误都与 C 和 C++ 有关,在 whether variable-length arrays are permitted 和 whether you can assign a string literal to a char* 上有所不同。
-
所以我不能使用nvcc?还是 Visual C++ 编译一个 .c 文件?
-
我不知道 nvcc 但是 Visual C++ 官方不支持很多 C 特性,例如你需要的这些。