[英]How can I add an int to a char in C
I'm trying to add an int to each char in a char array but I don't know how to do that.我正在尝试为 char 数组中的每个 char 添加一个 int ,但我不知道该怎么做。
void Offset(char sirDeCaractere[100], int x)
{
int i = 0;
while (sirDeCaractere[i] != '\0')
{
sirDeCaractere[i] += x;
i++;
}
printf("%c", sirDeCaractere[i]);
}
I've been trying to do something like this for a while, but I can't figure it out.我一直在尝试做这样的事情一段时间,但我无法弄清楚。 Written like this I don't think it will work due to pointer arithmetic, but I have no other ideas.像这样写我不认为它会由于指针运算而起作用,但我没有其他想法。
For example:例如:
Input:
sirDeCaractere = cuvant
x = 5
Output:
hz{fsy
How should I edit my code in order to achieve the desired output?我应该如何编辑我的代码以实现所需的 output?
Right now my program is crashing (as I said, because sirDeCaractere[i] += x; is pointer arithmetic).现在我的程序正在崩溃(正如我所说,因为 sirDeCaractere[i] += x; 是指针算术)。
Thanks.谢谢。
You want this:你要这个:
#include <stdio.h>
void Offset(char sirDeCaractere[100], int x)
{
int i = 0;
while (sirDeCaractere[i] != '\0')
{
sirDeCaractere[i] += x;
i++;
}
// remove this line, it makes no sense printf("%c", sirDeCaractere[i]);
}
int main(void)
{
char test[] = "ABCD";
Offset(test, 1);
printf("%s\n", test);
}
Output: Output:
BCDE
I guess the code you didn't show is something like this:我猜你没有显示的代码是这样的:
...
char *test = "ABCD";
Offset(test, 1);
...
or或者
Offset("ABCD", 1);
which will crash on most platforms.这将在大多数平台上崩溃。 Read this form more information: Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?阅读此表单更多信息: 为什么我在写入使用字符串文字初始化的“char *s”而不是“char s[]”时会出现分段错误?
Bonus:奖金:
Be aware that the [100]
below is useless:请注意,下面的[100]
是无用的:
void Offset(char sirDeCaractere[100], int x)
you can write:你可以写:
void Offset(char sirDeCaractere[], int x)
or:或者:
void Offset(char *sirDeCaractere, int x)
which do exactly the same thing.做同样的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.