简体   繁体   English

这个例子应该如何工作? 它对我来说是错误的

[英]How is this example supposed to work? It errors for me

I found this example at https://en.cppreference.com/w/c/string/byte/strcpy我在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
}

Using nvcc compiler, I get an error on the line char dst[strlen(src) + 1];使用 nvcc 编译器,我在char dst[strlen(src) + 1];行出现错误"expression must have a constant value." “表达式必须有一个常数值。”

Using Visual C++, I get that error and another error, "C++ a value of type cannot be used to initialize an entity of type," on the line char *src = "Take the test.";使用 Visual C++,我收到该错误和另一个错误,“C++ 类型的值不能用于初始化类型的实体”,位于char *src = "Take the test.";

If I compile and run it on the site, it's fine.如果我在网站上编译并运行它,那很好。

This feature is called "flexible array member" or in some cases "variable length arrays".此功能称为“灵活数组成员”或在某些情况下称为“可变长度数组”。 It is supported in 'c' starting with 'c99' standard.它在以 'c99' 标准开头的 'c' 中受支持。 gcc and microsoft 'c' supoorted it before the standard as well. gcc 和 microsoft 'c' 在标准之前也支持它。

c++ in general does not support this feature. c++ 一般不支持此功能。 Some support was added in c++14 requireing simple expressions as array indexes.在 c++14 中添加了一些支持,需要简单的表达式作为数组索引。

So, you might be able to compile it with a 'c' compiler which does support c99 or later standards.因此,您可以使用支持 c99 或更高标准的“c”编译器来编译它。 Some specific qualifiers could be needed at the compilation command line as well.在编译命令行中也可能需要一些特定的限定符。

The easiest way to work around it in a portable way would be using dynamic array allocation with malloc:以可移植方式解决它的最简单方法是使用 malloc 的动态数组分配:

 char *dst = malloc(strlen(src) + 1);
 strcpy(dst, src);

and later use strlen(dst) instead of the sizeof dst ;然后使用strlen(dst)而不是sizeof dst

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM