0

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?

7
  • HaHaHaHa,you are right, i'm so careless.Next time I will pay attention. Commented Dec 12, 2021 at 15:40
  • Better to post the error message as text than only a picture. Commented Dec 12, 2021 at 15:42
  • 1
    Use strcpy to write into an existing char array (although you'd need more safety checks in a real program) Commented Dec 12, 2021 at 15:43
  • One doesn't simply assign to a char array. You have to use std::strcpy and friends. Plus, if this is really C++, then use std::strings instead of char[]. Commented Dec 12, 2021 at 15:44
  • 1
    b[] = "world"; //I alse try b*/b,but it is not ok -- You can't learn C++ properly by randomly trying things. C++ is one of the most difficult languages to learn, and it is best to learn it by utilizing peer-reviewed C++ books. Commented Dec 12, 2021 at 15:45

2 Answers 2

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

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

#include<iostream>
#include<string>
using std::cout;
using std::string;

void sub(string &b){
    b = "world";
}

int main(){
    string a = "hello";
    sub(a);
    cout << a << endl; // output

    system("pause");
    return 0;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks you very much.Other question:If i don't want to use strcpy and string just using array as a function parameter.what should i do?
@Hideonbush As far as I know, you just cannot assign a string literal to a c-string variable unless it's a declaration. However, you can assign characters one by one, like b[0] = 'w'; b[1] = 'o'; and so on.
Ok,Thanks for the prompt reply.Next time,I will not assign a string literal to a c-string variable unless it's a declaration.
0

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.

1 Comment

Thanks, good explanation. So b[i] can only be assigned to a char type not string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.