简体   繁体   English

操作二维数组中的元素

[英]Manipulating elements in a 2D array

I am trying to manipulate the elements in a 2D array我正在尝试操作二维数组中的元素

#include <stdio.h>

main()
{
    char arr[][30] = {"hello", "goodbye"};
    printf("%s\t%s\n",arr[0], arr[1]);
    arr[0] = arr[1];
    printf("%s\t%s\n",arr[0], arr[1]);
}

incompatible types when assigning to type ‘char[30]’ from type ‘char *’

I am new to C and coming from an OO background, so my knowledge of pointers is still very fundamental.我是 C 的新手,并且来自 OO 背景,所以我对指针的了解仍然非常基础。

I understand this can be done using an array of pointers, but would like to know how to perform this operation with 2D arrays我知道这可以使用指针数组来完成,但想知道如何使用 2D arrays 执行此操作

Thank you for any clarification谢谢你的澄清

You need char* arr[] instead, since you can't assign an array to another array.您需要char* arr[]代替,因为您不能将数组分配给另一个数组。

But whyyyyy?但是为什么?

Well, what would that mean?那么,这意味着什么? Should it copy over the elements?它应该复制元素吗? Use strncpy or memcpy for that.为此使用strncpymemcpy Or should it somehow "redirect" the previous array?还是应该以某种方式“重定向”先前的数组? That doesn't make sense, because an array is just a block of memory... what can you do with it, other than modify its contents?这没有意义,因为数组只是 memory 的一个......除了修改它的内容之外,你能用它做什么? Not much, You can, however, have a pointer to the block, and change it to point somewhere else instead.不多,但是,您可以有一个指向该块的指针,并将其更改为指向其他地方。

But aren't arrays and pointers the same thing?但是 arrays 和指针不是一回事吗?

No!!不!! Why would they have two different names, then?那为什么他们会有两个不同的名字呢? :P Arrays can decay to pointers implicitly (the address of their first elements), but they're not the same thing! :P Arrays 可以隐式衰减到指针(它们的第一个元素的地址),但它们不是一回事! Pointers are just addresses , whereas arrays are a block of data.指针只是地址,而 arrays数据块。 They have no relation to each other, other than the implicit conversion.除了隐式转换之外,它们彼此没有任何关系。 :) :)

arr[0] is, itself, an array. arr[0]本身就是一个数组。 C does not support assigning to arrays. C 不支持分配给 arrays。 If you mean to copy the contents of array arr[1] into the the array arr[0] , use memcpy :如果您打算将数组arr[1]的内容复制到数组arr[0]中,请使用memcpy

memcpy(&arr[0][0], &arr[1][0], sizeof arr[0]);

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

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