Reputation: 1
I have the following code:
void main(int argc, char *argv[]){
for (int i=1; i<argc; i++){
printf("%s-%lu\t", argv[i], sizeof(argv[i]));
}
}
I expect that $./a.out int long
should give me
short-2 int-4 long-8
but instead I am getting
short-8 int-8 long-8
Can someone tell me why?
Upvotes: 0
Views: 141
Reputation: 42
Basically what's happening, is that the sizeof operator computes the size of the string that you input through argv
. The problem is that int
when typed in argv
means nothing, it's just text for the program.
Of course you could implement your idea using switch
or nested conditionals
to check if argv[i] is equal to the name of the type and then return the result of sizeof on that type. Look at @pmg's solution for that.
But even though it'll do what you want it has it's limitations, only the types implemented can have their size computed, which I guess is not your what you're looking for.
Upvotes: 0
Reputation: 67546
sizeof
is not a function; it is an operator.
It gives you the size of the object, type or constant expression. It will not give you the size of the type if you pass it as the string.
sizeof("long")
will give you the size of the string literal "long"
(i.e. 5) not the size of the type long
(e.g. 8).
As argv
is an array of pointers to char
, sizeof(argv[j])
will give you the size of the pointer to char
.
Upvotes: 6
Reputation: 222923
What type of parameter does sizeof accept?
The operand of sizeof
may be an expression (particularly a unary-expression in the formal grammar) or a type-name in parentheses, per C 2018 6.5.3 1. Per 6.5.3.4 1, it shall not be applied to:
sin
),x
after extern struct foo x;
, where struct foo
has not yet been defined),int []
), orFor sizeof(argv[i])
, sizeof
produces the size of argv[i]
, which is a pointer to char
. Applying sizeof
to a string will not produce the size of the type named in the string (except by coincidence); it produces its result based on the type of the expression itself, not upon the value of the expression or anything it points to or contains.
Upvotes: 4
Reputation: 108938
If you want to compare user input to "int"
, "long"
, etc you need to do it manually
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
if (argc < 2) exit(EXIT_FAILURE);
if (strcmp(argv[1], "int") == 0) {
int dummy = 42;
printf("size of int is %zu\n", sizeof dummy);
}
if (strcmp(argv[1], "double") == 0) {
printf("size of double is %zu\n", sizeof (double));
}
if (strcmp(argv[1], "long") == 0) {
long int dummy = 42;
printf("size of long is %zu\n", sizeof dummy);
}
return 0;
}
Upvotes: 2