C 复制字符的指针出现问题
我对getstring有问题。我不知道为什么它不工作,在主函数printf的输出中不放任何东西C 复制字符的指针出现问题,c,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
#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;
}
#包括
#包括
#包括
char*getstring(无符号整数长度最大值)
{
char*linePtr=malloc(len_max+1);//为“最坏情况”保留存储空间
如果(linePtr==NULL){return NULL;}
int c=0;
无符号整数i=0;
而(i
问题在于linePtr
指向包含输入行的字符串的末尾,而不是开头,因为在循环过程中您确实需要linePtr++
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[i++]
在循环期间存储每个字符,而不是递增linePtr
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;
}
char*getstring(unsigned int len_max)
{
char*linePtr=malloc(len_max+1);//为“最坏情况”保留存储空间
如果(linePtr==NULL){return NULL;}
int c=0;
无符号整数i=0;
而(i
如果确实需要通过递增指针来执行此操作,则需要将
linePtr
的原始值保存在另一个变量中,并返回该值,而不是递增的值。问题在于linePtr
指向包含输入行的字符串的末尾,而不是开头,因为您在循环期间执行linePtr++
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[i++]
在循环期间存储每个字符,而不是递增linePtr
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;
}
char*getstring(unsigned int len_max)
{
char*linePtr=malloc(len_max+1);//为“最坏情况”保留存储空间
如果(linePtr==NULL){return NULL;}
int c=0;
无符号整数i=0;
而(i
如果确实需要通过递增指针来执行此操作,则需要将
linePtr
的原始值保存在另一个变量中,并返回该值,而不是递增的值。您的问题在于返回的是缓冲区的结尾,您需要保留一份linePtr的副本或为其编制索引。(您正在循环中递增它) 您的问题是要返回缓冲区的结尾,您需要保留一份linePtr副本或为其编制索引。(您正在循环中递增它) 您可能需要熟悉如何调试小程序:您可能需要熟悉如何调试小程序: