返回错误的数组长度

可能重复:
C编程语言中数组的大小?

我一直在摆弄C以便更好地熟悉它,并认为我可能偶然发现了一个我不确定如何解决的初始化/指针问题。 下面的程序是ROT13的一个实现,所以它需要一个输入字符串,并将每个字母移动13,从而得到密文。 我程序的输出显示正确的移位,但它不会超过4个字符,让我想知道sizeof是否被错误地使用。 任何其他建议都表示赞赏,我确信此时我已经搞砸了一些事情。

#include  #include  void encrypt(char *); int main(void){ char input[] = "fascs"; encrypt(input); return 0; } void encrypt(char *input){ char alphabet[] = "abcdefghijklmnopqrstuvwxyz"; printf("Input: %s \n", input); int inputCount = sizeof(input); printf("Characters in Input: %i \n\n", inputCount); //holds encrypted text char encryptedOutput[inputCount]; //Initialize counters int i, j = 0; // loop through alphabet array, if input=current letter, shift 13 mod(26), // push result to output array, encryptedOutput for(i = 0; i < inputCount; i++){ for(j = 0; j < 26; j++){ if(input[i] == alphabet[j]){ encryptedOutput[i] = alphabet[(j + 13) % 26]; } } } //Nul Termination for printing purposes encryptedOutput[i] = '\0'; printf("Rot 13: %s \n\n", encryptedOutput); } 

encrypt sizeof()将不会按您的意愿运行。 在encrypt内部, sizeof(char *)4 (在32位机器上)或8 (在64位机器上),你可以看到它是一个指针的大小。

要获取sizeof(input)您必须将sizeof更改为strlen 。 因此解决方案= strlen(input)

为什么会这样? 将数组传递给函数时,该数组在内部表示为指针。 在被调用函数的末尾, input 只是一个指针,它根据您的机器提供48字节大小。

要获得inputsizeof ,只需使用如下宏: #define SIZEOF(x) (sizeof(x)/sizeof(x[0]))并在定义 x的函数中使用它。 在你的程序中, xmain() input

input类型为char* (读作“指向char的指针”)。 sizeof(input)为您提供指针的大小。 您可能希望使用strlen来查找字符串的长度,或者将长度作为附加参数传递给函数。

sizeof返回其参数类型的大小。 它无法确定指向字符数组的指针中有多少个字符。

如果您知道字符串以空值终止,则应考虑使用strlen函数。

此行会导致您的问题。

 int inputCount = sizeof(input); 

sizeof仅确定变量的大小,在这种情况下为char * 。 并且每个指针在32位系统上的大小为4个字节。

您无法在运行时确定数组的大小。 您可以*将输入的大小作为参数*传递,因为在您的情况下它是一个字符串,如果字符串由\0终止,则使用string.hstrlen来获取字符串的长度。

但在这两种情况下,您都不能简单地使用分配输出缓冲区

 char output[variable_containing_size]; 

您需要使用malloc()在运行时动态分配内存,甚至更容易将输出参数作为参数传递给函数。

 #include  #include  #define BUFFER_LENGTH 80 void encrypt(const char * input, char *output); int main(void){ char input[BUFFER_LENGTH] = "fascs"; char output[BUFFER_LENGTH] = {0}; // initialize every field with \0 encrypt(input, output); return 0; } void encrypt(const char *input, char *output){ char alphabet[] = "abcdefghijklmnopqrstuvwxyz"; printf("Input: %s \n", input); int inputCount = strlen(input); printf("Characters in Input: %i \n\n", inputCount); //Initialize counters int i, j = 0; // loop through alphabet array, if input=current letter, shift 13 mod(26), // push result to output array, output for(i = 0; i < inputCount; i++){ for(j = 0; j < 26; j++){ if(input[i] == alphabet[j]){ output[i] = alphabet[(j + 13) % 26]; } } } //Nul Termination for printing purposes output[i] = '\0'; printf("Rot 13: %s \n\n", output); } 

但在这种情况下, encrypt()函数根本不进行大小检查,如果你不小心,这很容易导致缓冲区溢出。