首页 > 解决方案 > 复制字符的指针问题

问题描述

我在使用 getstring 时遇到问题。不知道为什么不起作用,主函数printf中的输出没有放空

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

char *getstring(unsigned int len_max)
{
    char *linePtr = malloc(len_max + 1); // Reserve storage for "worst case."
    if (linePtr == NULL) { return NULL; }
    int c = 0;
    unsigned int i = 0;
    while (i < len_max && (c = getchar()) != '\n' && c != EOF){
        *linePtr++ = (char)c;
        i++;
    }

    *linePtr = '\0';

    return linePtr;
}

int main()
{

    char *line = getstring(10);

    printf("%s", line);
    free(line);

    return 0;
}

标签: c

解决方案


问题是linePtr指向包含输入行的字符串的结尾,而不是开头,因为您linePtr++在循环期间这样做。

而不是递增linePtr,用于linePtr[i++]在循环期间存储每个字符。

char *getstring(unsigned int len_max)
{
    char *linePtr = malloc(len_max + 1); // Reserve storage for "worst case."
    if (linePtr == NULL) { return NULL; }
    int c = 0;
    unsigned int i = 0;
    while (i < len_max && (c = getchar()) != '\n' && c != EOF){
        linePtr[i++] = (char)c;
    }

    linePtr[i] = '\0';

    return linePtr;
}

如果你真的需要通过增加一个指针来做到这一点,你需要将原始值保存linePtr在另一个变量中,并返回它而不是你增加的那个。


推荐阅读