简体   繁体   English

char a []和char * a之间的区别?

[英]difference between char a[] and char *a?

#include <bits/stdc++.h>
using namespace std;

// Function to copy one string in to other
// using recursion
void myCopy(char str1[], char str2[], int index = 0)
{
    // copying each character from s1 to s2
    s2[index] = s1[index]; 

    // if string reach to end then stop 
    if (s1[index] == '\0')  
        return;

    // increase character index by one
    myCopy(s1, s2, index + 1); 
}

// Driver function
int main()
{
    char s1[100] = "GEEKSFORGEEKS";
    char s2[100] = "";
    myCopy(s1, s2);
    cout << s2;
    return 0;
}

I did not understand how the value of s2 is getting printed ....since we passed address of s1 and s2 to function mycopy(). 我不明白s2的值是如何打印的....因为我们将s1和s2的地址传递给函数mycopy()。 mycopy() has two local array str1 and str2 as argument,so i was thinking two local array with values of s1 and s2 will be created.(call by values) mycopy()有两个局部数组str1和str2作为参数,因此我想创建两个具有s1和s2值的局部数组。(按值调用)

Shouldn't the function prototype be mycopy(char *s1,char *s2) for printing s2.(call by reference) 函数原型不应该是用于打印s2的mycopy(char * s1,char * s2)。(按引用调用)

void myCopy(char&str1 [],char&str2 [],int索引= 0)

To be able to reinitialize your parameter (array s2 in this case) you need to pass it by reference . 为了能够重新初始化参数(在这种情况下为数组s2 ),您需要通过reference传递它

Like this: 像这样:

void myCopy(char &str1[], char &str2[], int index = 0)

This means that myCopy() will use arrays as they are, otherwise it will create local duplication of them. 这意味着myCopy()将按myCopy()使用数组,否则将创建它们的本地复制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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