Home > Back-end >  Sizeof output is not as expected
Sizeof output is not as expected

Time:12-13

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

int main() {
   char str[400] = "rQvqQmyl9N9FmI8ECESs0N2dKBATuIrvT4HEh0lRa 6kGHIP0owiFqFdlvktmOQMTdZ5gW44G2O6T2uQGlIeeobnyYuZscLadvyM5tkzb1MhEmBoIuCp8db9GZ8SBBMnoDIWNi9Ad6pRzBpcxmobWJnJo3O6BQ/Kii03RMfXVEw5No7n576J0blLPirrH6M7OaIp7qcrT7hD4qHkGIKjoAcGLsu0c5Ii2r lOnFE1zgMPZtw8 QoHBp/lzFH5LyB973e k9B5T3UO/L7xM6h8ZN4ufXibM385PdzPuwZ3NbmZRCSpIrvGNyUSZo0/mcPuzt6KuoQpNLYt9Avmi";
   // Extract the first token
   char * token = strtok(str, " ");
   printf( " %s\n", token ); //printing the token
   printf("%lu \n", sizeof(token));
   return 0;
}

Output rQvqQmyl9N9FmI8ECESs0N2dKBATuIrvT4HEh0lRa 6kGHIP0owiFqFdlvktmOQMTdZ5gW44G2O6T2uQGlIeeobnyYuZscLadvyM5tkzb1MhEmBoIuCp8db9GZ8SBBMnoDIWNi9Ad6pRzBpcxmobWJnJo3O6BQ/Kii03RMfXVEw5No7n576J0blLPirrH6M7OaIp7qcrT7hD4qHkGIKjoAcGLsu0c5Ii2r lOnFE1zgMPZtw8 QoHBp/lzFH5LyB973e k9B5T3UO/L7xM6h8ZN4ufXibM385PdzPuwZ3NbmZRCSpIrvGNyUSZo0/mcPuzt6KuoQpNLYt9Avmi

8

Why Size of token is 8 ? It should be length of token.

CodePudding user response:

The variable token has the type char * that is it is a pointer

char * token = strtok(str, " ");

So this call of printf

printf("%lu \n", sizeof(token));

outputs the size of a pointer in your system.

You will get the same result if you will use even an uninitialized pointer that does not point to any string as for example

char *token;
printf( "%zu \n", sizeof(token));

If you want to output the length of the pointed string then you need to write

printf("%zu \n", strlen(token));

CodePudding user response:

sizeof is for managing memory, not data. It tells you how much memory a type requires. sizeof an array is the number of bytes the array requires. sizeof a pointer is the number of bytes the pointer requires.

strlen is for managing the data of strings. It tells you how long a string is, which is the number of non-zero characters before the first zero character.

CodePudding user response:

The eight is the size of your pointer which is platform dependent. What you need is to iterate through the token variable or use strlen(token) to get the actual size.

  • Related