gpt4 book ai didi

c - c中的字符串更新

转载 作者:太空宇宙 更新时间:2023-11-04 02:02:18 25 4
gpt4 key购买 nike

这是一个演示从函数中获取字符串值的示例程序

  1. 可以在被调用函数内部分配内存并返回
  2. 可以在调用函数内部分配内存,被调用函数只更新它。

我遇到了第二种方式的问题。有什么解决方法吗?

/*
* main.c
*
* Created on: Sep 6, 2014
* Author: Murtaza
*/
#include<stdio.h>
#include<stdlib.h>
char* someFunc1();
void someFunc2(char* str);
void firstApproach();
void secondApproach();
int main()
{
firstApproach();
printf("\n");
secondApproach();
return 0;
}
char* someFunc1()
{
char *str = (char*)malloc(sizeof(char)*10);
str = "HELLO";
return str;
}
void someFunc2(char* str)
{
str = "Hello";
}
void secondApproach()
{
char *str = (char*)malloc(sizeof(char)*10);
someFunc2(str);
printf(str);
printf("heythere");
}
void firstApproach()
{
char *str;
str=someFunc1();
printf(str);
printf("wassup");
}

请告诉我为什么第二种方法不起作用。谢谢!我的输出是:

HELLOwassup
h>heythere

我的预期输出应该是

HELLOwassup
Helloheythere

最佳答案

void someFunc2(char* str)  
{
str="Hello"; //-----the variable str is local to this function, thus it goes out of scope as
// soon as the function returns
}
void secondApproach()
{
char *str=(char*)malloc(sizeof(char)*10);
someFunc2(str);
printf(str); // -------------- here the value inside str is some garbage value.
printf("heythere");
}

CORRECTION :



void someFunc2(char **str )
{
*str = "hello";
}

void secondApproach()
{
char *str=(char*)malloc(sizeof(char)*10);
someFunc2(&str); // pass the address of the string
printf("%s", str);
printf("heythere");
}

关于c - c中的字符串更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25698664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com