我可以通过函数更改已初始化的char指针吗? [英] Can I change an initialized char pointer via function?

查看:98
本文介绍了我可以通过函数更改已初始化的char指针吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的main.c:

#include <stdio.h>

void changeStuff(char *stuff){
    stuff=  "Hello everyone";
}

int main(int argc, char **argv) {
    char *stuff;
    changeStuff(stuff);
    printf(stuff);
    return 0;
}

构建此文件时,会收到以下警告:

When I build this, I get this warning:

warning: ‘stuff’ is used uninitialized in this function [-Wuninitialized]

当我运行该程序时,什么都没有打印.

When I run this program, nothing is printed.

由于似乎不可能在声明后定义没有值的char*,我该如何更改传递给函数的char*的值?

Since it does not seem possible to define a char* with no value after it has been declared, how do I change the value of a char* passed to a function?

推荐答案

在C语言中,函数参数按值传递.为了修改指针值,您需要将指针传递给指针,例如:

In C, function arguments are passed-by-value. In order to modify a pointer value, you need to pass a pointer to the pointer, like:

#include <stdio.h>

void changeStuff(char **stuff){
    *stuff=  "Hello everyone";
}

int main(int argc, char **argv) {
    char *stuff;
    changeStuff(&stuff);
    printf("%s\n", stuff);
    return 0;
}

请注意,直接将用户定义的值传递给printf()不是一个好主意.请参阅:如何利用格式字符串漏洞?

Note that it's not a good idea to directly pass user-defined values to printf(). See: How can a Format-String vulnerability be exploited?

这篇关于我可以通过函数更改已初始化的char指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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