C ++将char数组传递给函数 [英] C++ passing char array to function

查看:338
本文介绍了C ++将char数组传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我宁愿只使用字符串,但我们不应该那样做,因为老师讨厌它们,并希望我们找出避免它们的方法。因此,我研究了使用结构,但本书并不遥远,当我跳过时,她讨厌它。所以我正在考虑这样做:

I would rather just use a string, but we aren't supposed to as the teacher hates them and wants us to figure out ways to avoid them. So I looked into using a struct, but we aren't that far in the book and she hates it when I skip ahead. So I was thinking of doing this:

#include <iomanip>
#include <iostream>
#include <stdio.h>

using namespace std;

void myfunc(char& );

int main()
{
    char myname[12];
    cout<<"enter  a name ";
    cin>>myname;
    cout<<"myname is "<<myname;

    cout<<"myname is " << myfunc(myname);

    getchar();
    getchar();
    return 0;
}

void myfunc(char &myname1)
{
    myname1 = "Billy"
}

但这不起作用,我也不知道为什么。

But this doesn't work and I don't know why.

推荐答案

一种方法是这样:

void myfunc(char *myname1)
{
    strcpy(myname1,"Billy");
}   

您还需要将main更改为:

You will also need to change your main to:

myfunc(myname);
cout<<"myname is " << myname;

但是您必须注意不要溢出初始缓冲区。

However you have to be careful not to overflow your initial buffer.

原始代码不起作用的原因是,您无法将字符串分配给 char 指针。相反,您必须将字符串复制到 char *

The reason why your original code doesn't work is because you can't assign strings to char pointers. Instead you must copy the string to the char*.

这篇关于C ++将char数组传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆