首页 > 解决方案 > 将指针作为输出参数传递给函数

问题描述

我使用“pBuff”作为指针并将一个字符数组放入函数“myfunc”中。所以,在主函数中,我应该在 aBuff 中接收它。

但它不起作用..这里有什么问题?

#include <stdio.h>

void myfunc(void *pBuff, int &i);
int main()
{
    int len;
    char aBuff[2]={0};
    printf("Hello World");
    myfunc(aBuff,len);
    printf("aBuff %s", aBuff);

    return 0;
}

myfunc(void *pBuff, int &i){
    char a[2] = {'a', 'b'};
    i = 5;
    pBuff = &a;
}

char a[]应该作为主函数中的输出参数

标签: c++pointers

解决方案


您正在传递一个指向您的函数的指针,在您的函数内部,您将临时变量的地址分配a给该pBuff变量。原始aBuff变量不受影响。

当我们使用 c++ 时,使用字符串的更简单的解决方案是:

#include <iostream>

void myfunc(std::string& pBuff, int &i);
int main()
{
    int len;
    std::string aBuff;
    std::cout << "Hello World";
    myfunc(aBuff,len);
    std::cout << "aBuff " << aBuff;

    return 0;
}

void myfunc(std::string& pBuff, int &i){
    pBuff = "ab";
    i = 5;
}

如果你真的必须使用原始字符数组,那么这将是实现它的一种方法(注意删除 ,void*这里没有理由使用它):

myfunc(char *pBuff, int &i){
    strcpy(pBuff, "ab");
    i = 5;
}

如果您需要在aBuff数组中存储 2 个字符,则它需要 3 个字符而不是 2 个字符,因为您需要为空终止符留出空间,否则printf其他字符串函数将无法正常工作。


推荐阅读