在 C 编程中添加到数组时,printf 出现段错误

问题描述 投票:0回答:1

我正在学习 C 并尝试为编码挑战创建一个结构。它可以编译并看起来可以工作,但当我在 Linux 上运行它时会出现段错误。

在 Windows 上,它无法编译,错误为:'msvcrt.dll!ungetwc (未知来源:0) [未知/即时编译代码] (未知来源:0)'

有人能看出我做错了什么吗?

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

struct cypher {char key[3]; char value;};
struct cypher code_list[26];

int add_code_pair(char key[3], char value)
{
    struct cypher pair;
    strcpy(pair.key, key);
    pair.value = value;
    printf("The key is %s and the value is %s.\n", pair.key, pair.value);
    code_list[atoi(key)] = pair;
    return 0;
}

int main()
{
    add_code_pair("1", 'a');
    return 0;
}
c segmentation-fault
1个回答
0
投票

我不知道单个字符需要 %c 。现在工作完美。非常感谢。

感谢您建议我在打开所有警告的情况下进行编译。

patrick@durotar:~/c_programming$ cc cypher.c -Wall -o cypher cypher.c:在函数“add_code_pair”中: cypher.c:14:45:警告:格式“%s”需要“char *”类型的参数,但参数 3 的类型为“int”[-Wformat=] 14 | 14 printf("键是 %s,值是 %s。 ",pair.key,pair.value); | 〜^〜~~~~~~~~~ | | | |字符 * 整数 | %d 帕特里克@durotar:~/c_programming$

© www.soinside.com 2019 - 2024. All rights reserved.