Home > Net >  Question about using string arrays as function parameters
Question about using string arrays as function parameters

Time:12-13

I am a novice, I encountered a little problem today, I hope to get someone's answer, thank you very much. Code show as below。

#include<iostream>
using namespace std;
void sub(char b[]){
    b[] = "world";    //I alse try b*/b,but it is not ok
}
int main(void){
    char a[10] = "hello";
    sub(a);
    cout<<a<<endl;

    system("pause");
    return 0;
}

error: expected primary-expression before ']' token b[] = "world"; ^ The error

I want the final output will be "world". The function sub() can run correctly. What should I do?

CodePudding user response:

strcpy(b, "world"); // need <string.h>

But I would use std::string (instead of c-string) directly.

#include<iostream>
#include<string>
using namespace std;
void sub(string &b){
    b = "world";
}
int main(){
    string a = "hello";
    sub(a);
    cout<<a<<endl; // output

    system("pause");
    return 0;
}

CodePudding user response:

as other people told you it's not c style but c style, I will try to explain why it does not compile. when you write b[i] you tell the compiler: "please go to memory location b sizeof(b type) * i", so when you write b[], the compiler can't understand what you want.

  • Related