垃圾值与字符串比较

时间:2015-10-22 21:20:43

标签: c

#include<stdio.h>
#include<string.h>

void* lsearch(void* key,void* base,int size,int elemSize){
  int i = 0;
  for(i = 0; i < size; i++){
    void* elemAddr = ((char*)base + (i * elemSize));
    if(memcmp(key,elemAddr,elemSize)==0){
            return elemAddr;
    }
  }
  return NULL;
}

int main(){
  char* a[] = {"Hello","Good","Morning","Ladies"};
  int size = sizeof(a)/sizeof(a[0]);
  char* key = "Good";
  char* search = (char*)lsearch(&key,&a,size,sizeof(char*));
  if(search == NULL){
   printf("\n key value not found!! \n");
   return -1;
  }
  printf("\n search : %s \n",search);
  return 0;
}

输出:

 search : �@ 

我试图对数组中的字符串进行搜索...字符串匹配,但是我打印了一个垃圾值..为什么会这样..

2 个答案:

答案 0 :(得分:3)

修正:

有些事情是错的,这是最值得注意的问题:

  • 算术void*:非法,
  • some_type array[] = {...};的长度为sizeof(array)(无任何花哨的划分),
  • 不恰当的界面选择:当您只是阅读时,请考虑使用const参数。另外,请确保参数&#39;类型与您的参数一致(例如baseconst char* []而不是char*)。最后,要在字符串数组中查找键,您需要一个键,一个数组句柄和数组的长度,这就是全部。

Run It Online

#include<stdio.h>
#include<string.h>

const char* lsearch(const char* key, const char* base[], const size_t size){
  size_t i = 0;
  const size_t max_len = strlen(key);  // strlen(), that's how you compute the length of a string (you might add `+1` to include `\0` if you want)

  for(i = 0; i < size; i++){
    const char* elemAddr = base[i];  // Arithmetic on a void* is illegal in both C and C++: https://stackoverflow.com/a/3524270/865719
    if(memcmp(key, elemAddr, max_len)==0) {  // @TODO use strncmp(), more appropriate, and safer. In particular, if strlen(elemAddr) < strlen(key)
            return elemAddr;
    }
  }
  return NULL;
}

int main() {
  // init
  const char* a[]   = {"Hello","Good","Morning","Ladies"};
  const size_t size = sizeof(a);  // size of the array -- i.e. element count

  // search
  const char* key = "Morning";
  const char* search = lsearch(key, a, size);

  // results
  if(search == NULL) {
   printf("\n key value not found!! \n");
   return -1;
  }

  printf("\n search : %s \n",search);
  return 0;
}

正如Jongware所指出的,更好的方法是使用字符串比较功能。在我看来,最安全的赌注是

int strncmp(const char *s1, const char *s2, size_t n);

你会这样使用它:

// safer. in particular, if (and when) strlen(elemAddr) < strlen(key)
if(strncmp(key, elemAddr, max_len) == 0) {
        return elemAddr;
}

答案 1 :(得分:0)

那会这样做:

  printf("\n search : %s \n",*(char**)search);

您试图从正确的位置读取,但编译器并不知道如何访问它