2016-04-24 36 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); 
    } 
} 
相關問題