0
#include<stdio.h>
int main()
{
 unsigned char a[3];
 unsigned char b[3];
 int *l[3]=NULL;
 int i = 0;

 a[0]=0;
 a[1]=1;
 a[2]=2;
 b[0]=3;
 b[1]=4;
 b[2]=5;

 l[0]=&a;
 l[1]=&b;
 if(strcmp(l[0],l[1])==0) {
   printf("Compared not same");
 }
 return 0;
}

我想将数组存储在数组“l”中。并对存储在索引 0 和索引 1 处的数组进行比较。我遇到了错误。请帮忙。

4

4 回答 4

1
#include<stdio.h>
int main()
{
  unsigned char a[3];
  unsigned char b[3];
  unsigned char *l[2];

  a[0] = '3'; a[1] = '4'; a[2] = '\0';
  b[0] = '3'; b[1] = '4'; b[2] = '\0';

  l[0] = a; l[1] = b;
  if(strcmp(l[0], l[1]) != 0) {
    printf("Compared not same");
  } else {
    printf("Compared same");
  }
  return 0;
}
于 2012-07-20T08:28:46.087 回答
1
#include<stdio.h>
int main()
{
 unsigned char a[3];
 unsigned char b[3];
 unsigned char *l[2];

 a[0] = 0; a[1] = 1; a[2] = 2;
 b[0] = 3; b[1] = 4; b[2] = 5;

 l[0] = a; l[1] = b;
 if(strncmp(l[0], l[1], 3) != 0) {
   printf("Compared not same");
 }
 return 0;
}
于 2012-07-20T08:06:28.217 回答
0

不确定是否将数组存储在数组中,但您应该使用memcmp而不是strcmp比较数组(因为strcmp比较字符串,而您的数组不是字符串)。

 unsigned char a[3];
 unsigned char b[3];
 unsigned char *l[2]; // note: corrected a few errors in this line
 int i = 0;

 a[0]=0;
 a[1]=1;
 a[2]=2;
 b[0]=3;
 b[1]=4;
 b[2]=5;

 l[0]=a;
 l[1]=b;
 if(memcmp(l[0],l[1], sizeof(a))==0) { // note: have to specify the length
   printf("Compared same"); // note: reveresed the logic
 }
于 2012-07-20T10:35:38.890 回答
0
int main()
{
    char a[3] = {1, 1, 2};
    char b[3] = {1, 4, 5};
    char *l[2]= {a, b};

    printf( (strncmp(l[0], l[1], 3)==0) ? "Compared are equal" : "Compared are not equal");

 return 0;
}

请注意,0 是行尾,因此字符数组 [0, 1, 2] 和 [0, 5, 5] 相等。此外,如果您在此类数组中没有 0,则可能会导致错误,因为它将是无穷无尽的数组,并且会尝试从内存中获取不适合该数组的值。你真的应该从任何关于语言基础的优秀 c/c++ 书籍开始。

于 2012-07-20T08:26:07.737 回答