CS253

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

Replace this with info about this class:

CS253: Problem Solving with C++

Spring 2014

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? Keep in mind that C is not Java, where references are everywhere.

#include <iostream>
#include <string>
using namespace std;
int main() {
    string a="hello", b=a;
    a[0]='j';
    cout << a << ' ' << b << endl;
    return 0;
}

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?

#include <iostream>
#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;
}

Modified: 2013-12-22T19:25

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