#define maxRow 5
#define maxStringLength 32
#define NULL ((void *) 0)
// returns 1 based index
// user must decrement the return value before use.
// returns 0 if not found
int srch( char **result, int rows, char *needle) {
for( int i = 0; i < rows; i++ ) {
if( strcmp( result[i], needle ) == 0 ) {
return (i + 1); // increment index by 1, important
}
}
return 0;
}
int main() {
int subTotal[maxRow];
char productName[16];
int resultCnt = 0;
int num;
char s[][16] = { "apple 10",
"apple 15",
"pair 20",
"melon 12",
"pair 100"
};
// ***** prepare char string dynamically *****
char **result = malloc( maxRow * sizeof(char *));
if( result == NULL ) { puts("Memory allocation error"); return 0; }
for( int i = 0; i < maxRow; i++) {
result[i] = malloc( maxStringLength * sizeof(char));
if(result[i] == NULL) { puts("Memory allocation error"); return 0; }
}
// ***** initialize *****
for( int i = 0; i < maxRow; i++ ) {
result[i][0] = 0x00; // initialize to Null string;
subTotal[i] = 0;
}
// #####_$$$$$ read and summary #####_$$$$$
for( int i = 0; i < sizeof( s) / sizeof( s[0]); i++ ) {
sscanf( s[i], "%s %d", productName, &num);
int indx = srch( result, maxRow, productName);
if( !indx ) {// if not found
strcpy( result[resultCnt], productName);
subTotal[ resultCnt ] = num;
resultCnt++;
} else {
subTotal[ --indx ] += num; // decrement index by 1, important
}
}
// ***** print out *****
for( int i = 0; i < resultCnt ; i++ ) {
printf("%s %d\n", result[i], subTotal[i]);
}
// ***** free array *****
for( int i = 0; i < maxRow; i++) {
free( result[i] );
result[i] = NULL;
}
free( result );
result = NULL;
return 0;
}
압축파일을 첨부한다.
'C 언어' 카테고리의 다른 글
| C언어 getString 함수 만들기 (0) | 2022.06.01 |
|---|---|
| strtok 함수 구현 (0) | 2022.03.11 |
| C언어 getline 함수(개행문자 제외) (0) | 2021.12.04 |
| C 언어 substring 함수 구현 방법 (1) | 2021.11.23 |
| C언어 개인 프로젝트 (매크로 함수 이용) (0) | 2021.10.26 |
댓글