我的函数没有按预期返回一个字符串,但它确实在for循环之前返回,如果我将return语句放在循环中,甚至会返回一个字符串,但之后似乎忽略了。我在完全失去了为什么它在循环之后没有返回任何东西。这是我的代码:
char * encode(char *plaintext, char *key){
char *message, *keyStr, *crypt;
char str[0], letter;
int keysize, i, num, n, plainInput[sizeof(plaintext)],
keyInt[sizeof(plaintext)], keyAndMessage[sizeof(plaintext)];
unsigned size;
size = (unsigned)strlen(plaintext);
keysize = (unsigned)strlen(key);
if(size != keysize){
printf("the key size is: %d\n", keysize);
printf("the plain text size is %d\n", size);
return "Key and Plaintext Size Mismatch.";
}
message = malloc(size);
keyStr = malloc(size);
crypt = malloc(size);
for(i = 0; i < size; i++){
// convert plaintext to ints
letter = plaintext[i]; // could be any upper or lower case
str[0] = letter; // place char into new memory location
num = strtol( str, NULL, 36 ) - 10; // convert the letter to a number
plainInput[i] = num; // store each number in an array ->
numInput
// convert keys to ints
letter = key[i]; // could be any upper or lower case
str[0] = letter; // place char into new memory location
num = strtol( str, NULL, 36 ) - 10; // convert the letter to a number
keyInt[i] = num; // store each number in an array ->
keyAndMessage[i] = (keyInt[i] + plainInput[i]) % 27;
// convert key to ascii for debugging only
keyStr[i] = (char)keyInt[i]+65;
// convert message to ascii text
message[i] = (char)plainInput[i]+65;
// combine message and key
plaintext[i] = (char)keyAndMessage[i]+65;
}
printf("the original message is: %s\n", message);
printf("the key is : %s\n", key);
printf("the crypt is : %s\n", plaintext);
printf("the size of origin is: %lu\n", sizeof(message));
printf("the size of key is: %lu\n", sizeof(key));
printf("the size of crypt is: %lu\n", sizeof(plaintext));
return plaintext;
答案 0 :(得分:0)
@BLUEPIXY提出了一个好点...可能最好的解决方案是先定义size
,然后将其用于数组大小(使用size+1
以留出空间来终止null):
char * encode(char *plaintext, char *key){
char *message, *keyStr, *crypt;
size_t size = strlen(plaintext);
int plainInput[size+1], keyInt[size+1], keyAndMessage[size+1];
:
:
但是你还有另外一个问题:你已经将str
定义为长度为0的数组,当它应该是长度为2时...一个用于字母,一个用于终止空字符。< / p>
char str[2];
如果您直接使用字符编码,那么转换会更简单(也更有效):
num = toupper(letter) - 'A'; // convert the letter to a number
此外,您在malloc
s中不允许空格终止null,并且您没有将放入终止空值,因此您正在打印未终止的字符串...这会产生不确定的行为。按如下方式更改malloc
:
message = malloc(size+1);
keyStr = malloc(size+1);
crypt = malloc(size+1);
并确保在尝试打印之前终止字符串:
message[size] = 0;
keyStr[size] = 0;
crypt[size] = 0;
哦,正如前面所指出的,sizeof只会给你指针的大小(在最后的printf
中),而不是字符串的大小。您需要再次strlen
。
还有一件事......你的函数试图修改传入的字符串(plaintext
),这是一个坏主意,因为它可能是一个常量字符串。最好将新字符放入malloc
ed缓冲区,与message
,et.al一样。此外,你忽略了释放你的malloc
ed缓冲区...内存泄漏!
希望这会让你更接近!