所以我在C中定义了以下函数:
#include <stdio.h>
void encrypt(int size, unsigned char *buffer){
buffer[i] = buffer[i] + 1;
printf("%c",buffer[i]);
}
int main(){
encrypt(5,"hello");
}
我希望这会返回ifmmp
,但我会收到错误
“分段错误(核心转储)”。
如果我摆脱了线路
buffer[i] = buffer[i] + 1
和
printf("%c",buffer[i]+1)
然后我得到了理想的结果。但我想实际更改存储在该地址中的值。我怎么能这样做?
答案 0 :(得分:1)
您的代码中存在许多问题:
i
未初始化"hello"
转换为int
,因此请避免以此方式发送。而是看下面的代码您已发送论据size
但尚未使用它。
最后,使用循环递增数组中的每个值char *buffer
返回main()
末尾的值,因为您提到的返回类型为int
所以,这是代码
#include <stdio.h>
void encrypt(int size, char *buffer){
int i;
for(i=0;i<size;i++)
buffer[i] =(buffer[i]+1);
printf("%s",buffer);
}
int main(){
char s[]="hello";// total 5 charcters + '\0' character
encrypt(5,s);
return 0;
}
生成的输出符合要求。