简体   繁体   English

我如何将二维数组分配给其他临时二维数组…? 在C编程中

[英]How can i assign a two dimensional array into other temporary two dimensional array…?? in C Programming

Hi I am trying to store the contents of two dimensional array into a temporary array.... How is it possible... I don't want looping over here, as it would add an extra overhead.. Any pointer notation would be good. 嗨,我正在尝试将二维数组的内容存储到一个临时数组中。...怎么可能...我不想在这里循环,因为这会增加额外的开销。.任何指针符号都是好。

struct bucket
{
   int nStrings;       
   char strings[MAXSTRINGS][MAXWORDLENGTH];
};

void func()
{
   char **tArray;
   int tLenArray = 0;
   for(i=0; i<TOTBUCKETS-1; i++)
   {
      if(buck[i].nStrings != 0)
      {
         tArray = buck[i].strings;
         tLenArray = buck[i].nStrings;
      }
   }
}

The error here i am getting is:-
[others@centos htdocs]$ gcc lexorder.c
lexorder.c: In function âlexSortingâ:
lexorder.c:40: warning: assignment from incompatible pointer type

Please let me know if this needs some more explanaition... 请让我知道是否需要更多说明...

You can use memcpy or wrap it in a struct and use assignment on the structs, but any way you do it, you'll effectively be looping over all the elements. 您可以使用memcpy或将其包装在struct并在struct使用赋值,但是通过任何方式,您都将有效地遍历所有元素。 That's fundamental. 这是根本。

The compiler issue is that the notation array[...][...] is not the same as char * *. 编译器问题是表示法array [...] [...]与char * *不同。 The char ** notation is pointer to a pointer. char **符号是指向指针的指针。

For example; 例如;

char ** pA;
pA = malloc(10);

pA[0] is a pointer pA [0]是一个指针

in the case of array[...][...] 如果是数组[...] [...]

array[0] is not a pointer. array [0]不是指针。 It is a char. 它是一个字符。

If you want to do what you are trying then you you need declare strings as char ** and initialize your structure like this. 如果要执行尝试的操作,则需要将字符串声明为char **并像这样初始化结构。

struct bucket
{
    int nStrings;       
    char** strings;
};

struct bucket buck;

buck.strings = (char **)malloc(MAXSTRINGS);

for(i = 0; i < MAXSTRINGS; i++)
    buck.strings[i] = (char*)malloc(MAXWORDLENGTH)

You mean cloning the array right? 您的意思是克隆数组吗?
Unfortunately, I don't think there is a way to clone an array in C without looping through all items in the array and making a copy of them somewhere else. 不幸的是,我认为没有一种方法可以在C中克隆数组而不循环遍历数组中的所有项目并在其他地方制作它们的副本。
The main problem is that since they are pointers, any thing you do to simply copy the contents would just copy the addresses and you would have a reference, not a clone. 主要问题在于,由于它们是指针,因此您仅复制内容所做的任何事情都将仅复制地址,并且您将拥有引用而不是克隆。

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

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