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

In C, how do I take two characters from a string, and assign them as a string of their own?

我从 运行 这段代码中得到以下错误:

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);

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

char src[] = "substr function Implementation";

int start = 7;
int no_of_char = 12;

char* dest = substr(src, start, no_of_char);

printf("%s\n", dest);