我正在编写一个程序,它接受命令行参数和用户输入,并计算两个字符之间的差异(密码学)。我想将我的参数传递到程序中的变量中,但我无法这样做。
#include <stdio.h>
int main(int argc, char** argv) {
char plain[2];
char cipher[2]; /*locations of plain and cipher text*/
char *ppoint; /*pointers to plain and cipher*/
char *cpoint;
scanf("%s",plain);
*ppoint=plain[0]; /* ppoint points to 1st character in plain*/
cipher=argv[1]; /* cpoint points to first argument character*/
*cpoint=cipher[1];
printf("%s %d \n",ppoint,plain);
printf("%s %d \n",cpoint,cipher);
return 0;
}
对于第 14 行,我遇到了编译器错误, (cipher=argv[1];) “赋值中的类型不兼容” 我一直在尝试许多方法,例如类型转换,但我无法得到任何工作。
我希望程序的最后两行输出实际字符及其各自的 ASCII 值。请帮助我跨越这个障碍!
更新:
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv) {
char plain;
char *cipher; /*locations of plain and cipher text*/
int *ppoint; /*pointers to plain and cipher*/
int *cpoint;
scanf("%s",plain);
*ppoint=(int) plain; /* ppoint points to 1st character in plain*/
cipher=argv[1]; /* cpoint points to first argument character*/
*cpoint=(int) cipher;
printf("%s %d \n",plain);
printf("%s %d \n",cipher);
return 0;
}
我使用类型转换来修复任何编译器错误。然而,在运行程序并为“plain”输入值时,我遇到了段错误。我仔细观察了很长时间,但看不出这个内存错误发生在哪里。请帮忙。
最佳答案
您正在尝试将 char
指针分配给 char
数组,这是不允许的。您需要以其他方式复制该参数。例如,您可以使用 strcpy:
strcpy(cipher,argv[1]);
或者,如果您从不修改它,则可以将 cipher
设为 char
指针。
const char *cipher;
...
cipher = argv[1];
关于C:将参数传递给程序以将字符转换为 ASCII 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32684199/