读书人

一个数组赋值时不能赋相同的值怎么

发布时间: 2012-05-09 12:13:59 作者: rapoo

一个数组,赋值时不能赋相同的值,如何限定……
就是在赋值的时候加上限定,不能和先前的数相同,如何实现

[解决办法]
如果是C的话,不能用类的
可用
void *lsearch(const void *key, void *base, size_t *num, size_t width, int (_USERENTRY *fcmp)(const void *, const void *));
一个字符数组的例子:

C/C++ code
#include <stdlib.h>#include <stdio.h>#include <string.h>     /* for strcmp declaration *//* initialize number of colors */char *colors[10] = { "Red", "Blue", "Green" };int ncolors = 3;int colorscmp(char **arg1, char **arg2){   return(strcmp(*arg1, *arg2));}int addelem(char **key){   int oldn = ncolors;   lsearch(key, colors, (size_t *)&ncolors, sizeof(char *),     (int(*)(const void *,const void *))colorscmp);   return(ncolors == oldn);}int main(void){   int i;   char *key = "Purple";   if (addelem(&key))      printf("%s already in colors table\n", key);   else   {      printf("%s added to colors table\n", key);   }   printf("The colors:\n");   for (i = 0; i < ncolors; i++)      printf("%s\n", colors[i]);   return 0;} 

读书人网 >C语言

热点推荐