首页 > 解决方案 > 关于 C 中的字符串(作为 cs50 中的变量)的问题

问题描述

如果您有一些字符串(作为来自 的变量类型),我们假设它是字符串 S,即“AAA”。您可以自由更改单个字符。喜欢:

for(int i=0; i<3; i++)
{
    S[i]++
}

我猜这会让它成为“BBB”。因此,在 cs50 课程中,我们得到了字符串函数,char *代码如下:

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

int main(void)
{
    // Get a string
    char *s = get_string("s: ");

    // Allocate memory for another string
    char *t = malloc(strlen(s) + 1);

    // Copy string into memory
    for (int i = 0, n = strlen(s); i <= n; i++)
    {
        t[i] = s[i];
    }

    // Capitalize copy
    t[0] = toupper(t[0]);

    // Print strings
    printf("s: %s\n", s);
    printf("t: %s\n", t);
}

这实际上是将一个字符串复制到另一个字符串,而不仅仅是制作另一个指向字符串起始字符的链接副本,而是制作另一个具有相同填充的字符串,只是我们将第一个字母大写的区别。所以,我有一个想法,我为什么要使用这个新的malloc(strlen(s) + 1). 如果我需要另一个字符串以仅创建一些内存罐的方式出现,为什么我不能只创建带有任何填充的新字符串。像这样:

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

int main(void)
{
    // Get a string
    string s = get_string("s: ");

    // Let`s consider we know exact size of s we are getting, so we are creating the string of same size, just for question purposes
    string t = "qooq";

    // Copy string into memory
    for (int i = 0, n = strlen(s); i <= n; i++)
    {
        t[i] = s[i];
    }

    // Capitalize copy
    t[0] = toupper(t[0]);

    // Print strings
    printf("s: %s\n", s);
    printf("t: %s\n", t);
}

此时它不起作用,它可以编译,但是当它进入 for 循环时会显示一些神秘的错误。那么我基本上错在哪里?我错过了什么吗?我可以对字符串中的字符做任何我想做的事情,那么为什么我不能只给字符赋予另一个字符的价值t[i] = s[i]???

标签: cstringcs50

解决方案


推荐阅读