简体   繁体   English

如何清除Char数组中的特定元素

[英]How to clear a particular element in Char array

I have two multi dimensional char arrays. 我有两个多维char数组。 They may have duplicates. 他们可能有重复。 I want to clear the duplicates in the second one. 我想清除第二个重复项。 will assigning the particular element in the second array to NULL, clears it or should I assign it to a "/0". 会将第二个数组中的特定元素分配为NULL,将其清除,或者我应将其分配为“ / 0”。

for(i=0; i<10; i++){
   for(j=0; j<10; j++){
      if(!strcmp(a[x][i], b[x][j])){
      b[x][j]=NULL;
   }
   i++;
}

Please give me your inputs. 请给我您的意见。

That really depends on a lot of things. 这确实取决于很多事情。

Are the strings malloc 'ed? 字符串malloc是ed吗? If they are you should probably free them and set the pointer to NULL. 如果它们是您可能应该free它们并将指针设置为NULL。 And then when you pass the cleaned up array, you need to check if the string is NULL , before you do what ever you need to do with it. 然后,当您传递清理后的数组时,您需要先检查字符串是否为NULL ,然后再执行所需的操作。

If the strings are static, or if you don't want to free them, because they are used else where, then you can set them to either NULL or '\\0' . 如果字符串是静态的,或者您不想释放它们(因为它们在其他地方使用),则可以将它们设置为NULL'\\0' If you choose the later, then you should check for strlen(s) == 0 or if s[0] == '\\0' . 如果选择后者,则应检查strlen(s) == 0s[0] == '\\0'

The thing is, you can do either, it probably doesn't mean much which you choose. 问题是,您可以选择执行任何一项操作,但这可能并不意味着您选择的内容太多。

Edit 编辑

I'll clarify a bit. 我会澄清一下。

What you need to do depends on whether you have an of arrays of char 's (which is '\\0' terminated) or an array of pointers to strings. 您需要做什么取决于您是否具有char数组(以'\\ 0'终止)或指向字符串的指针数组。

In the first case, if you want to "remove" a string, you can either change all the character in the array to '\\0', or just the first. 在第一种情况下,如果要“删除”字符串,则可以将数组中的所有字符更改为“ \\ 0”,也可以仅更改第一个。 And use strlen or `s[0] == '\\0' to determine if the string is empty. 并使用strlen或`s [0] =='\\ 0'来确定字符串是否为空。

In the second case, you should free the pointer, and set it to NULL . 在第二种情况下,您应该释放指针,并将其设置为NULL To check if the string is "empty", test for NULL . 要检查字符串是否为“空”,请测试NULL

The difference lies in the relationship between pointers and arrays in C, which is not trivial, see here . 区别在于C中的指针和数组之间的关系不小,请参见此处

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

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