Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Changing the address of a pointer question

  1. Oct 14, 2008 #1
    Code (Text):

    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: Oct 14, 2008
  2. jcsd
  3. Oct 14, 2008 #2

    KTC

    User Avatar

    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 (Text):
    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 (Text):
    #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';
    }
     
     
  4. Oct 15, 2008 #3
    how do you do a string in C??

    an array of chars?

    char a[5]={a,b,c,d,e}
    like that
    ??
     
  5. Oct 15, 2008 #4

    mgb_phys

    User Avatar
    Science Advisor
    Homework Helper

    Yes
    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.
     
  6. Oct 15, 2008 #5
    thanks
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: Changing the address of a pointer question
  1. Pointer question (Replies: 2)

  2. A pointer value question (Replies: 13)

Loading...