e, "No match Name", iMaxNameLen); return pRetName; } int main(int argc, char *argv[]) { int iId = 2; char *pName = GetStaffNameById(iId); printf("Staff Name is : %s(id = %d)\n", pName, iId); free(pName); pName = NULL; system("PAUSE"); return 0; } #include #include
typedef struct _STSTAFFINFO { char *pName; /* */ int iId; /*ID*/ }stStaffInfo;
/* ù ID */ char* GetStaffNameById(int iId) { int i; int iMaxNameLen = 20; stStaffInfo stTmpInfo[] = { {"Socrates", 1}, {"dyx1024", 2}, {"Kevin", 3}, {"Jim", 4} };
char *pRetName = (char *)malloc(iMaxNameLen); if (NULL == pRetName) { exit(1); } for (i = 0; i < sizeof(stTmpInfo) / sizeof(stTmpInfo[0]); i++) { if (stTmpInfo[i].iId == iId) { strncpy(pRetName, stTmpInfo[i].pName, iMaxNameLen); return pRetName; } } strncpy(pRetName, "No match Name", iMaxNameLen); return pRetName; }
int main(int argc, char *argv[]) { int iId = 2; char *pName = GetStaffNameById(iId); printf("Staff Name is : %s(id = %d)\n", pName, iId); free(pName); pName = NULL; system("PAUSE"); return 0; }
摘自 Socrates的专栏
|