c - 复制字符的指针问题
问题描述
我在使用 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;
}
解决方案
问题是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
在另一个变量中,并返回它而不是你增加的那个。
推荐阅读
- python - 如何使用 Twitter API 从电子邮件地址中查找帐户?
- html - 以角度创建递归动态扩展导航的正确方法是什么,以及如何正确切换其菜单项?
- spring-boot - Axios 身份验证请求无法将标头发送到 Spring Boot
- javascript - 如果为真,则 jquery 对话框发布
- c# - 收到错误消息“类型“XmlNode”在未引用的程序集中定义。”,但引用了适当的程序集
- c - Makefile 编译所有 src 并生成静态库
- r - 条形图的频率作为独立列表
- bash - 将进程替换与此处的字符串相结合
- r - 如何在R中循环使用多个数据库
- javascript - 验证提交按钮上没有附加文件上传