简体   繁体   English

更改 char[] 数组的元素

[英]Changing an element of an array of char[]

I find strings or character arrays in C confusing, so I tend to make mistakes and errors while writing code.我发现 C 中的字符串或字符 arrays 令人困惑,所以我在编写代码时往往会犯错误和错误。 The below code takes in a character array and while printing, prints the fourth element as x .下面的代码接受一个字符数组,并在打印时将第四个元素打印为x

void printString(char stuff[]) {
    for (int i = 0; i < 5; i++) {
        if (i == 3) {
            stuff[i] = 'x';
        }
        printf("%c", stuff[i]);
    }
}

int main(void) {
    char z[] = "hello";
    printString(z); // output helxo

When trying to apply the same concept with an array of character arrays, you can't change the values当尝试对字符数组 arrays 应用相同的概念时,您无法更改值

void printStrings(char stuff[5][20]) {
    for (int i = 0; i < 5; i++) {
        if (i == 4) {
            stuff[i] = "Not Cool"; // Error: assignment to expression with array type
        }
        printf("%s\n", stuff[i]);
    }
}

int main(void) {
    char a[5][20] = {
        "Words",
        "More Words",
        "Letters",
        "Arrays",
        "Cool"
    }
}

Any help would be appreciated.任何帮助,将不胜感激。

PS Any links to a resource explaining character arrays and strings would also be helpful:) PS 任何指向解释字符 arrays 和字符串的资源的链接也会有所帮助:)

The = operator is not defined to copy the contents of one array to another. =运算符未定义为将一个数组的内容复制到另一个数组。 You either have to copy each array element individually in a loop:您要么必须在循环中单独复制每个数组元素:

for ( size_t i = 0; i < num_elements; i++ )
  dst[i] = src[i];

or you have to call a library function like strcpy (for arrays that contain strings) or memcpy (for arrays that don't contain strings), which does pretty much the same thing under the hood.或者您必须调用库 function 之类的strcpy (对于包含字符串的 arrays)或memcpy (对于 arrays,它在引擎盖下几乎没有包含字符串),

Arrays and array expressions in C are weird compared to other aggregate types like struct or union ;structunion等其他聚合类型相比, Arrays 和 C 中的数组表达式很奇怪; as part of that weirdness, array expressions are not allowed to be the target of an assignment operator.作为这种怪异的一部分,数组表达式不允许成为赋值运算符的目标。 Under most circumstances, an expression of type "array of T " is converted, or "decays", to an expression of type "pointer to T " and the value of the expression is the address of the first element of the array.在大多数情况下,“ T的数组”类型的表达式被转换或“衰减”为“指向T的指针”类型的表达式,并且表达式的值是数组第一个元素的地址。

This isn't arbitrary - Ritchie had a reason for making arrays behave this way - but it doesn't make it any less weird.这不是任意的——Ritchie 有理由让 arrays 以这种方式行事——但这并没有让它变得不那么奇怪。

When trying to apply the same concept with an array of character arrays, you can't change the values当尝试对字符数组 arrays 应用相同的概念时,您无法更改值

Yes you can, just not the way you are doing it.是的,你可以,只是不是你这样做的方式。 You can't assign one array to another.您不能一个数组分配给另一个数组。 But you can use strcpy() instead to copy characters from one array to another, eg:但是您可以使用strcpy()将字符从一个数组复制到另一个数组,例如:

strcpy(stuff[i], "Not Cool");

Or better, strncpy() , eg:或者更好的是strncpy() ,例如:

strncpy(stuff[i], "Not Cool", 20);

When trying to apply the same concept with an array of character arrays, you can't change the values当尝试对字符数组 arrays 应用相同的概念时,您无法更改值

The problem is not that you cannot change the values.问题不在于您无法更改这些值。 It is exactly as the compiler tells you: you cannot assign to whole arrays.正如编译器告诉你的那样:你不能分配给整个 arrays。

Given this declaration:鉴于此声明:

 void printStrings(char stuff[5][20]) {

Parameter stuff is a pointer to an array of 20 char s.参数stuff是一个指向 20 个char数组的指针。 stuff[4] therefore designates an array, and is not an lvalue -- you cannot assign to it. stuff[4]因此指定一个数组,而不是左值——你不能分配给它。 But you can modify its elements via assignment, or, more generally, you can modify its contents via appropriate functions, such as strcpy() .但是你可以通过赋值来修改它的元素,或者更一般地说,你可以通过适当的函数来修改它的内容,比如strcpy()

    stuff[4][0] = 'f';

I find strings or character arrays in C confusing我发现 C 中的字符串或字符 arrays 令人困惑

There are some confusing things about C strings, but one thing that I hope will help you is to recognize that strings and character arrays are not the same thing.关于 C 字符串有一些令人困惑的事情,但我希望能帮助您的一件事是认识到字符串和字符 arrays 不是一回事。 Strings are values that may be represented by the contents of character arrays.字符串是可以由字符 arrays 的内容表示的值。 Even when a character array contains a string (because any one or more of its elements has value '\0' and therefore serves as a string terminator) the array itself is not the string, even though we are sometimes a bit lax with our language around such things.即使一个字符数组包含一个字符串(因为它的任何一个或多个元素具有值 '\0' 并因此用作字符串终止符),数组本身也不是字符串,即使我们有时对我们的语言有点松懈围绕这样的事情。

Compound that with the fact that string literals have their own quirks, and arrays in general have quirks, and yes, there is plenty of room for confusion.再加上字符串文字有自己的怪癖,而 arrays 通常也有怪癖,是的,有很大的混淆空间。

The misconcept you have comes from the fact that you think that arrays are assignable, as are other objects.您的误解来自您认为 arrays 是可分配的,其他对象也是如此。 The C concept of array is a bit poor.数组的 C 概念有点差。 When you use the array identifier as a whole, you are not meaning the whole array, but just the (constant) address of it's first element (like with a pointer), so you cannot write something like:当您将数组标识符作为一个整体使用时,您并不是指整个数组,而只是它的第一个元素的(常量)地址(如指针),因此您不能编写如下内容:

char A[100], B[100];
A = B; /* error, A is a constant address (the address of A array) and B is a constant address, so A is not assignable. */

This is very efficient when passing arrays as parameters to functions, because it avoids to copy the whole array into the parameter list, and just a pointer is put in it.这在将 arrays 作为参数传递给函数时非常有效,因为它避免了将整个数组复制到参数列表中,而只是在其中放入了一个指针。 It also freed the original C implementors to write code to copy full blocks of memory when you assigned arrays (which is something that is scarcely used in programming)当您分配 arrays 时,它还释放了原始 C 实现者编写代码来复制 memory 的完整块(这在编程中很少使用)

To provide a solution, they wrote a family of functions that allow you to copy arrays or strings (which are arrays of char ).为了提供解决方案,他们编写了一系列函数,允许您复制 arrays 或字符串(它们是char的 arrays )。 You can use:您可以使用:

#include <string.h>
...
       strcpy(stuff[i], "Not cool");

and this will make the string literal to be copied at position of the i -esim array element.这将使字符串文字被复制到i -esim 数组元素的 position 处。

You stated that你说

When trying to apply the same concept with an array of character arrays, you can't change the values当尝试对字符数组 arrays 应用相同的概念时,您无法更改值

but in your first case you were assigning a single char object (which as an scalar value is assignable in C) when you switched to arrays, you got to the fact that a whole array is not assignable in C.但是在第一种情况下,当您切换到 arrays 时,您分配了单个char object(在 C 中作为标量值可分配),您会发现整个数组在 Z0D61F83701D412D570B8 中不可分配。

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

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