C:printf char*返回最后一个字符
我试图理解为什么在我的C:printf char*返回最后一个字符,c,arrays,pointers,printf,C,Arrays,Pointers,Printf,我试图理解为什么在我的printf() 如果删除'\0',我会得到如下结果: 在代码中 word[count-starts+1] = '\0'; 基本上是越界访问调用的 您应该将代码更改为 word[nb_char-1] = '\0'; 因为您已经分配了nb\u char字节,最后一个索引将是nb\u char-1 也就是说,在使用返回的指针之前,总是需要检查malloc() word[count-starts+1] = '\0'; 基本上是越界访问调用的 您应该将代码更
printf()
如果删除'\0'
,我会得到如下结果:
在代码中
word[count-starts+1] = '\0';
基本上是越界访问调用的
您应该将代码更改为
word[nb_char-1] = '\0';
因为您已经分配了nb\u char
字节,最后一个索引将是nb\u char-1
也就是说,在使用返回的指针之前,总是需要检查malloc()
word[count-starts+1] = '\0';
基本上是越界访问调用的
您应该将代码更改为
word[nb_char-1] = '\0';
因为您已经分配了nb\u char
字节,最后一个索引将是nb\u char-1
也就是说,总是需要检查malloc()是否成功
在使用返回的指针之前,根据NULL
检查返回值。如果删除\0
printf无法知道字符串是否结束,并将继续递增指针,直到它看到空值,您将冒出现分段错误的风险
对于结尾没有0的字符串,可以使用snprintf
char* extract_word()
{
char* sentences = "hi! i'm a banana!";
int starts = 4;
int ends = 12;
int count;
int nb_char = ends-starts+1;
char* word = malloc(nb_char);
printf("\n\n%d\n",ends-starts);
for(count = starts; count < ends;count++)
{
word[count-starts] = sentences[count];
printf("%c == \n",sentences[count]);
}
word[count-starts+1] = '\0';
printf("\n\n%s",word);
return word;
}
此外,对于您试图实现的目标,还有memcpy
或strncpy
查看手册页以了解更多详细信息。如果删除\0
printf无法知道字符串是否结束,并将继续递增指针,直到它看到空值,您将冒出现分段错误的风险
对于结尾没有0的字符串,可以使用snprintf
char* extract_word()
{
char* sentences = "hi! i'm a banana!";
int starts = 4;
int ends = 12;
int count;
int nb_char = ends-starts+1;
char* word = malloc(nb_char);
printf("\n\n%d\n",ends-starts);
for(count = starts; count < ends;count++)
{
word[count-starts] = sentences[count];
printf("%c == \n",sentences[count]);
}
word[count-starts+1] = '\0';
printf("\n\n%s",word);
return word;
}
此外,对于您试图实现的目标,还有memcpy
或strncpy
查看手册页了解更多详细信息。其他选项包括word[count start]='\0'
(考虑到在代码中使用变量,这对我来说比nb_char-1
更自然),或者使用calloc
代替malloc
@M.M,我引用了malloc(nb_char)代码>,但无论如何,这只是意见的问题。重要的是保持在一定的范围内。你说得对。我计算以避免覆盖循环中的最后一个字符,我计算错了,并且。谢谢您的帮助。其他选项包括word[count start]='\0'
(考虑到在代码中使用变量,这对我来说比nb_char-1
更自然),或者使用calloc
代替malloc
@M.M,我引用了malloc(nb_char)代码>,但无论如何,这只是意见的问题。重要的是保持在一定的范围内。你说得对。我计算以避免覆盖循环中的最后一个字符,我计算错了,并且。谢谢您的帮助。我不能使用string.h或任何其他库(除了stdio.h)来执行此操作。我不知道snprintf
。我会读的。我不能使用string.h或任何其他库,除了stdio.h来做这件事。我不知道snprintf
。我会读到的。