gpt4 book ai didi

c - 将 strcmp 与数组一起使用

转载 作者:行者123 更新时间:2023-11-30 18:42:35 25 4
gpt4 key购买 nike

这是完整的代码。现在一直结冰

 typedef struct {
char *name;
} NAME;

将数组设置为空,然后根据需要添加的条目数对其进行扩展。

NAME    *array = NULL;
int itemCount = 0; // items inserted
int arraySize = 0; // size of array
int arrayCount; //gets size of file.
int found = 0;

int Add(NAME item)
{
if(itemCount == arraySize) {

if (arraySize == 0)
arraySize = 3;
else
arraySize *= 2; // double size of array

//relocate memory
void *tempMemory = realloc(array, (arraySize * sizeof(NAME)));

//error relocating memory
if (!tempMemory)
{
printf("Couldn't relocate the memory \n");
return(-1);
}

array = (NAME*)tempMemory;
}

array[itemCount] = item;
itemCount++;

return itemCount;
}
void printStruct()
{
int i;
for(i = 0; i < arrayCount; i++)
{
printf("%s \n", array[i].name);
}
}

int readFromFile()
{
int checkResult(char[]);
FILE *fp;
fp = fopen("names.txt", "r");

char names[arrayCount];

if (fp == NULL)
{
printf("Cannot access file \n");
}else{
while(!feof(fp))
{
fscanf(fp, "%s", names);
arrayCount++;
checkResult(names);
}
}

fclose(fp);

return 1;
}


int checkResult(char names[]){
NAME tempStruct;

int i;
if(array == NULL)
{
tempStruct.name = malloc((strlen(names) + 1) * sizeof(char));
strcpy(tempStruct.name, names);
tempStruct.count = 1;
}
else
{
for(i = 0; i < arrayCount; i++)
{
if(strncmp(array[i].name, names, arrayCount)==0)
{
printf("MATCH %s", names);
break;
}
}

if(i == arrayCount)
{
tempStruct.name = malloc((strlen(names) + 1) * sizeof(char));
strcpy(tempStruct.name, names);
}


if (Add(tempStruct) == -1)
{
return 1;
}
}
}

主要是释放内存并调用其他函数

int main(){
void printStruct();
int readFromFile();
readFromFile();

printStruct();

int i;
for (i = 0; i < arrayCount; i++)
{
free(array[i].name);
}

free(array);

return 0;
}

最佳答案

我们在这里所做的是循环查找第一个匹配项,并在找到它时中断循环。如果我们在数组中的任何位置都没有找到它,然后我们将其添加...

NAME** array = calloc( MAX_NAMES, sizeof( NAME* ) );
int count = 0;

int checkName(char names[])
{
if(!count)
{
array[0] = calloc( 1, sizeof( NAME ) );
array[0]->name = malloc((strlen(names) + 1) * sizeof(char));
strcpy(array[0]->name, names);
count = 1;
}
else
{
int i;

for(i = 0; i < count; i++)
{
if(strcmp(array[i]->name, names)==0)
{
printf("MATCH %s", names);
break;
}
}

if( i == count && count < MAX_NAMES )
{
array[count] = calloc( 1, sizeof( NAME ) );
array[count]->name = malloc((strlen(names) + 1) * sizeof(char));
strcpy(array[count]->name, names);
count++;
}
}
}

上面的代码首先测试数组是否为空...如果是,则为数组创建第一个元素并分配名称。

否则,它会解析数组以查看数组中是否有任何条目已与名称匹配...如果匹配,它将中断循环并且 i == count 测试将失败,所以没有添加名称。

如果循环结束时未匹配名称,则 i == count 测试将返回 true,并且如果数组中有空间,我们会将新名称添加到数组末尾。

关于c - 将 strcmp 与数组一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15932508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com