Changing the address of a pointer question

  • Thread starter Thread starter transgalactic
  • Start date Start date
AI Thread Summary
The discussion centers on the use of strings in C and C++, particularly the differences between `std::string` and C-style strings. It clarifies that `strcpy` is a function used to copy C-style strings, which are null-terminated character arrays, and emphasizes that `std::string` should be used in C++ for better safety and convenience. The conversation also touches on how to declare strings in C, highlighting that strings can be represented as arrays of characters, with the importance of including a null terminator to mark the end of the string. Examples are provided to illustrate proper string initialization and copying in both languages.
transgalactic
Messages
1,386
Reaction score
0
Code:
string t="rrrrr";
string *p=&t;
strcpy(p, "abc");

i was told that it tells P to point on the data which on the address "abc"

i thought that in order to change the address of a pointer we need to add &

strcpy(&p, "abc");

?

(i know that changing the address into "abc" is not recommended)
 
Last edited:
Technology news on Phys.org
Um, don't do that! string, or more precisely std::string is a C++ standard library string, which has its own various operators like assignment.
Code:
char* strcpy( char *to, const char *from )
is a C (and C++) function that copy the C-style string (null terminated char arrays) pointed to by from to the memory pointed to by to, returning to.

Of course, you should just be using std::string if you're programming in C++.

Code:
#include <cstring>

#include <iostream>
#include <string>

int main()
{
    char *p = new char[ std::strlen("abc") + 1 ]; // Don't forget the space for '\0'
    std::strcpy(p, "abc");
    std::cout << p << '\n';

    std::string t;
    std::string *pt = &t;
    *pt = "def";
    std::cout << t << '\n';
}
 
how do you do a string in C??

an array of chars?

char a[5]={a,b,c,d,e}
like that
??
 
transgalactic said:
how do you do a string in C??
an array of chars?
Yes
char a[5]={a,b,c,d,e}
like that
Either
char a[6]={'a','b','c','d','e','\0'}
You need to mark the end of a string in C with a null value, ie a zero.

or char a[]="abcde"
C will automatically size a one dimensional array for you and if you supply the string value in quotes it will also add the terminating zero.
 
thanks
 
Thread 'Is this public key encryption?'
I've tried to intuit public key encryption but never quite managed. But this seems to wrap it up in a bow. This seems to be a very elegant way of transmitting a message publicly that only the sender and receiver can decipher. Is this how PKE works? No, it cant be. In the above case, the requester knows the target's "secret" key - because they have his ID, and therefore knows his birthdate.
Back
Top