
이 링크에서 내가 원하는 작업에 매우 유용한 C 코드 조각을 찾았습니다.문자와 숫자의 가능한 모든 조합
#include <stdio.h>
//global variables and magic numbers are the basis of good programming
const char* charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
char buffer[50];
void permute(int level) {
const char* charset_ptr = charset;
if(level == -1){
puts(buffer);
}else {
while(buffer[level]=*charset_ptr++) {
permute(level - 1);
}
}
}
int main(int argc, char **argv)
{
int length;
sscanf(argv[1], "%d", &length);
//Must provide length (integer < sizeof(buffer)==50) as first arg;
//It will crash and burn otherwise
buffer[length]='\0';
permute(length - 1);
return 0;
}
그러나 제안된 대로 컴파일하려고 하면 다음과 같은 오류가 발생합니다. 누구든지 내가 문제를 해결하도록 도와줄 수 있나요?
$ make CFLAGS=-O3 permute && time ./permute 5 >/dev/null
make: Nothing to be done for 'permute'.
./permute: line 3: //global: No such file or directory
./permute: line 4: const: command not found
./permute: line 5: char: command not found
./permute: line 7: syntax error near unexpected token `('
./permute: line 7: `void permute(int level) {'
또한 gcc를 사용하려고 하면 Segmentation error 오류가 발생합니다.
$ mv permute permute.c
$ gcc permute.c -o permute.bin
$ chmod 755 permute.bin
$ ./permute.bin
Segmentation fault (core dumped)
답변1
처음에 C 파일 이름을 permute
; 실패했을 때 make
쉘에서 실행을 시도했는데 이로 인해 모든 구문 오류가 발생했습니다(쉘은 C 코드 실행 방법을 모르기 때문입니다).
두 번째 경우에는 댓글을 쳤습니다.
//첫 번째 인수로 길이(정수 < sizeof(buffer)==50)를 제공해야 합니다.
//그렇지 않으면 충돌이 발생하고 타버릴 것입니다.
프로그램에 첫 번째(또는 어떤) 인수도 제공하지 않았기 때문입니다. 노력하다 ./permute.bin 10
.
답변2
permute
첫 번째 경우에는 C 코드를 로 저장 한 후 실행해 본 것 같습니다.
make CFLAGS=-O3 permute && time ./permute 5 >/dev/null
Makefile
에 대한 대상이 없으므로 make
안내 메시지를 인쇄하는 동안 오류 없이 종료되었으며,
'순열'을 위해 할 수 있는 일은 없습니다.
make
오류 코드가 반환되지 않아 해당 명령의 두 번째 부분( ) time ./permute 5 >/dev/null
이 실행되었습니다. 소스 코드이고 실행 가능한 바이너리가 아니기 때문에 permute
쉘 스크립트로 해석되어 다음과 같은 결과가 출력됩니다.
./permute: line 3: //global: No such file or directory
./permute: line 4: const: command not found
./permute: line 5: char: command not found
./permute: line 7: syntax error near unexpected token `('
./permute: line 7: `void permute(int level) {'
더 나은 지침은 C 소스 코드를 저장 permute.c
한 후 다음 명령을 실행하여 컴파일하고 필수 라이브러리 파일에 연결하는 것입니다.
gcc -O3 -o permute permute.c
이는 permute
실행될 수 있는 실행 가능한 바이너리로 생성됩니다. 예:
./permute 2