在C中的函数内部修改char数组 [英] Modifying a char array inside a function in C

查看:417
本文介绍了在C中的函数内部修改char数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我最近一直在使用C,并且一直在尝试了解按值/引用传递的复杂性以及在函数内部操纵传入变量的能力.但是,我遇到了以下障碍:

So I've been playing around with C lately and have been trying to understand the intricacies of passing by value/reference and the ability to manipulate a passed-in variable inside a function. I've hit a road block, however, with the following:

void modifyCharArray(char *input)
{
    //change input[0] to 'D'
    input[0] = 'D';
}

int main()
{
    char *test = "Bad";
    modifyCharArray(test);
    printf("Bad --> %s\n", test);
}

因此,想法是只修改函数内部的char数组,然后在修改完成后打印出该数组.但是,这失败了,因为我所做的只是修改传入的input的值,而不是实际的内存地址.

So the idea was to just modify a char array inside a function, and then print out said array after the modification completed. However, this fails, since all I'm doing is modifying the value of input that is passed in and not the actual memory address.

简而言之,我有什么方法可以将char *input引入函数并修改其原始内存地址,而无需使用string.h中的memcpy之类的东西?

In short, is there any way I can take in a char *input into a function and modify its original memory address without using something like memcpy from string.h?

推荐答案

简而言之,我有什么方法可以将char *input引入函数并修改其原始内存地址,而无需使用string.h中的memcpy之类的东西?

In short, is there any way I can take in a char *input into a function and modify its original memory address without using something like memcpy from string.h?

是的,可以.您的函数modifyCharArray做正确的事.您所看到的是由于以下事实造成的:

Yes, you can. Your function modifyCharArray is doing the right thing. What you are seeing is caused by that fact that

char *test = "Bad";

在程序的只读存储器中创建"Bad",而test指向该存储器.更改它会导致行为不确定.

creates "Bad" in read only memory of the program and test points to that memory. Changing it is cause for undefined behavior.

如果要创建可修改的字符串,请使用:

If you want to create a modifiable string, use:

char test[] = "Bad";

这篇关于在C中的函数内部修改char数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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