Jump to content
  • Advertisement
Sign in to follow this  
ugoel123

Untitled

This topic is 4865 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi all, I am lil confused with the handling of char pointer and char array in C++. char* pstr = "Umesh Goel"; int nLenghtOfName = sizeof(pstr); char astr[] = "Umesh Goel"; int nLenghtOfNameA = sizeof(astr); Now I get the value of nLenghtOfName = 4 and nLenghtOfNameA = 11. I don't understand this behavior. Can any one enlighten me on the same. Any help in this regard will be highly appreciated. -Thanks --Umesh.

Share this post


Link to post
Share on other sites
Advertisement
You've fallen into a very common newbie trap. The thing is that sizeof works on types, giving in your example:'

int nLenghtOfName = sizeof(pstr);//sizeof(char*)
int nLenghtOfNameA = sizeof(astr);//sizeof(char[11])


so the first one simply returns the size of a pointer to char and on your platform (as is common on most 32bit platforms) the pointer is 4bytes large.

If you need the string length you should be using strlen or might I be so bold as to suggest that you use std::string for all your string needs? That will simplify things enormously down the road.

Share this post


Link to post
Share on other sites
Quote:
Original post by DigitalDelusion
If you need the string length you should be using strlen or might I be so bold as to suggest that you use std::string for all your string needs? That will simplify things enormously down the road.


You should include examples ;-).

/* Using strlen, which although better than sizeof is very bad, your code would
* look like this:
*/

#include <cstring>

char* pstr = "Umesh Goel";
int nLenghtOfName = std::strlen(pstr);
char astr[] = "Umesh Goel";
int nLenghtOfNameA = std::strlen(astr);

/* Or like this:
*/

#include <cstring>
using namespace std;

char* pstr = "Umesh Goel";
int nLenghtOfName = strlen(pstr);
char astr[] = "Umesh Goel";
int nLenghtOfNameA = strlen(astr);

/* The better solution is to use std::string instead of character pointers
* or arrays:
*/

#include <string> //not cstring, which provides the standard C library's string functions (strlen, strcpy, strcat, etc...)

std::string str = "Umesh Goel";
int nLengthOfName = str1.size();

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!