字符 *(指针)函数 [英] Char * (pointer) function

查看:21
本文介绍了字符 *(指针)函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to pass in a char * in a function and have it set to a cstring value. I can properly set it as a string in the function, but it doesn't seem to print out correctly in the function that called the char * function in the first place.

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

推荐答案

在 C 中,一切都是按值传递的.要记住的一般规则是,您不能更改传递给函数的参数的值.如果你想传递一些需要改变的东西,你需要传递一个指向它的指针.

In C, everything is passed by value. A general rule to remember is, you can't change the value of a parameter passed to a function. If you want to pass something that needs to change, you need to pass a pointer to it.

因此,在您的函数中,您想要更改 chunk.chunkchar *.为了能够更改 char * 的值,您需要传递一个指向它的指针,即 char **.

So, in your function, you want to change chunk. chunk is char *. To be able to change the value of the char *, you need to pass a pointer to that, i.e., 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;
}

然后在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);
 }

C中的传值是strtol()strtod()等需要char **endptr 参数而不是 char *endptr—他们希望能够将 char * 值设置为第一个无效字符的地址,以及他们可以影响的唯一方法调用者中的一个char *就是接收一个指向它的指针,即接收一个char *.同样,在您的函数中,您希望能够更改 char * 值,这意味着您需要一个指向 char * 的指针.

Pass-by-value in C is the reason why strtol(), strtod(), etc., need char **endptr parameter instead of char *endptr—they want to be able to set the char * value to the address of the first invalid char, and the only way they can affect a char * in the caller is to receive a pointer to it, i.e., receive a char *. Similarly, in your function, you want to be able to change a char * value, which means you need a pointer to a char *.

希望对您有所帮助.

这篇关于字符 *(指针)函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆