When applied to a string literal, is the sizeof operator supposed to return the size of the string
(including nul), or the size of a pointer?
For example, assuming a char is 1 byte and a char * is 4 bytes, should the following yield 4, 5, of
something else? (And, if something else, what determines the result?)
char x[] = "abcd";
printf( "%d\n", sizeof( x ) );
-Don 16 17622
Don Starr wrote: When applied to a string literal, is the sizeof operator supposed to return the size of the string (including nul), or the size of a pointer?
Smells like homework. For example, assuming a char is 1 byte and a char * is 4 bytes, should the following yield 4, 5, of something else? (And, if something else, what determines the result?)
Yup. Really smells like homework. char x[] = "abcd"; printf( "%d\n", sizeof( x ) );
Well, what do you think?
[hint: you're not taking the `sizeof' of a string literal here, but,
rather, an array of `char']
HTH,
--ag
--
Artie Gold -- Austin, Texas
Don Starr wrote: When applied to a string literal, is the sizeof operator supposed to return the size of the string (including nul), or the size of a pointer?
For example, assuming a char is 1 byte and a char * is 4 bytes, should the following yield 4, 5, of something else? (And, if something else, what determines the result?)
char x[] = "abcd"; printf( "%d\n", sizeof( x ) );
You'll get 5. (Actually you might get undefined behavior
because the `sizeof' operator yields a result of type `size_t',
and "%d" isn't necessarily the right format specifier. I've
used machines on which the above would print 0!)
Why 5? Because a string literal generates an array of
characters. When you apply the `sizeof' operator to an array
(any array), you get the number of bytes in the array. This
is one of the very few cases where an array reference does
*not* turn into a pointer to the zero'th element; the `sizeof'
operator applies to the array as a whole.
See also Questions 6.4 and 6.8 -- in fact, read all of
Section 6 -- in the comp.lang.c Frequently Asked Questions
(FAQ) list http://www.eskimo.com/~scs/C-faq/top.html
-- Er*********@sun .com
Don Starr <no****@nospam. net> writes: When applied to a string literal, is the sizeof operator supposed to return the size of the string (including nul), or the size of a pointer?
The sizeof operator yields the size of its operand's type. If
its operand has a pointer type, then it yields the size of the
pointer type. If its operand has an array type, then it yields
the number of bytes in the array. There is no special case for a
string.
For example, assuming a char is 1 byte
A char is always 1 byte.
and a char * is 4 bytes, should the following yield 4, 5, of something else? (And, if something else, what determines the result?)
char x[] = "abcd"; printf( "%d\n", sizeof( x ) );
You need to cast the result of sizeof to int here, because sizeof
yields a result of type size_t, which is an unsigned type.
With that correction, this will always print 5, because the array
has five elements of type char.
--
int main(void){char p[]="ABCDEFGHIJKLM NOPQRSTUVWXYZab cdefghijklmnopq rstuvwxyz.\
\n",*q="kl BIcNBFr.NKEzjwC IxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+= strchr(p,*q++)-p;if(i>=(int)si zeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Don Starr wrote: On Tue, 29 Jul 2003 20:43:11 GMT, Artie Gold <ar*******@aust in.rr.com> wrote:
Don Starr wrote:
When applied to a string literal, is the sizeof operator supposed to return the size of the string (including nul), or the size of a pointer? Smells like homework.
No, not homework. Haven't had any of that for about 17 years. It's an attempt to settle a dispute regarding the output of one compiler vs. several others.
My mistake. No offense meant. ;-)
Well, what do you think? [hint: you're not taking the `sizeof' of a string literal here, but, rather, an array of `char']
*I* think 5, and so do all (3) of the compilers I've tried.
Then we're all in agreement!
--ag
--
Artie Gold -- Austin, Texas
On Tue, 29 Jul 2003 20:28:19 GMT, Don Starr <no****@nospam. net> wrote: char x[] = "abcd"; printf( "%d\n", sizeof( x ) );
After reading the various responses, I realize that I goofed in my example. _Of course_ I'm asking
for the size of an array of char.
I should have posted originally:
#define _x "abcd"
size_t y = sizeof( _x );
I then should've asked about the resulting value of <y>.
I presume that the answer is still 5, as the string literal is treated here as a nul-terminated
array of char?
-Don
"Don Starr" <no****@nospam. net> wrote: I presume that the answer is still 5, as the string literal is treated here as a nul-terminated array of char?
Yes. A string literal is defined as a null-terminated,
non-modifyable but non-const array of char.
--
Simon.
Eric Sosman <Er*********@su n.com> wrote in message news:<3F******* ********@sun.co m>... Don Starr wrote:
This is one of the very few cases where an array reference does *not* turn into a pointer to the zero'th element; the `sizeof' operator applies to the array as a whole.
Can you please let me know the other cases where the array reference
does not turn into a pointer
In <3f************ **********@news .optusnet.com.a u> "Simon Biber" <sb****@optusho me.com.au> writes: "Don Starr" <no****@nospam. net> wrote: I presume that the answer is still 5, as the string literal is treated here as a nul-terminated array of char?
Yes. A string literal is defined as a null-terminated, non-modifyable but non-const array of char.
Nope, it ain't. A string literal is a purely syntactical construct. The
way it is translated depends on the context where it is used. Compare:
char a[] = "abcd";
char b[4] = "abcd";
The same string literal initialises a and b differently. Furthermore,
there is nothing preventing these arrays from being declared as arrays of
const char.
Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
In <a8************ **************@ posting.google. com> ma********@yaho o.com (madhukar_bm) writes: Eric Sosman <Er*********@su n.com> wrote in message news:<3F******* ********@sun.co m>... Don Starr wrote:
This is one of the very few cases where an array reference does *not* turn into a pointer to the zero'th element; the `sizeof' operator applies to the array as a whole.
Can you please let me know the other cases where the array reference does not turn into a pointer
Except when it is the operand of the sizeof operator or the unary &
operator, or is a character string literal used to initialize an array
of character type, or is a wide string literal used to initialize an
array with element type compatible with wchar_t, an lvalue that has
type ``array of type '' is converted to an expression that has type
``pointer to type '' that points to the initial member of the array
object and is not an lvalue.
Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Zombie |
last post by:
Hi, what is the correct way of converting contents of a <string> to
lowercase?
There are no methods of <string> class to do this so I fallback on
strlwr().
But the c_str() method returns a const pointer which cannot be used
with strlwr() as it does the conversion inplace. So, I use the
following logic of copying the contents to a dynamically allocated
char* array and then doing the conversion:
-----------------------------
|
by: dalbosco |
last post by:
Hello,
I am new to STL and I've written the following code
which crash.
Could anyone tell me why this code crash?
Thanks by advance.
--
J-F
#include <iostream>
|
by: Karl Ebener |
last post by:
Hi!
I am currently using a string to hold data (can be strings as well as
binary!). Now it occured to me, that the <string> might be unable to
handle Null-Bytes. Is that so?
Following question: How can I copy the binary data of a string into an
array, such as
char mtext (or alike) ?
|
by: Karl Ebener |
last post by:
Hi!
I asked a similar question before but then changed everything to using
char-Arrays instead of the string class, but I would rather not do this
again.
So, does anyone know of a string-Class similar to the STL-<string> that
supports null-bytes?
I tried with standard <string> but this definitely does not support
|
by: misirion |
last post by:
Ciao,
vorrei poter scrivere e leggere su files binari dei vettori di
stringhe, ed avrei implementato questo codice:
ifstream fin(conf.c_str(),ios::binary);
char inc;
fin.read( inc, sizeof(levelfiles) );
levelfiles = fromCharS(inc);
fin.close();
| |
by: KL |
last post by:
I have a problem trying to write to a binary file that I want to name
after a particular name from a set. My code for the function follows,
please excuse the horrible mistakes you may see, I am a student, and
trying my best.
void retrieveImage(set<string>finalset, string hostname, string filename){
set<string>::iterator i;
string img, filetoget;
char test;
for (i = finalset.begin();i != finalset.end();i++){
|
by: Gary Wessle |
last post by:
whats an efficient way to copy a string to a vector<string>?
how about this?
#include <iostream>
#include <string>
#include <vector>
Using namespace std;
|
by: barcaroller |
last post by:
In the boost::program_options tutorial, the author included the following
code:
cout << "Input files are: "
<< vm.as< vector<string()
<< "\n";
Basically, he is trying to print a vector of string, in one line. I could
|
by: barcaroller |
last post by:
1. If I pass pointers (char*) as iterators to an STL algorithm and the
return value is an iterator, can I convert that iterator to a pointer? If
yes, how?
2. What is the internal representation of vector<string>? Will the vector
contain the string objects or will it contain pointers/references to the
string objects? The reason I ask is that it is not clear to me how the
v.reserve() and &v operations would work for a vector<string>.
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |