使用指针从函数返回一个字符串

时间:2015-01-05 16:29:45

标签: c string function

我正在尝试读取函数中的字符串,然后将其返回到主程序并在那里打印。 问题是,当我在主程序中打印字符串时,似乎字符串数组中没有数据

我写的代码是:

#include <stdio.h>

char *getString(){
    char buff[10]; //String Array to be used within the function
    char *pbuff = &buff; //Pointer to the address
    printf("Enter the name: ");
    scanf("%s", buff);
    return pbuff; //Returns the pointer to the array
}

int main(){
    char MyString[10]; //string in the main program
    char *pMyString = (char*)malloc(sizeof(char) * 10); // Allocation for the memory for the pointer


    pMyString = &MyString; //pointer to the array


    *pMyString = getString();

    printf("%s", pMyString);

}

0 个答案:

没有答案