이것은 K &5 섹션 5.11에서 찾을 수있는 정렬 프로그램입니다.K & R 섹션의 프로그램 정렬 5.11
alloc.c
:
#include <stdio.h>
#define BUFSIZE 10000
static char allocbuf[BUFSIZE];
static char *allocp = allocbuf;
char *alloc(int n) {
if(allocbuf + BUFSIZE - allocp >= n) {
allocp += n;
return allocp - n;
}
else {
return NULL;
}
}
io.c
:
#include <stdio.h>
#include <string.h>
#define MAXLEN 1000
char *alloc(int);
int getLine(char *s, int maxline) {
int i;
int c;
c = getchar();
maxline--;
for(i = 0; c != EOF && c != '\n' && maxline > 0; i++, c = getchar(), maxline--) {
s[i] = c;
}
if(c == '\n') {
s[i] = c;
i++;
}
s[i] = '\0';
return i;
}
int readlines(char *lineptr[], int maxlines) {
int len, nlines;
char *p, line[MAXLEN];
nlines = 0;
while((len = getLine(line, MAXLEN)) > 0) {
if(nlines >= maxlines || (p = alloc(len)) == NULL)
return -1;
else {
line[len - 1] = '\0';
strcpy(p, line);
lineptr[nlines++] = p;
}
}
return nlines;
}
void writelines(char *lineptr[], int nlines) {
int i;
for(i = 0; i < nlines; i++)
printf("%s\n", lineptr[i]);
}
main.c
:
#include <stdio.h>
#include <string.h>
#define MAXLINES 5000
char *lineptr[MAXLINES];
int readlines(char *lineptr[], int nlines);
void writelines(char *lineptr[], int nlines);
void qqsort(void *lineptr[], int left, int right, int(*comp)(void *, void *));
int numcmp(char *, char *);
int main(int argc, char *argv[]) {
int nlines;
int numeric = 0;
if(argc > 1 && strcmp(argv[1], "-n") == 0) {
numeric = 1;
}
if((nlines = readlines(lineptr, MAXLINES)) >= 0) {
qqsort((void **)lineptr, 0, nlines - 1, (int (*)(void *, void *)) (numeric ? numcmp : strcmp));
writelines(lineptr, nlines);
return 0;
}
else {
printf("input too big to sort\n");
return 1;
}
}
readlines.c
:
#include <stdlib.h>
void swap(void *v[], int i, int j) {
void * tmp;
tmp = v[i];
v[i] = v[j];
v[i] = tmp;
}
int numcmp(char *s1, char *s2) {
double v1, v2;
v1 = atof(s1);
v2 = atof(s2);
if(v1 < v2) {
return -1;
}
else if(v1 > v2) {
return 1;
}
else {
return 0;
}
}
void qqsort(void *v[], int left, int right, int(*comp)(void *, void *)) {
int i, last;
if(left >= right) {
return;
}
swap(v, left, (left + right)/2);
last = left;
for(i = left + 1; i <= right; i++) {
if((*comp)(v[i], v[left]) < 0) {
swap(v, ++last, i);
}
}
swap(v, left, last);
qqsort(v, left, last - 1, comp);
qqsort(v, last + 1, right, comp);
}
문제는이 프로그램이 무엇을하는지 실제로 이해하지 못한다는 것입니다. 그것은 입력에서 몇 줄을 읽어야하며 정렬 된 순서로 인쇄해야합니다. 그러나 나는 그것의 입력에 비해 프로그램의 출력에 변화가 없음을 안다. 예를 들어
:
INTPUT은 :
test1
asdasdasdas
test2
fobafoobarfoobar
barfoobarfoobarfooofoobar
출력은 :
기호 인수"-n"
가 주어
test1
asdasdasdas
test2
fobafoobarfoobar
barfoobarfoobarfooofoobar
출력은 여전히 동일하다. 예를 들어 : 입력 :
1234234432
2333
2222222
23423
1
출력 :
1234234432
2333
2222222
23423
1
내가 잘이 프로그램의 목적을 이해하지 못하는 것 같아요. 소스 코드와 관련된 문서를 읽고 무엇을해야하는지 알아낼 수 있습니다. 프로그램이 예상대로 작동하지 않습니다.
1
2333
23423
2222222
1234234432
누군가가 내가 잘못 뭐하는 거지 설명해 수 : 두 번째 예에서 I 출력이 같이 기대? , BTW이 프로그램은 swap()
잘못 (133)
'C = getchar가;
그래서 하나를 시도 maxline--; 당신은'getchar()'를 두 번 호출하고있다. (getch()는 두 번 호출한다. 'getline (...)'이 필요합니까? – dud3