CS253

This file defines the header for each page. An optional "icon" image (I use the textbook):

A link to enable editing of this page: Edit TopBar Replace this with info about this class:

CS253: Problem Solving with C++

Spring 2012

Example String Cast

Links to the various pages for this class:

Wish I could do this: * Schedule

A String Example

Consider this code--what does it display?

(:source lang=cpp filename=c.cc -inline:)

  1. include <iostream>
  2. include <string>

using namespace std; int main() {

    string a="hello", b=a;
    a[0]='j';
    cout << a << ' ' << b << endl;
    return 0;

} (:sourceend:)

Now, consider this code. This code is evil, because it casts the result of a.data() to be writable. However, its result may be surprising. What does it display?

(:source lang=cpp filename=d.cc -inline:)

  1. include <iostream>
  2. include <string>

using namespace std; int main() {

    string a="hello", b=a;
    char *p = (char *) a.data();
    *p = 'm';
    cout << a << ' ' << b << endl;
    return 0;

} (:sourceend:)

Modified: 2009-02-02T13:40

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building