我正在编写一个函数,根据邮政编码的值对指向结构的指针数组进行排序。我在网上找到了一个排序函数(这是我第一次编写排序函数),我想尝试一下它,看看会发生什么,但我不断收到错误“数组类型‘char[7] 不可分配’”,我不知道为什么。有什么想法吗?
谢谢。
struct personCatalog {
char name[50];
char address[50];
char cityState[50];
char zipCode[7];
} ;
#include <stdio.h>
#include "header.h"
#include <stdlib.h>
#include <string.h>
void bubble_sort(struct personCatalog *arrayOfPointers[]){
int num1 = 0;
while (arrayOfPointers[num1] != NULL) {
atoi(arrayOfPointers[num1++]->zipCode);
}
int progress = 0;
do {
int i;
progress = 0;
for (i = 0; i < num1 - 2; ++i) {
if (arrayOfPointers[i]->zipCode > arrayOfPointers[i + 1]->zipCode) {
struct personCatalog temp = *arrayOfPointers[i];
arrayOfPointers[i] = arrayOfPointers[i + 1];
arrayOfPointers[i + 1] = &temp;
progress = 1;
}
}
} while (progress);
}
最佳答案
C 语言本质上并不知道如何将 7 个字符分配给另外 7 个字符。它一次只允许您将一种基本类型分配给另一种:
zipCode[0] = temp[0]
zipCode[1] = temp[1];
// etc.
要复制 C 中连续的数组,例如 zipCode
,您可以使用 memcpy
:
memcpy(zipCode, temp, 7);
此外,我可能在小屏幕上误读了您的意图,但您也不应该将结构指针分配给 zipCode。
关于c - 编写一个排序函数对指向结构的指针数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13547939/