[英]Printf won't print string & debug shows that the string disappears after it reaches printf
我在 CS50 設置的這個問題上遇到了一些問題。 我想要做的是加密一條消息並且它不打印結果。
這是 debug50 在密文到達 printf 之前顯示的內容
這是我的代碼,一團糟
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
bool check_key(char k);
string cipher (char text[], int key);
char alphabet[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
int main(int argc, string argv[])
{
// Check the key
// Check if it's more or less than 1 command line argument
// If not print ERROR
if (argc != 2)
{
printf("ERROR!\n");
return 1;
}
// Check if it's non negative - <= 0
// Check if it's a valid int
// If not print "Usage: ./caesar key"
char k = *argv[1];
if (check_key(k) == 0 || k == '0')
{
printf("Usage: ./caesar key\n");
return 1;
}
// Turn key into and int
int key = atoi(argv[1]);
// Get text
string plaintext = "ABC"; //I used this as a placeholder for get_string("plaintext: ");
string ciphertext = cipher(plaintext, key);
// Print cipher
printf("ciphertext: %s\n", ciphertext);
}
bool check_key(char k)
{
return isdigit(k); // Doesn't take negative values
}
string cipher (char text[], int key)
{
// Take plaintext characters and change each character of it with the character key positions away
// Add the character from alphabet array to another chiper array
// Add cipher array to cipher string and return
int position = 0;
int text_position = 0;
int text_length = 0;
char ciphertext[strlen(text)];
do
{
if (alphabet[position] == text[text_position])
{
int key_position = position + key;
ciphertext[text_position] = alphabet[key_position];
position = 0;
text_position++;
}
else
{
position++;
}
}
while (text[text_position] != '\0');
string final_cipher = ciphertext;
return final_cipher;
}
我無法讓它打印密文。 我想知道問題是否是因為我將數組轉換為字符串的方式,但除了使用重載運算符之外,我不知道還有其他方法可以做到這一點。
您需要使用 malloc 為密文數組分配一個位置,並使您的函數返回一個 char*,或者如果您有一個字符串結構為此分配一個位置並分配給 char*。
在 function cipher
中,在行
char ciphertext[strlen(text)];
您正在創建一個本地字符數組。 一旦 function cipher
結束,這個數組的生命周期就會結束。
在行
string final_cipher = ciphertext;
您沒有創建數組的副本。 相反,您正在創建對現有數組的引用。 這是因為數據類型string
實際上並不包含字符串。 它僅包含對字符數組的引用,該數組可能包含以 null 結尾的字符串。 在 CS50 的第 4 周,您將了解到數據類型string
實際上是char *
的別名,它是一個指針,即對另一個變量或數組的引用。
因此,在行
return final_cipher;
您不會返回數組的副本,而只是返回對現有數組ciphertext
的引用。
但是,如前所述,一旦 function 返回,引用的數組ciphertext
將不復存在。 之后使用此引用的任何嘗試都將導致未定義的行為。
由於數組ciphertext
不再存在,程序很可能會將數組之前使用的memory用於其他目的。 這可能就是您在調試器中看到內存值意外變化的原因。 function printf
可能正在使用 memory 做某事。
這個問題有幾種解決方案:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.