简体   繁体   English

如何复制char ** a-C的值

[英]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". 我无法将值从向量“ f”复制到向量“ skey”。 Someone to help? 有人帮忙吗?

With givetome(&skey[5]) , you start assigning characters at the end of skey and thereby exceed array bounds then. 使用givetome(&skey[5]) ,您可以开始在skey的末尾分配字符,从而超出了数组范围。 With givetome(&skey[0]) or simply givetome(skey) it should work. 使用givetome(&skey[0])或简单地givetome(skey)都可以使用。

BTW: as you print the result as a string, you'll need to terminate the string with '\\0' : 顺便说一句:当您将结果打印为字符串时,您需要以'\\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];
    }
}

Lots of problems here. 这里有很多问题。

You defined skey as an array of pointers. 您将skey定义为指针数组。 What you want is an array of characters: 您想要的是一个字符数组:

char skey[5];

Then when you call the function: 然后,当您调用函数时:

givetome(&skey[5]);

You pass the address of the array element with index 5. The largest index in an array of size 5 is 4, so you're passing a pointer to one past the end of the array. 您通过索引5传递数组元素的地址。大小为5的数组中的最大索引为4,因此您要传递一个指向数组末尾的指针。 You want to pass the array by name, which passes in the address of the first element. 您要按名称传递数组,该名称将传递第一个元素的地址。

givetome(skey);

Then, since we've redefined skey , we need to change givetome to accept a char * . 然后,由于我们已经重新定义了skey ,因此需要更改givetome以接受char * Then when assigning, assign to skey[i] , not *skey[i] . 然后在分配时,分配给skey[i] ,而不是*skey[i]

You'll also have a problem printing because %s expects a string, which is defined as a null-terminated array of characters. 您还会遇到打印问题,因为%s需要一个字符串,该字符串定义为以空值结尾的字符数组。 The array doesn't contain a null byte, so printing will read past the end of the array. 该数组不包含空字节,因此打印将读取数组的末尾。 So add a null byte to the end of f and save room for it in skey . 因此,在f的末尾添加一个空字节,并在skeyskey

With all the changes, the code should look like this. 进行所有更改后,代码应如下所示。

#include <stdio.h>

void givetome(char *skey);

int main(int argc, const char * argv[]) {
    char skey[6];
    givetome(skey);
    printf("%s\n", skey);
    return 0;
}

void givetome(char *skey){
    char f[6]={'g','h','f','d','s', '\0'};
    for (int i=0; i<6; i++) {
        skey[i]=f[i];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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