【问题标题】:Change string with malloc in other function在其他函数中使用 malloc 更改字符串
【发布时间】:2016-04-24 14:02:59
【问题描述】:

当我使用 malloc 时如何更改其他函数中的字符串?

in main: 

char *myString;
changeString(myString);


changeString(char *myString){

    myString = malloc((size) * sizeof(char));
    myString[1] = 'a';

}

谢谢

【问题讨论】:

  • 但是我应该如何改变函数内部的指针,因为我试过了,它没有用..
  • 我不想退货
  • 我在互联网上搜索过这个,但它不起作用或没有直接描述..
  • 您的函数在一块全新的内存上运行,该内存分配并存储在局部变量myString 中。这对调用者的字符串没有影响。此外,它会造成内存泄漏。对新分配内存的唯一引用是 myString 局部变量,该变量在函数终止时消失。对此有很多疑问:为什么在 C 函数中修改变量对调用者的变量没有影响。

标签: c string pointers malloc


【解决方案1】:

C 中的参数是按值传递的。因此,要修改函数中的变量,您必须将指针传递给它。例如,int *intchar **char *

void changeString(char **myString){
    // free(*myString); // add when myString is allocated using malloc()
    *myString = malloc(2);
    (*myString)[0] = 'a';
    (*myString)[1] = '\0';
}

【讨论】:

    【解决方案2】:

    在 main 中分配内存,然后将指向分配内存开始的指针传递给函数。
    还要将一个包含分配内存大小的变量传递给函数,这样可以确保新文本不会溢出分配的内存。
    修改后的字符串可从 main 获得。

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    void changeString(char *stringptr, int sz);
    
    int main(void)
    {
        const int a_sz = 16;
        /* allocate memory for string & test successful allocation*/
        char *myString = malloc(a_sz);
        if (myString == NULL) {
            printf("Out of memory!\n");
            return(1);
        }
    
        /* put some initial characters into String */
        strcpy(myString, "Nonsense");
        /* print the original */
        printf("Old text: %s\n", myString);
    
        /* call function that will change the string */
        changeString(myString, a_sz);
    
        /* print out the modified string */
        printf("New text: %s\n", myString);
    
        /* free the memory allocated */
        free(myString);
    }
    
    void changeString(char *stringptr, int sz)
    {
        /* text to copy into array */
        char *tocopy = "Sense";
        /* only copy text if it fits in allocated memory
           including one byte for a null terminator */
        if (strlen(tocopy) + 1 <= sz) {
            strcpy(stringptr, tocopy);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-02-21
      • 1970-01-01
      • 1970-01-01
      • 2012-10-09
      • 1970-01-01
      • 2013-03-07
      • 1970-01-01
      • 2016-06-19
      • 2014-10-29
      相关资源
      最近更新 更多