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);
}
sizeof()inencryptwill not behave as you want it to. Insideencrypt, thesizeof(char *)is4(on a 32bit machine) or8(on a 64 bit machine), which you can see is the size of a pointer.To get the
sizeof(input)you must changesizeoftostrlen. 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
inputis just a pointer, which gives either4or8bytesize depending upon your machine.To get the
sizeofofinput, 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,xisinputinmain()