c - 关于 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]
???
解决方案
推荐阅读
- c++ - 如何比较自定义类的 std::variant?
- scikit-learn - Scikit-learn PCA 预测时间序列;转换错误
- c# - WPF ControlTemplate - 为椭圆触发不同的背景颜色
- python - 逻辑回归 PMML 不会产生概率
- php - PHP 方法范围绑定
- android - ConstraintLayout 在底部工作表视图中无法正常工作
- xslt - 比较 2 个 XML 并进行排序
- excel - 如何使用VBA调整PowerPoint图表中的数据选择范围
- html - 为什么在Ubuntu18.04中html的默认打开方式设置为Visual Studio Code URL Handler
- angular - Angular 组件的 Input() 属性未定义