How can i get the sizeof a variable through a function using a pointer as a parameter?
readEachChar(unsigned char * input){
printf("The the size of the string %zu", sizeof(input));
for (size_t i = 0; i < sizeof(input); i++) // currently it show me the size of the pointer (8 bytes)
{
printf("[%x]",input[i]);
}
printf("\n");
}
unsigned char text[] = "thisisalongkindofstring";
int main(){
readEachChar(&text);
return 0;
}
In the line
printf("The the size of the string %zu", sizeof(input));
the sizeof
operator will give you the size of the pointer input
. It will not give you the size of the object that it is pointing to (which may be the size of the array or the length of the string).
In the function main
, the definition
unsigned char text[] = "thisisalongkindofstring";
will make text
an array of 24 characters: These 24 characters consist of the 23 actual characters and an extra character for the null terminating character. In C, a string is, by definition, a sequence of characters that is terminated by a null character, i.e. a character with the character code 0
.
Therefore, in order to determine the length of the string, you must count every character of the string, until you encounter the terminating null character. You can either do this yourself, or you can use the function strlen
which is provided by the C standard library.
Also, it is normal to use the data type char
for individual characters of a string, not unsigned char
. All string handling functions of the C standard library expect parameters of type char *
, not unsigned char *
, so, depending on your compiler, mixing these data types could give you warnings or even errors.
Another issue is that this line is wrong:
readEachChar(&text);
The function readEachChar
seems to expect the function argument to be a pointer to the first character of the string, not a pointer to an entire array. Therefore, you should write &text[0]
instead of &text
. You can also simply write text
, as this expression will automatically decay to &text[0]
.
After applying all of the fixes mentioned above, your code should look like this:
#include <stdio.h>
#include <string.h>
void readEachChar( char * input )
{
size_t len = strlen( input );
printf( "The size of the string: %zu\n", len );
for ( size_t i = 0; i < len; i++ )
{
printf( "[%x]", input[i] );
}
printf("\n");
}
int main()
{
char text[] = "thisisalongkindofstring";
readEachChar( text );
return 0;
}
This program has the following output:
The size of the string: 23
[74][68][69][73][69][73][61][6c][6f][6e][67][6b][69][6e][64][6f][66][73][74][72][69][6e][67]