Sizeof returning incorrect array length [duplicate]

冷暖自知 提交于 2019-12-19 12:08:50

问题


Possible Duplicate:
Sizeof an array in the C programming language?

I've been fiddling with C to become better acquainted with it and think I may have stumbled upon a initialization/pointer issue that I'm unsure of how to resolve. The below program is an implementation of ROT13, so it takes an input string, and shifts each letter by 13, resulting in the cipher text. The output of my program displays the correct shift, but it won't work for more than 4 characters, making me wonder if sizeof is being used incorrectly. Any other suggestions are appreciated, I'm sure I've messed a few things up at this point.

#include <stdio.h>
#include <string.h>

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);

}

回答1:


sizeof() in encrypt will not behave as you want it to. Inside encrypt, the sizeof(char *) is 4(on a 32bit machine) or 8(on a 64 bit machine), which you can see is the size of a pointer.

To get the sizeof(input) you must change sizeof to strlen. Hence solution = strlen(input)

Why this happens?? when you pass an array into a function, that array is internally represented as a pointer. At the called-function's end input is just a pointer, which gives either 4 or 8 bytesize depending upon your machine.

To get the sizeof of input, just use a macro like this: #define SIZEOF(x) (sizeof(x)/sizeof(x[0])) and use this in the function that defines x. In your program, x is input in main()




回答2:


input has type char* (read as "pointer to char"). sizeof(input) gives you the size of the pointer. You probably want to use strlen to find the length of the string, or pass the length in to the function as an additional argument.




回答3:


sizeof returns the size of the type of its argument. It cannot determine how many characters are in a pointer to a character array.

You should consider using the strlen function if you know that your string is null-terminated.




回答4:


This line causes your problem.

int inputCount = sizeof(input);

sizeof only determines the size of the variable in this case char *. And every pointer has the size of 4 bytes on a 32 bit system.

You can't determine the size of an array during runtime. You could either * pass the size of the input as an parameter * because in your case it is a string, use the strlen in string.h to get the length of the string if the string is terminated by \0.

But in both cases you can't simply allocate the output buffer using

char output[variable_containing_size];

You would need to use malloc() to dynamically allocate memory during runtime or even easier pass the output parameter as parameter to your function.

#include <stdio.h>
#include <string.h>

#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);

}

But in this case the encrypt() function does no size checks at all, and if you're not careful this could easily lead to buffer overflows.



来源:https://stackoverflow.com/questions/13081682/sizeof-returning-incorrect-array-length

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!