Changing the address of a pointer question

  • Thread starter Thread starter transgalactic
  • Start date Start date
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
4 replies · 2K views
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:
Physics 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.