为char的动态字符串分配内存

时间:2020-08-07 21:45:56

标签: c

我正在尝试创建一个函数,该函数将在用户按Enter键以外的任何键时动态分配内存。该代码编译时没有错误或警告(在gcc上),但无法正常工作...有人可以告诉我到底是哪里出了问题吗?

如果我修改函数以返回指向char i,e的指针,则代码将起作用

QMetaType::registerConverter<QObject*,CustomDataObject>( [] (QObject* qObjPtr) { CustomDataObject* dataPtr = qobject_cast<CustomDataObject*>( qObjPtr ); return (dataPtr == nullptr) ? CustomDataObject() : CustomDataObject( *dataPtr ) ; });

但是,我仍然对原始代码感到好奇,为什么不起作用,请多多关照。在此先感谢您抽出宝贵时间阅读本文。

char * getString(char * string);

2 个答案:

答案 0 :(得分:5)

string参数通过值传递给getString(),因此它是str变量的副本 ,因此getString()string本身所做的任何更改(如为其分配内存地址)都不会反映在原始str变量中。

要解决此问题,您需要改为通过指针传递string参数

如果realloc()失败,您还需要修复代码中的内存泄漏和访问冲突。

尝试一下:

#include <stdio.h>
#include <stdlib.h>

void getString(char ** string);

int main(void){

    char * str = NULL;

    printf("Write something:\n");
    getString(&str);
    printf("You wrote:\n");
    printf("%s\n", str);
    free(str);
    return 0;
}

void getString(char ** string){
    char ch, *newstr;
    int length = 0;

    if (string == NULL) {
        printf("ERROR: invalid parameter!!\n");
        return;
    }
    *string = NULL;

    do{
        if (scanf("%c", &ch) < 1) {
            ch = '\n';
        }

        newstr = (char *) realloc(*string, length + 1);
        if (newstr == NULL){
            printf("ERROR: memory could not be allocated!!\n");
            free(*string);
            *string = NULL;
            return;
        }
        *string = newstr;

        newstr[length] = ch;
        length++;
    }
    while (ch != '\n');

    (*string)[length - 1] = '\0';
}

答案 1 :(得分:0)

实施解决方案的更好方法。
您应该使用双指针作为getString的参数,它将存储来自用户的输入字符串。

#include <stdio.h> 
#include <stdlib.h>

void getString(char**); // function prototype

/* Main function */
int main()
{
    /* Pointer to point to the memory location
     * where input string will be stored */
    char *s=NULL;
    /* Call by reference,the function will place 
     * string in memory location where the pointer
     *  is pointing */
    getString(&s); 
    printf("s=%s\n",s);
    
    free(s);
    return 0;
}

/* getString function will
 * store each input character in
 * the allocated memory area. */
void getString(char** p)
{
    if(*p==NULL){
        if((*p=malloc(1*sizeof(char)))==NULL)
            exit(0);
    }

    int c; //Variable to store each input character
    size_t i=0; //Counter to keep track of the size of the input string

    while((c=getchar())!='\n' && c!=EOF){
        char* newp = realloc(*p,i+1);
        if(newp==NULL){
            fprintf(stderr,"realloc failed\n");
            free(p);
            exit(0);
        }
        *p = newp;
        *(*p+i)=c;
        i++;
    }
    *(*p+i)='\0'; //Null character to end the string.
}
相关问题