Skip to content

Instantly share code, notes, and snippets.

@caoxudong
Created November 5, 2012 10:36
Show Gist options
  • Save caoxudong/4016551 to your computer and use it in GitHub Desktop.
Save caoxudong/4016551 to your computer and use it in GitHub Desktop.
给一个数组和一个值,从数组中删除这个指定的值的所有出现,并且返回新的数组的长度。
/**
* 给一个数组和一个值,从数组中删除这个指定的值的所有出现,并且返回新的数组的长度。
* size_t remove_elem(T* array, size_t len, T elem) {}。
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]){
int array[] = {1,2,3,4,5,6,4,7,3,7,89,3};
int result = remove_elem(array, 12, 4);
printf("%d\n", result);
}
int remove_elem(int* array, int len, int elem) {
int* newArray = (int*)malloc(sizeof(int) * len);
int newArrayLength = 0;
int i=0;
for(i=0;i<len;i++){
if(array[i] != elem) {
newArray[newArrayLength] = array[i];
newArrayLength++;
}
}
for(i=0;i<newArrayLength;i++) {
array[i] = newArray[i];
}
free(newArray);
return newArrayLength;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment