繁体   English   中英

如何在C中的数组中查找元素

[英]How to find an element in an array in C

我试图在数组中找到元素的位置。 我试图使用我生成的这段代码

for(i=0;i<10;i++)
    {
    if (strcmp(temp[0],varptr[i])==0) j=i;
    }

varptr是一个指向数组var [11] [10]的指针,根据定义* varptr [11] [10]。 我已将字符串分配给var [i],我想获取我的元素“ THE ADRESS”的“ i”号。

感谢您的任何评论。

EDit:temp也是一个指向我要检查的字符串的指针。 我也使用2D数组来保留变量名及其地址。 所以是的,我想将其保留在2D数组中。 问题是此代码根本不起作用,它没有将i分配给j,所以我想知道这个想法在哪里出问题? 编写“中断”不会改变代码是否起作用,只是稍微优化了代码。

完整代码:

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

double atof(char*);
int main(void)
{
    char in[100], *temp[10],var[11][10],*varptr[11][10];
    int i,j, n = 0,fullval=0;
    double val[11];
    strcpy(var[11], "ans");
    for(i=0;i<11;i++)
    {
        for(j=0;j<10;j++) varptr[i][j]=&var[i][j];
    }
START:
    printf("Enter the expression: ");
    fflush(stdout);
    for(i=0;i<10;i++) temp[i]=NULL;

    if (fgets(in, sizeof in, stdin) != NULL)
    {
        temp[0] = strtok(in, " ");

        if (temp[0] != NULL)
        {
            for (n = 1; n < 10 && (temp[n] = strtok(NULL," ")) != NULL; n++)
                ;
        }
        if (*temp[0]=="quit")
        {
            goto FINISH;}

        if (isdigit(*temp[0]))
        {

            if (*temp[1]=='+') val[0] = atof(temp[0])+atof(temp[2]);
            else if (*temp[1]=='-') val[0] = atof(temp[0])-atof(temp[2]);
            else if (*temp[1]=='*') val[0] = atof(temp[0])*atof(temp[2]);
            else if (*temp[1]=='/') val[0] = atof(temp[0])/atof(temp[2]);
            printf("%s = %f\n",var[11],val[0]);
            goto START;

        }
        else
            if (temp[1]==NULL) //asking the value of a variable
            {
            for(i=0;i<10;i++)
            {
            if (strcmp(temp[0],varptr[i])==0) j=i;
            }
            printf("%s = %d\n",var[j],val[j]);
            goto START;
            }
            if (*temp[1]==61)
            {
            strcpy(var[fullval], temp[0]);
            if ((temp[3])!=NULL)
            {
            }
            val[fullval]=atof(temp[2]);
            printf("%s = %f\n",var[fullval],val[fullval]);
            fullval++;
            goto START;
            }
            if (*temp[1]!=61)
            {


            }

    }
    getch();
FINISH:
    return 0;


}
j=-1;
for(i=0;i<10;i++) 
{ 
  if (strcmp(temp[0],varptr[i])==0) {j=i;break;} 
}//strcmp is not safe, try use strncmp

一条评论:找到字符串即可立即退出循环。

#define NOT_FOUND (-1)

int j = NOT_FOUND;
int i;
for (i = 0 ; i < 11 && j == NOT_FOUND; i++)
{
    if (strncmp(temp,var[i], 10) == 0) // Nick D's comment
    {
        j = i;
    }
}

另一条评论:

我无法理解varptr和var如何相互关联(请显示定义)。 我已经在上面基于定义的假设中使用了var:

char var[11][10];

char temp[10];
int i;
int found = 0;
for (i = 0 ; i < 11 ; i++)
{
    if (strcmp(temp,var[i]) == 0) 
    {
           found = 1; 
           break;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM