简体   繁体   English

如何删除C中的char指针数组

[英]How to delete in char pointer array in C

I want to delete the cell which has "sth" in: 我想删除“sth”中的单元格:

char* a[200];

how should I do it? 我该怎么办? I tried this but it does not work! 我试过这个,但它不起作用!

for(i=0;i<100;ti++)
{

 if(strcmp(a[i],"sth")!=0)
    temp[i]=a[i];
}
a=temp  //not sure here

You cannot delete a cell from an array like this. 您不能从这样的数组中删除单元格。 You can set it instead to something arbitrary, like an empty string. 您可以将其设置为任意值,例如空字符串。

The harder way is: 更难的方法是:

  • count the items you want to delete 计算要删除的项目
  • create a new smaller array 创建一个新的较小的数组
  • copy the items you need from the old array to the new one 将您需要的项目从旧阵列复制到新阵列
  • delete the old one. 删除旧的。

You may wonder why is a simple thing like this is so complicated. 你可能想知道为什么像这样的简单事情是如此复杂。 The reason is that the array is a sequence of data in the memory. 原因是数组是存储器中的数据序列。 It works something like a bureau with a lot of drawers. 它的工作方式就像一个有很多抽屉的局。 You can tell the program what to put in the drawers, but you can't really get rid only a part of it without destroying the whole bureau. 你可以告诉程序什么放在抽屉里,但你不能真正摆脱它的一部分而不破坏整个局。 So you have to make a new one. 所以你必须做一个新的。

something like 就像是

j=0;
for(i=0;i<100;i++)
{
    a[j]=a[i];
    if(strcmp(a[i],"sth")) {
     j++;
    }else{
     a[j]=0;
    }
}

i didnt free the memory here, since i dont know where the strings came from. 我没有释放内存,因为我不知道字符串来自哪里。 If the strings were allocated with malloc they should be freed (if not used elsewhere) 如果字符串是用malloc分配的,那么它们应该被释放(如果没有在其他地方使用)

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

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