473,408 Members | 1,951 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,408 software developers and data experts.

Why is the size of empty constant 1 byte ?

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3. char ch="";
  4. printf("%c %d",ch ,ch);
  5. return 0;
  6. }
I am getting diff answers in different compilers , so whats the reason behind this ?

Also when I write
Expand|Select|Wrap|Line Numbers
  1. printf("%d"sizeof(""))
;

then I get the output as 1 byte whats the reason behind this ?
Jun 29 '15 #1
9 1467
computerfox
276 100+
Try putting single quotes and a null value: \0.
Double quotes is usually saved for strings and you declared it as a char.
Jun 29 '15 #2
But then how is it working if I am giving double quotes?
Jun 29 '15 #3
Maybe the compiler allocates a char array of about a byte and set the address of ch to array[0], which is the first character in the array? Does sizeof(ch) gives you 1? Does sizeof("") gives you 1 or 4? I am actually intrigued why the compiler wouldn't issue, at least, a warning about using a string literal (which is an array) in a char. I am not savvy on the details of the C and C++ language specifications so I do not know if the compilers are allowed to silently fix the problem for you since an array of "" also equals char. Let me reproduce your problem and I will respond back with a more concrete hypothesis!
Jun 29 '15 #4
I ran the following program.
Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3. char ch="sad\0";
  4. char ar[10] = "sad\0";
  5. char* x = malloc(10);
  6. printf("%d",sizeof(ch));//Outputs actual size of ch
  7. printf("%s", "\n");
  8. printf("%d %x", ch, &ch);//Outputs integer representation of ch's contents, hexadecimal value of address of ch
  9. printf("%s", "\n");
  10. printf("%s %x %d %x %x", ar, ar, sizeof(ar), &ar[0], &ar);//Outputs string, hexadecimal representation of ar (actually, address), actual size of ar, hexadecimal of address of 1st character in array, hexadecimal of address of array
  11. printf("%s", "\n");
  12. printf("%d", sizeof(""));//Outputs 1 because "" is an array of size 1
  13. printf("%s", "\n");
  14. printf("%d", sizeof(x));//Outputs 4 because x is an array allocated in the heap (type pointer which is of size 32bits or 4 bytes)!
  15. return 0;
  16. }
Results:
  1. Your program had a small bug. Passing ch directly to printf without a call to sizeof() was outputting the address in RAM, which is expected to change.
  2. I transiently forgot that arrays on the stack have known sizes so this will also change but only according to char array size! Thus, a char array of size 10 will output 10 when I use sizeof()! I confirmed this by comparing this output to the output of sizeof() on an array allocated on the heap of actual size 10!
  3. It seems the compiler never assigns any portion of a string literal to the ch variable, since it outputs the ascii value of a random character that is not in the string literal!

I hope this helps!
Jun 29 '15 #5
donbock
2,426 Expert 2GB
... = "";
This defines an empty string consisting of only the null-termination. That is, the string consists of one char.

Line 3 should provoke a compiler error.
Either of the following variations are legal:
Expand|Select|Wrap|Line Numbers
  1. char ch[] = "";
  2. char *ch = "";
In the first of these, ch is a 1-element char array. sizeof(ch) is 1.

In the second, ch is a pointer to a 1-element char array. sizeof(ch) is the implementation-specific size of a data pointer.

However, the compiler may insert pad bytes either to allow for faster access or to insure proper alignment of the next variable. I'm not sure, but I think whether or not pad bytes are included in the sizeof value is implementation-specific.
Jun 29 '15 #6
I would agree that line 3 should provoke a compiler error, but gcc allows this syntax (char c = "";). However, the content of ch is not the first character in the array, which is the least behavior I would expect. ch always yields 36 in the test program I made. Why does gcc allows a blatantly wrong syntax and doesn't do anything related to what the syntax is trying to convey? It baffles me...
Jun 29 '15 #7
weaknessforcats
9,208 Expert Mod 8TB
Fix this error first:

Expand|Select|Wrap|Line Numbers
  1. char ch="sad\0";
ch is a char. "sad\0" is the address of element 0 of a char[5]. If your compiler does not burp on this, get a better compiler.

Before pulling your hair on arrays, I recommend reading: http://bytes.com/topic/c/insights/77...rrays-revealed

Then post again.
Jun 30 '15 #8
Don't get me wrong. I understand arrays. I simply reproduced the sample posted by the opener with some modifications to confirm this behavior and yes gcc accepts the syntax without giving an error. It throws a mild warning (warning: initialization makes integer from pointer without a cast [enabled by default]). I figured out what gcc is doing behind the scenes. It takes the address of the array and recast it as a char which means it throws away 3 of the 4 bytes. It's quiet an interesting behavior. Don't believe me? Try it yourself and you will see what the person actually asking saw. Regardless, the opener had a bug in his/ her program logic that has little to do with the char syntax and all to do with not calling sizeof on the variable to get the size of the type rather than the contents of the variable.
Culprit:
Expand|Select|Wrap|Line Numbers
  1. printf("%c %d",ch ,ch);
Should be:
Expand|Select|Wrap|Line Numbers
  1. printf("%c %d",ch ,sizeof(ch));
On the argument of &ar[0] == &ar, that's what I demonstrate to the opener with
Expand|Select|Wrap|Line Numbers
  1. printf("%s %x %d %x %x", ar, ar, sizeof(ar), &ar[0], &ar);
On the get a better compiler remark, welcome to Linus Torvalds' club. In all seriousness, I have plenty of compilers to fiddle around, I just picked the first one I had in front of my eyes for the experiment.

Oh yes, I read your article on arrays about 6 years ago and was going to link it if the opener was curious about why I hypothesized that char would get assigned the first character of the array "" after being allocated. Little did I know gcc was doing more nefarious things under the scenes (maybe that's why Google is so fond of Clang). Hey, at least, the scientific method works.
Jun 30 '15 #9
donbock
2,426 Expert 2GB
@kiseitai2, the behavior you describe is what you might expect from casting a pointer value into a char. That's a clue to what is happening. The compiler creates the initializer array somewhere in memory (just as it would if ch were a char*) and then assigns the address of that array to ch via an implicit cast. Probably.

I say might expect because casting a pointer into a char is at best implementation-defined behavior, and at worst undefined behavior. I'm not going to bother to look up which it is.
Jun 30 '15 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

9
by: pvinodhkumar | last post by:
The number of elemets of the array, the array bound must be constant expression?Why is this restriction? Vinodh
53
by: Neo | last post by:
Hi All, Is that true that size of a byte not necessarily 8-bit? What the std. says? If that true, then what will the size of an int, i mean what sizeof(int) should return? On my machine...
3
by: Nick | last post by:
I have found a class that compresses and uncompresses data but need some help with how to use part of it below is the deflate method which compresses the string that I pass in, this works OK. At...
2
by: Ron | last post by:
Hello, I am trying to read a list of files from an FTP server (mainframe) to a byte array using sockets as follows, but not getting all the files in a given directory: private readonly static...
9
by: Manu | last post by:
Hi, Following code shows how a packet is sent from a client to a server's socket. The file size (fileSizeTemp) is converted to network byte order before sending to the server. *((unsigned...
1
by: Jon Finch | last post by:
Hi All this is a follow up to a post I did a few days back regarding reading a font from an assembly into a memory font object. The only thing I am stuck on is getting the actual memory size of a...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.