在C语言中将字符串的一部分复制到另一部分
我在尝试将字符串的一部分复制到另一部分时遇到问题。给定这两个字符指针:在C语言中将字符串的一部分复制到另一部分,c,strstr,strncpy,ptrdiff-t,C,Strstr,Strncpy,Ptrdiff T,我在尝试将字符串的一部分复制到另一部分时遇到问题。给定这两个字符指针: line points at string cointaining: "helmutDownforce:1234:44:yes" username points at: NULL 下面是我的函数,它将这些指针作为输入: char* findUsername(char* line, char* username){ char* ptr = strstr(line, ":"); ptrdiff_t index
line points at string cointaining: "helmutDownforce:1234:44:yes"
username points at: NULL
下面是我的函数,它将这些指针作为输入:
char* findUsername(char* line, char* username){
char* ptr = strstr(line, ":");
ptrdiff_t index = ptr - line;
strncpy(username, line, index);
return username;
}
我在strncpy期间遇到分段错误。怎么会?我想要的结果是函数返回一个指向包含helmutDownforce的字符串的指针。根据ofstrncpy
:
the destination string dest must be large enough to receive the copy
因此,在调用strncpy
之前,必须先使用malloc
为username
分配一些内存,然后再根据strncpy
调用strncpy:
the destination string dest must be large enough to receive the copy
因此,在调用strncpy之前,必须先使用malloc
为username
分配一些内存。此函数分配并返回一个新字符串,因此为了避免内存泄漏,调用函数必须负责最终释放它。如果行中没有分隔符冒号,它将返回NULL
char* findUsername(char* line){
char* ptr = strchr(line, ':');
/* check to make sure colon is there */
if (ptr == NULL) {
return NULL;
}
int length = ptr - line;
char *username = malloc(length+1);
/* make sure allocation succeeded */
if (username == NULL) return NULL;
memcpy(username, line, length);
username[length] = '\0';
return username;
}
此函数分配并返回一个新字符串,因此为了避免内存泄漏,调用函数必须负责最终释放它。如果行中没有分隔符冒号,它将返回NULL
char* findUsername(char* line){
char* ptr = strchr(line, ':');
/* check to make sure colon is there */
if (ptr == NULL) {
return NULL;
}
int length = ptr - line;
char *username = malloc(length+1);
/* make sure allocation succeeded */
if (username == NULL) return NULL;
memcpy(username, line, length);
username[length] = '\0';
return username;
}
您是否正在传递指向strncpy()
的NULL
-指针?寻求调试帮助的问题(“此代码为什么不工作?”)必须包括所需的行为、特定问题或错误以及在问题本身中重现该问题所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参阅:如何创建一个最小、完整且可验证的示例。将代码后调用到findUsername()
。是否传递指向strncpy()
的NULL
-指针?寻求调试帮助的问题(“此代码为什么不工作?”)必须包括所需的行为,一个特定的问题或错误,以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参阅:如何创建一个最小、完整且可验证的示例。将调用代码后放到findUsername()
。好奇:为什么在int length=ptr-line中使用typeint
代替OP的ptrdiff\u t
或size\u t
,(malloc()收到的类型
?好奇:为什么在int length=ptr-line中使用typeint
,代替OP的ptrdiff\u t
或size\u t
,(malloc()收到的类型?
?