 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
Michael DeWulf Guest
|
Posted: Sat Sep 16, 2006 7:47 am Post subject: sizeof |
|
|
Why does the code in example 1 output 100 and the code in example 2 output
4? Rather, I understand example 2's output, but why doesn't example 1
also output 4?
-Mike
----Example 1----
#include <iostream>
using namespace std;
int main()
{
char c[100];
cout << sizeof(c) << endl;
return 0;
}
----Example 2----
#include <iostream>
using namespace std;
int main()
{
char * c = "what's up?";
cout << sizeof(c) << endl;
return 0;
} |
|
| Back to top |
|
 |
Frederick Gotham Guest
|
Posted: Sat Sep 16, 2006 7:55 am Post subject: Re: sizeof |
|
|
Michael DeWulf posted:
| Quote: | int main()
{
char c[100];
cout << sizeof(c) << endl;
return 0;
}
|
This should print 100 on every implementation, as sizeof(char) is exactly 1
on every implementation. Therefore, sizeof( char[100] ) should be equal to
100 * 1.
| Quote: | #include <iostream
using namespace std;
int main()
{
char * c = "what's up?";
cout << sizeof(c) << endl;
return 0;
}
|
In your former example, "c" is an array". In _this_ example, "c" is a
pointer. If the bell is ringing in your head yet, I suggest you read a good
book which explains the nature of arrays and pointers in C/C++.
--
Frederick Gotham |
|
| Back to top |
|
 |
Jim Langston Guest
|
Posted: Sat Sep 16, 2006 8:52 am Post subject: Re: sizeof |
|
|
"Michael DeWulf" <mtd1 (AT) hive (DOT) cec.wustl.edu> wrote in message
news:Pine.LNX.4.64.0609152144010.4483 (AT) hive (DOT) cec.wustl.edu...
| Quote: | Why does the code in example 1 output 100 and the code in example 2 output
4? Rather, I understand example 2's output, but why doesn't example 1
also output 4?
-Mike
----Example 1----
#include <iostream
using namespace std;
int main()
{
char c[100];
cout << sizeof(c) << endl;
return 0;
}
|
c is an array with 100 elements.
| Quote: | ----Example 2----
#include <iostream
using namespace std;
int main()
{
char * c = "what's up?";
cout << sizeof(c) << endl;
return 0;
}
|
c is a char pointer that takes 4 bytes of memory. |
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|