Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify the type of const char* and const char[] in code?

const char* s1   = "teststirg";  
const char  s2[] = "teststirg";

I want a method tell me that s1 is "char*" and s2 is "char[]",how to write the method?

like image 453
timestee Avatar asked Mar 13 '12 07:03

timestee


People also ask

What is the difference between const char * and char * const?

The difference is that const char * is a pointer to a const char , while char * const is a constant pointer to a char . The first, the value being pointed to can't be changed but the pointer can be. The second, the value being pointed at can change but the pointer can't (similar to a reference).

What is const char * const *?

const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed. And we cannot change the value of pointer as well it is now constant and it cannot point to another constant char.

What is a static const char * in C++?

const char* is a pointer to a constant char, meaning the char in question can't be modified. char* const is a constant pointer to a char, meaning the char can be modified, but the pointer can not (e.g. you can't make it point somewhere else).

What is a char * in C?

well, char * means a pointer point to char, it is different from char array. char amessage[] = "this is an array"; /* define an array*/ char *pmessage = "this is a pointer"; /* define a pointer*/ And, char ** means a pointer point to a char pointer.


1 Answers

Use templates:

template<typename T, unsigned int SIZE>
bool IsArray (T (&a)[SIZE]) { return true; }

template<typename T>
bool IsArray (T *p) { return false; }

This will evaluate at runtime.
Usage:

if(IsArray(s1))
...

if(IsArray(s2))
...

If interested, you can use some advance techniques, which will tell you this as compile time.

Edit:

typedef char (&yes)[2];

template<typename T, unsigned int SIZE>
yes IsArray (T (&a)[SIZE]);

template<typename T>
char IsArray (T *p);

Usage:

if(sizeof(IsArray(s1)) == sizeof(yes))
...
if(sizeof(IsArray(s2)) == sizeof(yes))
...
like image 187
iammilind Avatar answered Oct 20 '22 00:10

iammilind