2016-04-24 32 views
0

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

in main: 

char *myString; 
changeString(myString); 


changeString(char *myString){ 

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

} 

感谢您使用C

+0

让它'字符**' –

+0

但我应如何改变内部机能的研究指针,因为我尝试过了,它没有工作.. – sponge

+0

我不想返回它 – sponge

回答

0

参数是按值传递。因此,要修改函数中的变量,您必须将指针传递给它。例如,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'; 
} 
+0

为什么降价?! –

0

在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); 
    } 
} 
相关问题