C中结构数组的搜索
如何搜索在结构数组中随机生成的字符。 如果找到char,函数必须在struct数组中返回C中结构数组的搜索,c,struct,char,C,Struct,Char,如何搜索在结构数组中随机生成的字符。 如果找到char,函数必须在struct数组中返回info[i].num,其中info是结构数组(请参见下面的代码) 我在gcc warning: comparison between pointer and integer if(info[j].name == s ); 如何使用正确的比较 #include <stdio.h> #include <stdlib.h> #include<string.h> #defi
info[i].num
,其中info是结构数组(请参见下面的代码)
我在gcc
warning: comparison between pointer and integer
if(info[j].name == s );
如何使用正确的比较
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#define InfoSize 3
int main(int argc, char *argv[])
{
char arr[20];
struct st
{
char name[20];
int num[5];
};
struct st info[InfoSize] = {{ "some10",6 },{"some50",8},{"some5",4}};
int r = rand() % (50 + 1 - 10) + 10 ;
char s = sprintf( arr, "some%d", r );
for(int j=0;j<3;j++){
if(info[j].name == s )
printf("found %s and it's num =%d",info[j].name,info[j].num);
}
#包括
#包括
#包括
#定义InfoSize 3
int main(int argc,char*argv[])
{
char-arr[20];
结构街
{
字符名[20];
int-num[5];
};
struct st info[InfoSize]={{“some10”,6},{“some50”,8},{“some5”,4};
int r=rand()%(50+1-10)+10;
char s=sprintf(arr,“某些%d”,r);
对于(int j=0;j,您的程序缺少很多东西。
首先,您需要为rand函数设置种子,以便获得伪随机数
您得到的警告(至少在我的编译器上不是错误)告诉您正在将指针与整数进行比较,因为c中的数组实际上是普通的旧指针
char s = sprintf( arr, "some%d", r );
据
sprintf将输出发送到您的arr变量,并根据操作的成功情况重新运行一个值,因此以下代码:
if(info[j].name == s )
应写为
if(strcmp(info[j].name,arr)==0)
我建议您尝试掌握C的核心概念,因为即使您不再使用C,它对您未来的编程生活也会有很大帮助。以下建议代码:
干净地编译
纳入了对该问题的大多数评论
执行所需的功能
记录包含每个头文件的原因
代码可能无法在支柱数组中找到匹配的条目,因为arr[]
内容的生成可能是10到50之间的任何值,因此不会在字符串中追加5:some
。并且不太可能追加10或50
现在是拟议的守则
#include <stdio.h> // printf(), sprintf()
#include <stdlib.h> // rand(), srand()
#include <string.h> // strcmp()
#include <time.h> // time()
#define INFO_SIZE 3
#define MAX_ARR_LEN 20
int main( void )
{
char arr[ MAX_ARR_LEN +1 ];
struct st
{
char name[20+1]; // +1 to allow for trailing NUL byte
int num;
};
struct st info[ INFO_SIZE ] =
{
{ "some10",6 },
{ "some50",8 },
{ "some5",4 }
};
srand( (unsigned int)time( NULL ) );
int r = (rand() % 41) + 10 ;
sprintf( arr, "some%d", r );
for(int j=0; j<INFO_SIZE; j++ )
{
if( strcmp( info[j].name, arr ) == 0 )
{
printf("found %s and it's num =%d",info[j].name,info[j].num);
}
}
}
#包括//printf(),sprintf()
#包括//rand()、srand()
#包括//strcmp()
#包括//时间()
#定义信息大小3
#定义最大排列长度20
内部主(空)
{
字符阵列[最大阵列长度+1];
结构街
{
字符名[20+1];//+1以允许尾随NUL字节
int-num;
};
结构st信息[信息大小]=
{
{“some10”,6},
{“大约50”,8},
{“some5”,4}
};
srand((无符号整数)时间(NULL));
int r=(rand()%41)+10;
sprintf(arr,“一些%d”,r);
对于(int j=0;j