Char*(指针)功能

bob*_*123 1 c char

我需要在函数中传入char*并将其设置为cstring值.我可以在函数中将其正确设置为字符串,但它似乎在首先调用char*函数的函数中没有正确打印出来.

int l2_read(char *chunk,int length)
{
    chunk = malloc( sizeof(char) * length);

    int i;
    for(i = 0; i < length; i++){
       char c;
       if(read(&c) < 0) return (-1); // this gets a single character
          chunk[i] = c;
    }

    printf("%s",chunk); // this prints fine
    return 1;
}


    // main
    char *string;
    int value = l2_read(string,16);
    printf("%s",chunk); // prints wrong
Run Code Online (Sandbox Code Playgroud)

Alo*_*hal 14

在C中,一切都按值传递.要记住的一般规则是,您不能更改传递给函数的参数的值.如果要传递需要更改的内容,则需要传递指针.

所以,在你的功能中,你想要改变chunk. chunkchar *.为了能够改变它的值char *,你需要传递一个指向它的指针,即char **.

int l2_read(char **chunkp, int length)
{
    int i;
    *chunkp = malloc(length * sizeof **chunkp);
    if (*chunkp == NULL) {
        return -2;
    }
    for(i = 0; i < length; i++) {
        char c;
        if (read(&c) < 0) return -1;
        (*chunkp)[i] = c;
    }
    printf("%s", *chunkp);
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

然后在main():

 char *string;
 int value = l2_read(&string, 16);
 if (value == 1) {
     printf("%s", string); /* corrected typo */
     free(string); /* caller has to call free() */
 } else if (value == -2) {
    /* malloc failed, handle error */
 } else {
    /* read failed */
    free(string);
 }
Run Code Online (Sandbox Code Playgroud)

传址值C是原因strtol(),strtod()等等,都需要char **endptr参数,而不是char *endptr-他们希望能够到设定char *值,第一个无效字符的地址,只有这样,他们可以影响一个char *在主叫方是接收指向它的指针,即接收一个char *.同样,在您的函数中,您希望能够更改char *值,这意味着您需要指向a的指针char *.

希望有所帮助.