Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple printf with sizeof does not work at all

Tags:

c

sizeof

I got the most simple code to display sizeof() of a datatype, say an int.

#include <stdio.h>
int main() { 
  printf('%i', sizeof(int));
}

No matter what I do, such as put sizeof(int) into an integer, or use 'zu' instead of 'i', it hands me this error:

error: invalid conversion from ‘int’ to ‘const char*’

Is there something wrong with my compiler? I do not get why I cannot print such a simple sizeof..

EDIT: It seems a printf('%s', 'foo'); STILL tells me I am converting int to const char*, how on earth??

like image 959
John Avatar asked Sep 22 '10 05:09

John


People also ask

Why printf in C is not working?

Printf is not the thing being buffered, it's stdio, so all similar functions will behave in the same way. To demonstrate the buffering, all you have to do is printf a lot of characters, usually more than 1024, and printf will print as you will have exceeded the maximum buffer length and it will automatically fflush.

What can I use instead of sizeof in C?

Re: Alternative for sizeof operatorNo there is not alternative to sizeof() operator in standard ANSI C. Sizeof() is a compiletime operator can be applied to type too ,i.e. sizeof(int); runtime not call any function so sizeof() is very quick. Why do you will not use sizeof() operator?

How do I print T size?

We should use “%zu” to print the variables of size_t length. We can use “%d” also to print size_t variables, it will not show any error. The correct way to print size_t variables is use of “%zu”. In “%zu” format, z is a length modifier and u stand for unsigned type.

What is %s in printf?

%s and string We can print the string using %s format specifier in printf function. It will print the string from the given starting address to the null '\0' character. String name itself the starting address of the string. So, if we give string name it will print the entire string.


1 Answers

printf("%zu", sizeof(int));
  • printf, not print
  • %zu, not %i (it's an unsigned value, not an integer)
  • double quotes, not single quotes
like image 144
Alexander Avatar answered Oct 04 '22 17:10

Alexander