Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do strings use char*?

Tags:

Why do most string functions in the C/C++ stdlibs take char* pointers?

The signed-ness of char is not even specified in the standard, though most modern compilers (GCC, MSVC) treat char as signed by default.

When would it make sense to treat strings as (possibly) signed bytes? AFAIK there are no meaningful character values below zero in any character set. For certain string operations, the values must be cast to unsigned char anyway.

So why do the stdlibs use char*? Even C++-specific methods, such as string::string(const char *);?

like image 825
Unsigned Avatar asked Jun 24 '12 03:06

Unsigned


People also ask

Why do we use char * in C++?

In C++, the char keyword is used to declare character type variables. A character variable can store only a single character.

How is a char * a string?

char represents a single character whereas String can have zero or more characters. So String is an array of chars. We define char in java program using single quote (') whereas we can define String in Java using double quotes (").

Can we use string instead of char *?

It's safer to use std::string because you don't need to worry about allocating / deallocating memory for the string. The C++ std::string class is likely to use a char* array internally. However, the class will manage the allocation, reallocation, and deallocation of the internal array for you.

Is string and char * the same?

The main difference between Character and String is that Character refers to a single letter, number, space, punctuation mark or a symbol that can be represented using a computer while String refers to a set of characters. In C programming, we can use char data type to store both character and string values.


1 Answers

  1. I'm pretty sure most of the string functions predate the existence of unsigned char.
  2. Plain char may be either a signed or an unsigned type. The C and C++ standards explicitly allow either one (it's always a separate type from either unsigned char or signed char, but has the same range as one or the other).
  3. While the C string functions use char *, std::string is what's used in most C++.
like image 106
Jerry Coffin Avatar answered Dec 31 '22 16:12

Jerry Coffin