Ayush Naithani
Ayush Naithani

Reputation: 133

how to pass a string by pointer in C++?

In C++ programming i was passing string as pointer

Code:

#include<iostream>
using namespace std;
void changeString(string *s) {
    // change s[1] to 'a' inside this function
}

int main(void) {
    string s = "ayush";
    changeString(&s);
    cout<<s;
}

i wrote code *s[1] = 'a', but it is showing error. how do i access first character of string inside function "changeString" . please help any support is appreciated.

Upvotes: 2

Views: 1219

Answers (1)

Lazy Ren
Lazy Ren

Reputation: 914

According to the C++ Operator Precedence, subscript has higher priority than dereference.
So as @dxiv mentioned in comment *s[1] is parsed as *(s[1]).

So you need to use parenthesis to change priority as (*s)[1].

By the way, using string::replace instead of assign operator is safer way to change string.

Better yet, IMHO using reference is more c++ way of doing so. Check code below for example.

#include<iostream>
using namespace std;

void changeStringWithReference(string &s) {
    s[3]= 'a';
}

void changeString(string *s) {
    (*s)[1] = 'a';
    // better to use string::replace
}

int main(void) {
    string s = "abcde";
    changeString(&s);
    cout << s << endl;
    changeStringWithReference(s);
    cout << s << endl;
}

Upvotes: 6

Related Questions