Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String statements

Tags:

c++

c

Talking about strings in C++, what is the difference between the following statements: s1=s2 and strcpy (s1, s2)? Supposing that s1 and s2 are (original version: type 'char', as revised) type char *.

like image 379
Venus Avatar asked Jun 29 '26 04:06

Venus


2 Answers

Given:

char s1, s2;
...
s1 = s2;          // Assigns value in s2 to s1
strcpy(s1, s2);   // Error detected by compiler; strcpy() takes char pointers

Given:

char *s1, *s2;
...
s1 = s2;         // s1 points to the same 'string' that s2 does
strcpy(s1, s2);  // the space pointed to by s1 contains the same
                 // characters as the space pointed to by s2.

In the second case (pointers), there are a number of caveats about making sure you have enough space allocated for the actual string - as opposed to the pointers. The triple dots indicate where there is some work to be done to ensure things are initialized.

like image 159
Jonathan Leffler Avatar answered Jun 30 '26 17:06

Jonathan Leffler


Difference between char and char* and char* null terminated string:

At first your question asked about strcpy and char. char holds a single character. Each char has an address. The address of a char is char*

It is very common in C/C++ to use a char* to point to the first character of a null terminated character array. We consider a null terminated character array a null terminated string.

To know when the string contained inside the array ends, a null terminated character is added to the end of the string.

Null terminated strings:

const char *p = "hello";
const char *s = "world";
p = s;

Both p and s hold a memory address to the first element in the array of the string literal. When you say p = s you are simply changing what the p variable holds to be the s memory address value that s holds.

So above originally p may hold 0x94749248, and s may hold 0x84811409. And after the assignment p = s, p and s hold 0x84811409.

The actual array of characters are stored at memory address 0x84811409

strcpy:

strcpy works on char* not char. By char* I mean a pointer to the first element of an array of chars, representing a null terminated string.

The following actually copies the data into szBuffer.

char szBuffer[512];
char *p = "hello world!";
strcpy(szBuffer, p);

Nowp holds a memory address of the string literal "hello world!" and szBuffer holds its own copy of all of the characters.

szBuffer after the call to strcpy still holds the same 512 memory addresses. It's just that they have been filled with the values starting at *p.

STL strings:

strings in C++ usually refer to STL strings.

#include <string>

std::string s = "hi";
like image 31
Brian R. Bondy Avatar answered Jun 30 '26 18:06

Brian R. Bondy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!