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

标签 c

<分区>

这是我的代码:

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;
}

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

最佳答案

字符串需要以 '\0' 结束,因此允许一个额外的字符。重新分配时最好使用另一个指针,以防重新分配失败。

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

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;
}

关于C - 如何读取未知长度的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34296476/

相关文章:

复制 SRC 目录并为所有 c 库函数添加前缀

c++ - 如何在 C 中反转以下算法

c - 使用 malloc 具有 X 和 y 坐标的 N 边多边形

对 C 中的 typedef 的困惑

c++ - 我如何使用 void** 函数 (void**)

c - 一个简单的 float 序列化示例的问题

c - XCode 分配不适用于 C?

c++ - 使用 Arduino 上的 atoi 和 itoa 从 int 转换为字节数组然后返回 int 进行传输

c - 通过 C 中的管道使用动态数组写入和读取结构

c - 如何返回指向 C 中分配的数据结构的指针?