gpt4 book ai didi

c - 在 C 中,如何从字符串中取出两个字符,并将它们分配为自己的字符串?

转载 作者:行者123 更新时间:2023-11-30 16:08:20 24 4
gpt4 key购买 nike

运行此代码时出现以下错误:

UndefinedBehaviorSanitizer:DEADLYSIGNAL
==1074==ERROR: UndefinedBehaviorSanitizer: SEGV on unknown address 0x00000042acda (pc 0x000000422519 bp 0x7ffe697712d0 sp 0x7ffe697711f0 T1074)
==1074==The signal is caused by a WRITE memory access.
#0 0x422518 (/root/sandbox/crack+0x422518)
#1 0x7fb78fc7ab96 (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)
#2 0x402a79 (/root/sandbox/crack+0x402a79)

UndefinedBehaviorSanitizer can not provide additional info.
==1074==ABORTING
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <crypt.h>

int main(int argc, string argv[])
{
if (argc == 2)
{
string hash = argv[1];
string salt = "AB";
for (int i = 0; i < 2; i++)
{
salt[i] = hash[i]; // The error is here.
}
printf("%s\n", salt);
}
else
{
printf("ERROR\nUsage: ./crack hash\n");
return 1;
}
}

经过研究,我了解到你不能将一个数组中的字符分配为另一个数组中的字符,但是当我尝试时:

int j = hash[i]; // It worked here.
salt[i] = j; // The error is here.

还是没用。有人可以帮我解决这个问题吗?我需要将命令行参数中的前两个字符存储为它们自己的变量。

最佳答案

您使用 CS50 库和头文件。在string.h中,string被定义为char*string salt = "AB"; 定义一个指向文字字符串的指针。文字字符串是常量,不能修改。您需要一个字符数组,例如:

char salt[3];

另外,不要忘记在循环后的字符串末尾粘贴 0:

salt[i] = 0;

否则,你的字符串将不会被终止。更好的是,调用函数 strncpy 而不是编写自己的循环:

strncpy(salt, hash, (sizeof salt) - 1);

关于c - 在 C 中,如何从字符串中取出两个字符,并将它们分配为自己的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59367513/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com