C 字符串中的无效初始值设定项

Invalid Initializer in C String

我正在用 C 语言测试一个大写到小写的转换器(我比较新),但我在主文件(附在下面)中遇到了一些问题。我可以添加 upperlower.c 代码,但我认为这与我的问题无关。我收到了一些无效的初始值设定项错误,但我会这样做。我附上了错误消息的图像。您还可以在代码中看到我已经注释掉了一些 strcpy 方法,因为它们导致了一些运行时分段错误。有谁知道发生了什么事? Error Message

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "upperlower.h"

#define SAMPLESTRING "AbCdEfGhIjKlMnOpQrStUvWxYz"

int main()
{
    char* lower[] = SAMPLESTRING;
    char* upper[] = SAMPLESTRING;

    // strcpy(*lower, SAMPLESTRING);
    // strcpy(*upper, SAMPLESTRING);

    ToLower(lower, lower);
    ToUpper(upper, upper);

    printf("Lower: %s\nUpper: %s\n", lower, upper);
}

键入 char * lower[N];,您要求编译器在字符数组上创建一个指针。

但您只需要一个字符数组:

char lower[] = SAMPLESTRING;
char upper[] = SAMPLESTRING;

您可能会感到困惑的部分是使用全局常量作为字符数组的值。

使用全局常量设置值等同于使用局部变量、字符串或字符数组设置值。

这些方法中的任何一个都应该足够了:

char array[] = globalvariable;
char array[] = localvariable;
char array[] = "this is a string";
char array[] = {'t','h','i','s',' ','i','s',' ','a',' ','s','t','r','i','n','g'}

如果你打算使用指针,那么你用来指向数组的数组变量不需要是一个数组,只是一个指针。

使用您的代码,将按如下方式执行:

char * lower;
char * upper;

来自C标准(6.7.9初始化)

14 An array of character type may be initialized by a character string literal or UTF−8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

那就是你可以声明一个字符数组并用像

这样的字符串文字来初始化它
char lower[] = SAMPLESTRING;

但是你声明了一个 char * 类型的指针数组而不是字符数组。在这种情况下,您需要将初始化程序括在大括号中,例如

char* lower[] = { SAMPLESTRING };

在上面的行中,声明了一个数组,其中有一个指针类型 char * 的元素指向字符串文字 SAMPLESTRING 的第一个字符。但是使用指针(数组的单个元素)您可能不会更改字符串文字。任何更改字符串文字的尝试都会导致未定义的行为。

考虑到 printf

的调用
printf("Lower: %s\nUpper: %s\n", lower, upper);

在使用格式字符串 "%s" 的地方,您似乎要准确地处理字符数组。否则你有 ro write

printf("Lower: %s\nUpper: %s\n", lower[0], upper[0]);

所以你需要写

char lower[] = SAMPLESTRING;
char upper[] = SAMPLESTRING;

char lower[] = { SAMPLESTRING };
char upper[] = { SAMPLESTRING };

而不是

char* lower[] = SAMPLESTRING;
char* upper[] = SAMPLESTRING;

在这种情况下 strcpy 的调用看起来像

strcpy( lower, SAMPLESTRING);
strcpy( upper, SAMPLESTRING);

尽管数组由于初始化已经包含此字符串文字。