字符串函数参数 [英] String in function parameter

查看:102
本文介绍了字符串函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  INT的main()
{
        char *之X =HelloWorld的;
        烧焦Y [] =HelloWorld的;        X [0] ='Z';
        // Y [0] ='M';        返回0;
}

在上面的程序,的HelloWorld 将在只读部分(即字符串表)。 X 将指向该只读部分,所以尝试修改值将是不确定的行为。

将在堆栈中分配和的HelloWorld 将被复制到内存。所以修改Ÿ将工作正常。 字符串文字:指针与字符数组

这里是我的问题:

在下面的程序,无论是的char *改编字符ARR [] 导致段错误如果内容改性。

  void函数(字符ARR [])
// void函数(字符* ARR)
{
   改编[0] =X;
}
诠释的main()
{
   功能(MyString的);
   返回0;
}


  1. 如何在不同的功能参数方面?

  2. 无记忆将函数参数的分配?

请分享你的知识。


解决方案

在函数参数列表,字符ARR [] 是绝对等同于字符* ARR ,所以对定义和对声明的是等价的。

  void函数(字符ARR []){...}
void函数(字符* ARR){...}void函数(ARR的char []);
void函数(字符* ARR);

问题是调用的上下文。您提供的字符串文字的功能;字符串不能修改;你的函数尝试修改字面它被赋予的字符串;你的程序调用未定义的行为而坠毁。所有犹太完全

款待字符串文字,好像他们是静态常量字符文字[] =字符串; ,不要试图对它们进行修改

int main()
{
        char *x = "HelloWorld";
        char y[] = "HelloWorld";

        x[0] = 'Z';
        //y[0] = 'M';

        return 0;
}

In the above program, HelloWorld will be in read-only section(i.e string table). x will be pointing to that read-only section, so trying to modify that values will be undefined behavior.

But y will be allocated in stack and HelloWorld will be copied to that memory. so modifying y will works fine. String literals: pointer vs. char array

Here is my Question:

In the following program, both char *arr and char arr[] causes segmentation fault if the content is modified.

void function(char arr[])
//void function(char *arr)
{
   arr[0] = 'X';
}        
int main()
{
   function("MyString");    
   return 0;
}

  1. How it differs in the function parameter context?
  2. No memory will be allocated for function parameters??

Please share your knowledge.

解决方案

Inside the function parameter list, char arr[] is absolutely equivalent to char *arr, so the pair of definitions and the pair of declarations are equivalent.

void function(char arr[]) { ... }
void function(char *arr)  { ... }

void function(char arr[]);
void function(char *arr);

The issue is the calling context. You provided a string literal to the function; string literals may not be modified; your function attempted to modify the string literal it was given; your program invoked undefined behaviour and crashed. All completely kosher.

Treat string literals as if they were static const char literal[] = "string literal"; and do not attempt to modify them.

这篇关于字符串函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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