简体   繁体   中英

How to access elements of char array passed as a parameter to a function in c?

I have this function which receives a pointer to char array and initializes it to be len repetitions of "a":

void test(char ** s, int len) {
    *s = (char *)malloc(sizeof(char) * len);
    int i;
    for(i = 0; i < len; i++) {
        *(s[i]) = 'a';
    }
    printf("%s\n", *s);
}

in the main() I have this code:

char * s;
test(&s, 3);

but I get EXC_BAD_ACCESS (code=1, address=0x0) error when I run main() . The error occurs on the second iteration of the for loop in this line: *(s[i]) = 'a';

As far as I understand I'm not accessing the elements correctly, what is the correct way?

s is declared as a pointer to a pointer. In reality, it's a pointer to a pointer to the start of an array, but that cannot be inferred from the type system alone. It could just as well be a pointer to a start of an array of pointers, which is how s[i] treats it. You need to first derefence s (to get the pointer to the array's start), and then index on it:

(*s)[i] = 'a';

Also, as @MFisherKDX correctly pointed out in comments, if you're going to pass *s to printf or any other standard string-manipulation function, you have to turn into a proper C string by terminating it with a 0 character.

This more clearly shows what you should be doing, while staying close to your original code:

void test(char ** s, int len) {
    char *p = malloc(len);
    int i;
    for(i = 0; i < len; i++) {
        p[i] = 'a';
    }
    printf("%s\n", p);
    *s = p;
}

Note that sizeof(char) is always one by definition, and in C there's no need to cast the result of malloc() .

That code also has all your original problems in that it doesn't actually create a string that you can send to printf( "%s... ) . This fixes that problem:

void test(char ** s, int len) {
    char *p = malloc(len+1);
    int i;
    for(i = 0; i < len; i++) {
        p[i] = 'a';
    }
    p[i]='\0';
    printf("%s\n", p);
    *s = p;
}

And this is even easier, with no need to use a double- * pointer:

char *test(int len) {
    char *p = malloc(len+1);
    int i;
    for(i = 0; i < len; i++) {
        p[i] = 'a';
    }
    p[i]='\0';
    printf("%s\n", p);
    return(p);
}

Instead of assignment

*(s[i]) = 'a';

use this:

(*s)[i] = 'a';

But do not forget that C/C++ strings are null terminated

Or you can use this approach to get more readable code:

void test(char** s, int len) {
    // 1 char extra for zero
    char *str = (char*)malloc(sizeof(char) * (len+1));

    int i;
    for(i = 0; i < len; i++)
        str[i] = 'a';

    // zero terminated string
    str[len] = 0;

    printf("%s\n", str);

    *s = str;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM