簡體   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