c - 如何处理和优化 C 代码

标签 c function optimization

我是 C 新手,非常有兴趣了解如何解决具有超过 3 或 4 个函数的任何问题,我总是查看所需的输出并操作我的代码,在其他函数中调用函数并获取所需的输出。 以下是我首先通过 ID 然后通过用户名查找学生记录的逻辑。 根据我的教授的说法,这段代码逻辑过多,并且在很多方面都缺乏,如果有人可以帮助我如何解决 C 或任何其他语言中的任何问题,这对我作为初学者来说会有很大的帮助,是的,我先写伪代码。

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

typedef struct{

int id;                                  //Assuming student id to be unique
int age;
char *userName;                         //Assuming student userName to be unique
char *dept;

}student;                               // Alias "student" created for struct

student* createstruct();                // All function prototype declared
student* createArray();
void addstruct(student* s2);
void searchChar(student* s2,int num);
void searchInt(student* s2,int num);

student* createstruct()                          // function createStruct() to malloc data of struct student.
{
    student *s;
    s = (student*)malloc(sizeof(student));
    s->userName = (char*)malloc(sizeof(char)*32);
    s->dept = (char*)malloc(sizeof(char)*32);
    printf("please enter id ");
    scanf("%d",&s->id);
    printf("please enter age ");
    scanf("%d",&s->age);
    printf("please enter userName ");
    scanf("%31s",s->userName);
    printf("please enter department ");
    scanf("%31s",s->dept);
    printf("\n");

    return s;
}

student* createArray()
{
    student *arr;                                    //declaration of arr poiter, type struct student
    arr = (student*)malloc(sizeof(student)*10);     // memory allocated for a size of 10
    return arr;
}

void addstruct(student *s2)                       // function for adding data to the structures in array
{
    int i,num;
    student* s1;
    printf("please enter the number of records to add:");
    scanf("%d",&num);
    printf("\n");

    if(num>0 && num<11)
    {
      for(i=0;i<num;i++)                    // if user want to enter 5 records loop will only run 5 times
       {
         s1 = createstruct();
         s2[i].id = s1->id;                 // traversing each element of array and filling in struct data
         s2[i].age = s1->age;
         s2[i].userName = s1->userName;
         s2[i].dept= s1->dept;
       }
    }
    else if(num>10)                         // if user enters more than 10
    {
      for(i=0;i<10;i++)                     // loop will still run only 10 times
        {
         s1 = createstruct();
         s2[i].id = s1->id;
         s2[i].age = s1->age;
         s2[i].userName = s1->userName;
         s2[i].dept = s1->dept;
        }

       printf("Array is full");            // Array is full after taking 10 records
       printf("\n");
    }

searchInt(s2,num);                        // Calling searchInt() function to search for an integer in records
searchChar(s2,num);                       // Calling searchChar() function to search for a string in records
free(s1);
free(s2);
}

void searchChar(student* s2,int num)           // function for searching a string in records of structure
{
    char *c;
    int i;
    c = (char*)malloc(sizeof(char)*32);
    printf("please enter userName to search ");
    scanf("%31s",c);
    printf("\n");

  for (i=0;i<num;i++)                             //num is the number of struct records entered by user
    {
      if ((strcmp(s2[i].userName,c)==0))          //using strcmp for comparing strings
      {
       printf("struct variables are %d, %d, %s, %s\n", s2[i].id,s2[i].age,s2[i].userName,s2[i].dept);
       break;
      }
      else if(i == num-1)
      {
          printf("nothing in userName matches: <%s>\n",c);
          break;
      }
    }
}

void searchInt(student* s2,int num)                 //searchs for an integer and prints the entire structure
{
    int i,z;
    printf("please enter id to search ");
    scanf("%d",&z);
    printf("\n");

  for (i=0;i<num;i++)
    {
      if (s2[i].id == z)
      {
          printf("struct variables are %d, %d, %s, %s\n\n", s2[i].id,s2[i].age,s2[i].userName,s2[i].dept);
          break;
      }
      else if(i == num-1)
      {
          printf("nothing in id matches: <%d>\n\n",z);
          break;
      }
    }
}

int main(void)
{
    student *s2;
    s2 = createArray();
    addstruct(s2);
    return 0;
}

最佳答案

我不打算进行优化,因为如果你想要更好的理论性能,你可能会使用不同的数据结构,例如有序数组/列表、树、哈希表或某种索引......没有一个这在本例中是相关的,因为您有一个处理少量数据的简单程序。

但我要以你的 searchInt 函数为例,告诉你你的教授提到的“过度逻辑”:

for (i=0;i<num;i++)
{
  if (s2[i].id == z)
  {
      printf("struct variables are %d, %d, %s, %s\n\n", s2[i].id,s2[i].age,s2[i].userName,s2[i].dept);
      break;
  }
  else if(i == num-1)
  {
      printf("nothing in id matches: <%d>\n\n",z);
      break;
  }
}

这里的问题是,每次循环时,您都会测试是否位于循环中的最后一个元素。但循环已经做到了这一点。所以你要做两次,更糟糕的是,你要做一个减法(这可能会也可能不会被编译器优化到寄存器中)。

你通常会做这样的事情:

int i;
student *s = NULL;

for( i = 0; i < num; i++ )
{
    if( s2[i].id == z ) {
        s = &s2[i];
        break;
    }
}

if( s != NULL ) {
    printf( "struct variables are %d, %d, %s, %s\n\n",
            s->id, s->age, s->userName, s->dept );
} else {
    printf("nothing in id matches: <%d>\n\n",z);
}

请注意,您只需要通过某种方式知道循环发现了某些内容。在测试循环是否发现某些内容之前,您需要等待循环完成。

在本例中,我使用指针来指示成功,因为我可以使用指针来访问相关记录,而不必重新索引到数组中并使代码变得困惑。您不会总是使用指针。

有时你设置一个标志,有时你存储数组索引,有时你只是从函数返回(如果循环失败,你知道它没有找到任何东西)。

编程就是为要解决的问题做出明智的选择。仅在需要时进行优化,不要使问题过于复杂,并始终尝试编写易于阅读/理解的代码。

关于c - 如何处理和优化 C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13060989/

相关文章:

python - 尝试从文件制作 python 字典,但我不断收到类似 'too many values to unpack' 的错误

mysql - 在MySQL中计算上午6点之前和晚上10点之后的时间差

algorithm - 帮助我优化 VBA Excel 代码,用于将工作表上每一行的某些列复制到另一张

c - 为什么 int 存在于 C 中,为什么不只是 short 和 long

C 跳过函数的一个命令?

c - 为性能设计服务器的最佳方法是什么?

check_order 的 C 程序无法正常工作

php - php : error: Cannot redeclare 中的函数内部函数

java - 如何修复我的音频? (优先)

MySQL 3个链接表的查询优化