【问题标题】:Why can't I access my pointer of char through my function?为什么我不能通过我的函数访问我的 char 指针?
【发布时间】:2022-11-13 08:15:49
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h> 
#include <unistd.h>
#include <ctype.h>
#include <assert.h>


void *process(char **nbE) 
{

char buffer[8] = "test";

*nbE = &buffer[0];
printf("%s\n", *nbE);

}


int main(int argc, char **argv) 
{


char *str;
process(&str);

printf("%s\n", str);


}

我试图通过使其指向数组中第一个字符的地址来获取 main() 中 *nbE 的值。 但它返回一些未编码的东西,为什么?

我这样做的方法是什么?

注意:我知道我可以做得更简单,我有一个更复杂的代码,这是一个小例子

基本上我的数组中有一些有趣的东西,想通过 char* 变量将它传递给我的主函数

【问题讨论】:

    标签: arrays c


    【解决方案1】:
     char buffer[8] = "test";
    

    创建一个函数本地的字符串,一旦从该函数返回,它就会被销毁。做这个

     static char buffer[8] = "test";
    

    或者

      char * buffer = strdup("test");
    

    在第二种情况下,您必须在完成后释放字符串

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-02
      • 1970-01-01
      • 2014-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多