无法在 C 中使用 strcpy 从指针数组复制字符串?

标签 c undefined-behavior strcpy string-literals

<分区>

我正在做一个练习,其中字符指针数组用作存储单词的方式。我不明白为什么我不能使用“strcpy”将单词“hoi”复制到主函数中数组的第二个元素。当我编译代码时,我在 CodeBlocks 中收到消息“程序已停止工作”。

函数“numberOfWordsInDict”和“printDict”工作正常。

提前致谢。

int numberOfWordsInDict(char **dict)
{
    int i, cnt = 0;
    for(i = 0; i < 10; i++)
    {
        if(dict[i] != NULL)
        {
            cnt++;
        }
    }
    return cnt;
}

void printDict(char **dict)
{
    int i = 0;
    printf("Dictionary:\n");
    if(numberOfWordsInDict(dict) == 0)
    {
        printf("The dictionary is empty.\n");
    } else
    {
        for(i = 0; i < 10; i++)
        {
            printf("- %s\n", dict[i]);
        }
    }
}

int main()
{
    char *dict[10] = {
            "aap", "bro ", "jojo", "koe", "kip", 
            "haha", "hond", "    drop", NULL,NULL};

    char *newWord1 = "hoi";
    printDict(dict);
    strcpy(dict[1], newWord1);
    printDict(dict);

    return 0;
}

最佳答案

数组 dict 是指向字符串文字的指针数组。

在这个声明中

strcpy(dict[1],newWord1);

您正在尝试将一个字符串文字复制到另一个字符串文字中。

字符串文字在 C 和 C++ 中是不可修改的。任何修改 strig 文字的尝试都会导致程序出现未定义的行为。

来自 C 标准(6.4.5 字符串文字)

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

如果要在其元素中复制字符串文字,或者动态分配字符数组的一维数组,则应声明一个二维字符数组。

程序可以如下所示

#include <stdio.h>
#include <string.h>

#define N   9

size_t numberOfWordsInDict( char dict[][N] )
{
    size_t n = 0;

    while ( *dict[n] ) ++n;

    return n;
}

void printDict( char dict[][N] )
{
    printf("Dictionary:\n");

    size_t n = numberOfWordsInDict( dict );
    if ( n == 0 )
    {
        printf("The dictionary is empty.\n");
    } 
    else
    {
        for ( size_t i = 0; i < n; i++ )
        {
            printf( "- %s\n", dict[i] );
        }
    }
}

int main(void) 
{
    char dict[10][9] = 
    {
        "aap", "bro ", "jojo", "koe", "kip", "haha", "hond", "    drop"
    };
    char *newWord1 = "hoi";

    printDict(dict);
    strcpy(dict[1], newWord1);
    printDict(dict);

    return 0;
}

程序输出为

Dictionary:
- aap
- bro 
- jojo
- koe
- kip
- haha
- hond
-     drop
Dictionary:
- aap
- hoi
- jojo
- koe
- kip
- haha
- hond
-     drop

或者您可以使用可变长度数组。

请记住,根据 C 标准,不带参数的函数 main 应声明为

int main( void )

关于无法在 C 中使用 strcpy 从指针数组复制字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45615939/

相关文章:

c - 内存中的 strcpy 和字符串表示

c - 实现 session 管理

c - 如何实现与push相反的功能?

c - 将二维数组中的所有非零项保存到另一个一维数组中

c++ - C++20 的分支需要二进制补码

c - C语言中strcpy的使用

c - 文件的结构和输入

C:类型转换成不同尺寸的结构

java - Java 是否像 C++ 那样具有未定义的行为?

c - C 中的结构,错误为 "no member named..."