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



我在运行此代码时收到以下错误:

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("%sn", salt);
}
else
{
printf("ERRORnUsage: ./crack hashn");
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);

使用 substr 函数从给定位置获取字符数并分配给另一个字符串

char src[] = "substr function Implementation";
int start = 7;
int no_of_char = 12;
char* dest = substr(src, start, no_of_char);
printf("%sn", dest);

最新更新