这是我的代码:
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我正在尝试读取包含名称的字符串.用户可以输入字符直到他输入':'.我的代码出了什么问题?
1> user3121023..:字符串需要终止,
'\0'
因此允许额外的字符.重新分配时,最好在重新分配失败时使用另一个指针.#include#include int main(void) { int i=0; int size=1; char *pntName=NULL;//a pointer to an array of chars. char *temp=NULL;//a temporary pointer pntName = malloc( size + 1);//allocate space for two char one for the '\0' to terminate the string while(1){ size++; temp = realloc(pntName, size + 1);//reallocat space. if ( temp == NULL) { printf ( "error allocating memory"); free ( pntName); return 1; } pntName = temp; if ( ( scanf("%c",&pntName[i])) == 1) { i++; pntName[i] = '\0'; // terminate the string if ( pntName[i-1] == ':') { break; } } else { break; } } printf ( "\n%s\n", pntName); free ( pntName);// release memory return 0; }