strncpy函数修改
strncpy函数将指定字符串的指定长度复制到另外一个字符串,我想在前面加一个偏移量,从指定的位置开始复制,而不是从头开始,将指定位置的指定长度的指定字符串复制到另外一个字符串,可是最后的输出一直的空直接拿strncpy的源码进行修改的,求大佬帮忙解惑
char* strncpy_ch(char* dest, const char* source, size_t count,size_t begin)
{
char* new_dest = dest+begin;
char* start=new_dest;
while (count && (*new_dest++ = *source++))
count--;
if(count)
while (--count)
*new_dest++='\0';
return(start);
} 将指定位置的指定长度的指定字符串复制到另外一个字符串,
这个你不应该传入指定字符串后先移动指针到指定位置吗,然后剩下就和strncpy一样了 (char* dest, const char* source, size_t count,size_t begin)
你是要将参数1的指针的字符串的第begin位置开始拷贝count个到source吗?
想入门的新人 发表于 2022-4-24 16:32
(char* dest, const char* source, size_t count,size_t begin)
你是要将参数1的指针的字符串的第begin位 ...
是的 想入门的新人 发表于 2022-4-24 16:27
将指定位置的指定长度的指定字符串复制到另外一个字符串,
这个你不应该传入指定字符串后先移动指针到指定 ...
是的,所以我先把dest部分加了begin个单位,生成一个新的字符串new_dest,后面部分再复制,可以发现这个样子最后的输出是null 本帖最后由 jackz007 于 2022-4-24 18:03 编辑
偷懒写的
#include <stdio.h>
#include <string.h>
char * strncpy_ch(char * dest , const char * source , size_t count , size_t begin)
{
return strncpy(dest , & source , count) ;
}
自己写的
#include <stdio.h>
char * strncpy_ch(char * dest , const char * source , size_t count , size_t begin)
{
int c , i , n ;
for(c = n = 0 ; source ; n ++) ;
if(n > 0 && count < n) for(c = 0 , i = begin ; c < count && source ;) dest = source ;
dest = '\0' ;
return dest ;
} jackz007 发表于 2022-4-24 17:51
偷懒写的
自己写的
给大佬递茶{:5_105:} jackz007 发表于 2022-4-24 17:51
偷懒写的
自己写的
谢谢大佬,想通了,我偏移量加错地方了{:5_109:}
页:
[1]