Search code examples
csizeof

How to pass a string that stores a datatype taken as an input from user into sizeof() operator and obtain the size of the data type?


Actually when a datatype, say int is stored in a string or a character array, and the string is passed as an argument to sizeof operator, the program returns the character array size instead of substituting the actual data type that is stored in the string, as an argument.

So is it possible in anyway to substitute the content of the string as an argument instead?

Here's the code in

#include <stdio.h>
int main()
{
        char s[20];  

        printf("Please enter the data type to find it's size!: ");

        scanf("%s",&s); 

        printf("The size of %s data type in c language is: %d",s,sizeof(s)); 

        return 0;

}

Solution

  • No, that’s not possible. There’s no more type information in your program after it’s compiled (of course, there might be debugging information, but I doubt you wanna use that).

    One thing you could do, is create a large if statement:

    // ...
    scanf("%s",&s); 
    
    size_t size;
    if (strcmp(s, "int") == 0) {
      size = sizeof(int);
    }
    else if (strcmp(s, "short") == 0) {
      size = sizeof(short);
    }
    // ... all other types you wanna support
    else {
      printf("Did not recognize type %s\n", s);
      return 1;
    }
    
    printf("The size of %s data type in c language is: %d ",s,size); 
    

    This way you retrieve all type information at compile time, store it in your program explicitly and you can therefore access it.