简体   繁体   English

将char数组分配给C中的char数组

[英]Assigning char array to char array in C

can you help me with this code, i am able to copy arr into arr2(from index 1 and further, i cannot figure index 0 till now), but some others can't.你能帮我写这段代码吗,我可以将 arr 复制到 arr2(从索引 1 开始,直到现在我无法计算索引 0),但其他一些不能。 Can you tell if anything's wrong here?你能告诉这里有什么问题吗?

#include <stdio.h>

int main(){
        char arr[] = "char_arr_one";
        char arr2[] = {arr};
        printf("%s\n%s\n", arr, arr2);
        int i;
        for(i=0;i<13;i++){
                printf("%c %c\n", arr[i], arr2[i+1]);
        }
}

this is working on my system!这是在我的系统上工作!

The C standard does not permit to assign an array to another array: C 标准不允许将数组分配给另一个数组:

char arr[] = "char_arr_one";
char arr2[] = {arr};        // This does not work.

Why it works on a specific implementation as you´d stated, I don´t know, but generally it should not be possible to compile that code without at least one warning.为什么它适用于您所说的特定实现,我不知道,但通常在没有至少一个警告的情况下编译该代码是不可能的。

So maybe you disabled or even ignored warnings?那么也许您禁用甚至忽略了警告?

One link to that context, here: Why should I always enable compiler warnings?指向该上下文的一个链接,此处: 为什么我应该始终启用编译器警告?

Nonetheless, this doesn´t bring you the desired result of copying the string "char_arr_one" into arr2 .尽管如此,这不会给您带来将字符串"char_arr_one"复制到arr2的预期结果。

If you want to store the string, stored inside of arr , in arr2 you can use strcpy in the header string.h :如果要存储存储在arr内部的字符串,则可以在arr2中使用strcpy在标头string.h

char arr[] = "char_arr_one";
char arr2[13];                // You need to provide the amount of elements, at least
                              // as much as are required to store the string inside arr
                              // the null character.
strcpy(arr2,arr);             // Copies the string in arr into arr2.

Note, that you need to specify the elements of arr2 , which need to be at least as much as are required to store the string of "char_arr_one" plus the terminating null character \\0 , when defining arr2 .请注意,你需要指定的元素arr2 ,这就需要至少不亚于需要存储的字符串"char_arr_one"加上终止空字符\\0定义时, arr2 In this case, arr2 needs to have at least 13 char objects.在这种情况下, arr2需要至少有 13 个char对象。

You could also "automatically" detect the size of arr by using the sizeof operator:您还可以使用sizeof运算符“自动”检测arrsizeof

char arr[] = "char_arr_one";
char arr2[sizeof(arr)];       // Automatically detects the size of `arr` and provides
                              // it for specify the required amount of elements for storing 
                              // the string in arr + the null character.

strcpy(arr2,arr);             // Copies the string in arr into arr2.

Beside that, the third argument of arr2[i+1] inside the printf call will get you into Undefined Behavior.除此之外, printf调用中arr2[i+1]的第三个参数将使您进入未定义的行为。 At the last iteration, it would print something what lies beyond the array of arr2 .在最后一次迭代中,它将打印超出arr2数组的内容。 So change that to arr2[i] .所以将其更改为arr2[i]


The corrected code shall be:更正后的代码应为:

#include <stdio.h>
#include <string.h>

int main(){
        char arr[] = "char_arr_one";
        char arr2[sizeof(arr)];

        strcpy(arr2,arr);

        printf("%s\n%s\n",arr,arr2);

        for(int i = 0; i < 13; i++){
                printf("%c %c\n", arr[i], arr2[i]);
        }

        return 0;
}

Output:输出:

char_arr_one
char_arr_one
c c
h h
a a
r r
_ _
a a
r r
r r
_ _
o o
n n
e e

in C you can't assign array to array.在 C 中,您不能将数组分配给数组。

You need to copy it yourself你需要自己复制

    char arr[] = "char_arr_one";
    char arr2[sizeof(arr)];

    memcpy(arr2, arr, sizeof(arr);

or或者

        for(size_t index = 0; index < sizeof(arr); index++)
        {
            arr2[index] = arr[index];
        }

If I make your example a bit less trivial (by adding another variable) the result is obvious.如果我让你的例子不那么琐碎(通过添加另一个变量),结果是显而易见的。 It does not work.这是行不通的。

#include <stdio.h>

int main(){
        char arr[] = "char_arr_one";
        char another[] = "it does not work for sure";
        char arr2[] = {arr};
        printf("%p %p\n", (void *)arr, (void *)arr2);
        printf("%s\n%s\n", arr, arr2);
        int i;
        for(i=0;i<13;i++){
                printf("0x%02hhx - '%c' 0x%02hhx, '%c'\n", arr[i], arr[i],
                  arr2[i], (arr2[i] >= 32 && arr2[i] <= 127) ? arr2[i] : ' ' );
        }
}

https://godbolt.org/z/dvLcqq https://godbolt.org/z/dvLcqq

And the result is:结果是:

0x7fff4a68b84f 0x7fff4a68b82f
char_arr_one
Oit does not work for sure
0x63 - 'c' 0x4f, 'O'
0x68 - 'h' 0x69, 'i'
0x61 - 'a' 0x74, 't'
0x72 - 'r' 0x20, ' '
0x5f - '_' 0x64, 'd'
0x61 - 'a' 0x6f, 'o'
0x72 - 'r' 0x65, 'e'
0x72 - 'r' 0x73, 's'
0x5f - '_' 0x20, ' '
0x6f - 'o' 0x6e, 'n'
0x6e - 'n' 0x6f, 'o'
0x65 - 'e' 0x74, 't'
0x20 - '' 0x20, ' '

i am able to copy arr into arr2(from index 1 and further, i cannot figure index 0 till now), but some others can't.我可以将 arr 复制到 arr2(从索引 1 开始,直到现在我无法计算索引 0),但其他一些则不能。 ..... .....

On what basis you are sure about this?你有什么根据? I do not see any code which is copying arr to arr2 from index 1 and further.我没有看到任何将arr从索引1复制到arr2以及更远的代码。

Look at the gcc compiler warning on the statement which is, as per you, copying arr to arr2 from index 1 :查看语句上的gcc编译器警告,根据您的说法,将arr从索引1复制到arr2

<source>:5:24: warning: initialization of 'char' from 'char *' makes integer from pointer without a cast [-Wint-conversion]

5 |         char arr2[] = {arr};

Meaning of this warning -此警告的含义 -
The array name arr decays to pointer and the pointer is converted to integer and assigned to the first element of arr2 (element at 0 th index of array arr2 ).数组名称arr衰减为指针,指针转换为整数并分配给arr2的第一个元素(数组arr20索引处的元素)。
Note that if the char is signed then the result of this assignment will be implementation defined 1) .请注意,如果char已签名,则此分配的结果将是实现定义的1)

The way the arr and arr2 placed in stack on your machine, you may be getting expected output but on a different platform/architecture you may get different result. arrarr2在您的机器上放置堆栈的方式,您可能会得到预期的输出,但在不同的平台/架构上,您可能会得到不同的结果。 Note that C language standards do not specify how a function local variables should be placed in stack.请注意,C 语言标准并未指定函数局部变量应如何放置在堆栈中。 The standards even do not have a single mention of memory segments (stack, heap etc.) in it.标准中甚至没有提到内存段(堆栈、堆等)。 These things are completely dependent on the underlying platform/architecture.这些东西完全依赖于底层平台/架构。 Standards only talk about the scope and life of variables.标准只讨论变量的范围和寿命。

Can you tell if anything's wrong here?你能告诉这里有什么问题吗?

Since you have omit the dimension of arr2 , the compiler computes it based on the size of the initializer.由于您省略了arr2的维度,编译器会根据初始值设定项的大小计算它。 The initializer of arr2 is having only 1 element. arr2的初始值设定项只有1元素。 So, the size of arr2 will be 1 ie arr2 is a char array with just one element.因此, arr2的大小将为1arr2是一个只有一个元素的char数组。 Here you accessing the arr2 beyond its size:在这里,您可以访问超出其大小的arr2

    for(i=0;i<13;i++){
            printf("%c %c\n", arr[i], arr2[i+1]);
                                      ^^^^^^^^^

Accessing an array beyond its size is undefined behavior .访问超出其大小的数组是未定义的行为 An undefined behavior includes it may execute incorrectly (either crashing or silently generating incorrect results), or it may fortuitously do exactly what the programmer intended.未定义的行为包括它可能会错误地执行(崩溃或静默地生成错误的结果),或者它可能恰好按照程序员的意图去做。


1) From C Standards#6.2.5p15 1) 来自 C 标准#6.2.5p15

15 The three types char, signed char, and unsigned char are collectively called the character types. The implementation shall define char to have the same range, representation, and behavior as either signed char or unsigned char.45)

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

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