gpt4 book ai didi

C - 如何读取未知长度的字符串

转载 作者:太空宇宙 更新时间:2023-11-04 00:36:19 24 4
gpt4 key购买 nike

<分区>

这是我的代码:

int main() {
int i=0;
int size=1;
char *pntName=NULL;//a pointer to an array of chars.
pntName = (char*) malloc(size *sizeof(char));//allocate sapce for the first char.
while(pntName[size-1]!=':'){
if(pntName!=NULL)//check the case couldn't allocate
printf("Error");
else{
if(i<size){//meaning there is space for new char.
scanf("%c",&pntName[i]);
i++;
}
else{//case we don't have enough space
size++;
pntName = (char*)realloc(pntName,(size)*sizeof(char));//reallocat space.
scanf("%c",&pntName[i]);
i++;
}
}
}
return 1;
}

我正在尝试读取一个包含名称的字符串。用户可以输入字符,直到他输入':'。我的代码有什么问题?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com