Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/grails/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C语言中将字符串的一部分复制到另一部分_C_Strstr_Strncpy_Ptrdiff T - Fatal编程技术网

在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的字符串的指针。

根据of
strncpy

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中使用type
int
代替OP的
ptrdiff\u t
size\u t
,(malloc()收到的类型
?好奇:为什么在
int length=ptr-line中使用type
int
代替OP的
ptrdiff\u t
size\u t
,(malloc()收到的类型?