Search code examples
carrayscopyc-strings

How to copy values for the char **a - C


In this code:

#include <stdio.h>
void givetome(char** skey);
int main(int argc, const char * argv[]) {
    char *skey[5];
    givetome(&skey[5]);
    printf("%s\n",*skey);
    return 0;
}
void givetome(char **skey){
    char f[5]={'g','h','f','d','s'};
    for (int i=0; i<5; i++) {
        *skey[i]=f[i];
    }
}

I'm not able to copy the values from the vector "f" to the vector "skey". Someone to help?


Solution

  • With givetome(&skey[5]), you start assigning characters at the end of skey and thereby exceed array bounds then. With givetome(&skey[0]) or simply givetome(skey) it should work.

    BTW: as you print the result as a string, you'll need to terminate the string with '\0':

    #include <stdio.h>
    void givetome(char* skey);
    int main(int argc, const char * argv[]) {
        char skey[6];
        givetome(skey);
        skey[5] = '\0';
        printf("%s\n",skey);
        return 0;
    }
    void givetome(char *skey){
        char f[5]={'g','h','f','d','s'};
        for (int i=0; i<5; i++) {
            skey[i]=f[i];
        }
    }