포인터를 이용하여 배열안의 원소들의 주소 바꾸기
조회수 1731회
#include <stdio.h>
#include <string.h>
# define MAX 50
typedef struct contact_st
{
char Name[10];
char PhoneNumber[13];
} Contact;
Contact PhoneBook[MAX];
int contactSwap(void* arr, int i, int j)
{
int temp;
temp = ((int*)arr + i);
*((int*)arr + i) = ((int*)arr + j);
*((int*)arr + j) = temp;
// Goal: arr[i] <- arr[j], arr[j] <- arr[i]
// calculate address for arr[i]: ((int*)arr+i)
// derefernce int: *((int*)arr+i))
}
int main() {
Contact A[5] = { { "Roki", "12345678" }, { "Thor", "33333333" }, { "IronMan","3765898" }, { "Hulk", "74561253" }, { "Groot", "99999999" } };
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4 - i; j++)
{
if (*((Contact*)A + i)->PhoneNumber, *((Contact*)A + j)->PhoneNumber){
contactSwap(A, i, j);
}
}
}
void *vp;
vp = A;
for (int i = 0; i < 5; i++)
{
// Calculate address for arr[i]: ((Contact*)arr+i)
// derefernce structure Contact: *((Contact*)arr+i)).Name
// for stucture we use ->: ((Contact*)vp+i)->Name
printf("Addr vp:%p\t", (Contact*)vp + i);
printf("name:%s\t phone:%s\n", ((Contact*)vp + i)->Name, ((Contact*)vp + i)->PhoneNumber);
}
printf("\n");
}
컴파일은 잘 됩니다만 논리적인것에서 틀린건지... 이름의 순서대로 내림차순해주고 싶은데, 순서는 안 바뀌고 제일 처음의 값만 이상해지네요. 어떻게 해야 할까요? 제발 부탁드립니다.ㅠㅠ 함수를 잘 못 만든걸까요? C 로 작성하였습니다.
댓글 입력