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?
CodePudding user response:
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
.
CodePudding user response:
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:
- an expression that has function type (example:
sin
), - an expression that has incomplete type (example:
x
afterextern struct foo x;
, wherestruct foo
has not yet been defined), - an incomplete type (example:
int []
), or - a bit-field member.
For 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.
CodePudding user response:
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;
}