C语言中的局部作用域
我在C中有类似的内容:C语言中的局部作用域,c,scope,cs50,C,Scope,Cs50,我在C中有类似的内容: string getCipherText(string text, int key) { string cipherText = ""; printf("Plaintext: %s, key: %i\n", text, key); key = key % 26; for (int i = 0; i < strlen(text); i++) { if ((text[i] >
string getCipherText(string text, int key) {
string cipherText = "";
printf("Plaintext: %s, key: %i\n", text, key);
key = key % 26;
for (int i = 0; i < strlen(text); i++) {
if ((text[i] >= 'A' && text[i] <= 'Z') || (text[i] >= 'a' && text[i] <= 'z')) {
text[i] = (int) text[i] + key;
}
cipherText += text[i];
}
return cipherText;
}
为什么返回的密文字符串为空?for循环中的变量不是同一个吗?这是来自EdX的云IDE,在这里他们在中有一个字符串类型,假设字符串是char*的别名,cipherText+=text[i];不是连接字符串,而是移动指针
您应该分配一个缓冲区并将结果存储在那里,如下所示:
string getCipherText(string text, int key) {
size_t len = strlen(text):
string cipherText = malloc(len + 1);
if (cipherText == NULL) {
fputs("malloc() failed!\n", stderr);
return NULL;
}
printf("Plaintext: %s, key: %i\n", text, key);
key = key % 26;
for (int i = 0; i < len; i++) {
if ((text[i] >= 'A' && text[i] <= 'Z') || (text[i] >= 'a' && text[i] <= 'z')) {
text[i] = (int) text[i] + key;
}
cipherText[i] = text[i];
}
cipherText[len] = '\0';
return cipherText;
}
cipherText += text[i];
如果这是C,那么C语言中没有类型字符串 它可以通过typedef或其他技巧创建 但该语言不支持使用+=将字符串连接在一起,如下所示:
string getCipherText(string text, int key) {
size_t len = strlen(text):
string cipherText = malloc(len + 1);
if (cipherText == NULL) {
fputs("malloc() failed!\n", stderr);
return NULL;
}
printf("Plaintext: %s, key: %i\n", text, key);
key = key % 26;
for (int i = 0; i < len; i++) {
if ((text[i] >= 'A' && text[i] <= 'Z') || (text[i] >= 'a' && text[i] <= 'z')) {
text[i] = (int) text[i] + key;
}
cipherText[i] = text[i];
}
cipherText[len] = '\0';
return cipherText;
}
cipherText += text[i];
由于要直接修改text参数的内容,因此可以删除对ciphertext变量的所有引用,只需
return text;
最后。这样做的好处是,文本字符串已经存在于调用函数中,并且肯定在该调用函数的范围内。我认为名称字符串表示以下typedef名称
typedef char *string;
因此,在本宣言中
string cipherText = "";
声明了一个指向字符串文本的指针
所以在这个声明中
cipherText += text[i];
text[i] = (int) text[i] + key;
使用指针算法,将指向字符串文本的指针增加文本[i]的整数值。这是指针指向任何地方。指针指向的地方没有有效的对象。因此,函数调用未定义的行为
此外,该语句中还有另一个bug
cipherText += text[i];
text[i] = (int) text[i] + key;
因为如果右侧的表达式的行为与带符号的类型char相同,则会导致类型char溢出
在任何情况下,实现都与函数声明不对应
函数声明意味着必须在不创建任何其他字符数组的情况下就地更改传递的字符串
否则,函数参数应声明为const char*text,因为在创建原始字符串的修改副本的情况下,原始字符串本身不会被修改。这真的是C吗?可能是cs50.h,不是C++?这是对类型字符串的定义?你不能在C中添加到字符串中。任何人都会认为在学习C之前你已经学会了脚本语言,这样的操作是可能的。C不是那样的。您必须为字符串分配内存。你分配一个指向只读内存的指针,当你处理它的内容时,这可能会给你带来麻烦。这是他们的云IDE。它们在cs50.hAlso中有自己的字符串类型,text[i]+key;当总和超过127时可能会出现问题。对我来说,这是最简单的解决方案。谢谢感谢其他人对缓冲区和字符串类型的解释。我知道你在那里做了什么,但它违反了最小惊喜原则。返回一个字符串表明它是一个新字符串,与您传入的字符串不同。适当地修改字符串的技术是不返回任何内容。