简体   繁体   中英

Passing an Array Reference in C++

I'm new to C++ and running into a lot of sytax all the time.. I havn't been able to find a concrete answer to this in a while now. I'm trying to run this piece of code:

void test(char &testChar){
    char B[3] = {"BB"};
    testChar = B;
}

int main(int argc, const char * argv[])
{
    char A[3] = {"AB"};
    test(A);
    std::cout << A;

    return 0;
}

I want to pass my Variable A to function test and have that function replace the content of A with the content of local variable B , and then print that out. How should this be done?

reference to array should be this

void test(char (&testChar)[3]){
 // code
}

But in your test function testChar = B; expression is wrong. you need to explicitly string copy (second reference doesn't change in C++, not like pointer) for this you may like to read: C++ Reference, change the refered variable

Edit : As @ChristianSjöstedt commented.

Python is "dynamic typed language" where type and value of variable can be change, Where as in C++ one you declare the type of a variable it doesn't change.

 i = 10         # reference to int 
 i = "name"     # reference to str

this is possible in Python but not in C++ (and C)

C/C++ are static language mean "statically typed language" . for example type of a variable can't be change and defined statically at compilation time.

int i = 10;

i in int can be char.

Dynamic type languages versus static type languages

"Passing an Array Reference in C++"

Assuming you want to pass a reference to an array to a function, and set the elements of that array to those stored in another one, you can use std::copy , since arrays are not assignable. It is better to use a template function to have a handle on the size of the array:

template <size_t N>
test( char (&testChar)[N] )
{
  char B[N] = {"BB"};
  stc::copy(B, B+N, testChar);
}

But I suggest you use std::array , which is copyable and assignable:

template <size_t N>
test(std::array<char,N>& testarray; )
{
  std::array<char, N> B = {"BB"};
  teasArray = B;
}

对于固定大小的数组使用std::array ,对于动态(可变长度)数组使用std::vector

This is the code you are probably looking for

#include <string.h>

void test(char *testChar){
    char B[3] = {"BB"};
    strcpy(testChar, B);
}

int main(int argc, const char * argv[])
{
    char A[3] = {"AB"};
    test(A);
    std::cout << A;

    return 0;
}

but there are all sorts of reasons why code like this is a bad idea. If you want to do string manipulation then you should start with the std::string class instead of getting into the horrible mess that is arrays and pointers in C++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM