用于复制字符的指针出现问题



我对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 = '';
return linePtr;
}
int main()
{
char *line = getstring(10);
printf("%s", line);
free(line);
return 0;
}

问题是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] = '';
return linePtr;
}

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

你的问题是你正在返回缓冲区的末尾,你需要保留一个linePtr的副本或索引它。(你在循环中递增它(;

最新更新