2014-04-10 2 views
0

나는 문제가 내 코드는 아래와 같습니다 C.에서 문자 포인터의 배열로 문자 배열의 내용을 복사하려고 데 : 내가 보는 것과복사 char 배열

# include<stdio.h> 
# include<stdlib.h> 
# include<string.h> 

# define RECORD_SIZE 300 
# define BUFFER_SIZE 3 

/* Structure for representing a single 
* password entry */ 
typedef struct Record { 
    char * sitename; 
    char * username; 
    char * password; 
    struct Record * next; 
} Record; 

/* Declare function prototypes */ 
int isCorrectKey(char *,char *); 
int isValidOperation(char); 
int isValidSyntax(char *); 
void getFields(char *,char * []); 
void listEntries(); 
int updateEntries(char *); 
int deleteEntries(char *); 
int entryExists(char *); 
void init(char *,char *,char *); 
void readDB(); 
void writeToDB(char *); 
void encrypt(char *,char * [],char *); 
void decrypt(char *,char * [],char *); 

/* Declare global variables */ 
char * database; 
Record * records; 

// Pre-condition: A character pointer to plaintext 
// A character pointer to an empty buffer, 
// A character pointer to the user input key 
// Post-condition: The plaintext is encrypted and 
// inserted into the buffer 
void encrypt(char * text,char * buffer[BUFFER_SIZE],char * key) { 
    int i = 0; 

    for(;i < strlen(text);i++) { 
     buffer[i] = ((char *) (text[i]+3)); 
    } 
    buffer[i] = 0; 
} 

// Pre-condition: A character pointer to ciphertext 
// A character pointer to an empty buffer 
// A character pointer tothe user input key 
// Post-condition: The ciphertext is decrypted and 
// inserted into the buffer 
void decrypt(char * text,char * buffer[BUFFER_SIZE],char * key) { 
    int i = 0; 

    for(;i < strlen(text);i++) { 
     buffer[i] = ((char *) (text[i]-3)); 
    } 
    buffer[i] = 0; 
} 

// Pre-condition: The database variable must be set 
// The records variable must exist 
// Post-condition: The value in database variable is 
// used as filename to read the data. The data that 
// is read and used to initialize the records variable 
void readDB() { 
    // Open the file in read-only mode 
    FILE * f = fopen(database,"r"); 
    char buffer[BUFFER_SIZE]; 
    int index = 0; 

    if(f == NULL) { 
     // Print error if file is invalid 
     printf("Sorry. Unable to find password database."); 
    } else { 
     char c = 0; 
     // Read the file 
     while((c = fgetc(f)) != EOF) { 
      if(c != '\n') { 
       buffer[index++] = c; 
      } else { 
       buffer[index] = 0; // terminate each entry with null 
       index = 0; 
      } 
     } 
     fclose(f); // Close the file handle 
    } 
} 

// Pre-condition: The database variable must be set 
// A character pointer to some text must be provided 
// as input 
// Post-condition: The value in database variable is 
// used as filename to write the data. 
void writeToDB(char * text) { 
    // Open the file in append mode 
    FILE * f = fopen(database,"a"); 
    int index = 0; 

    if(f == NULL) { 
     // Print error if file is invalid 
     printf("Sorry. Unable to find password database."); 
    } else { 
     fputs(text,f); // Write to the file 
     fclose(f); // Close the file handle 
    } 
} 

// Pre-condition: A character pointer to the user input key 
// A character pointer to the actual key 
// The records variable must be set 
// Post-condition: Returns 1 if the key value in the records variable 
// has been properly decrypted. 
// Returns 0 otherwise. 
int isCorrectKey(char * uKey,char * mkey) { 
    return strcmp("ThisIsTheSecretKey",records->password); 
} 

// Pre-condition: A character indicating an operation value 
// Post-condition: Returns 1 if the operation value is supported 
// Returns 0 otherwise. 
int isValidOperation(char operation) { 
    return operation == 'L' || operation == 'U' || operation == 'D'; 
} 

// Pre-condition: A character pointer to a user input command string 
// Post-condition: Returns 1 if the syntax of the command is correct 
int isValidSyntax(char * command) { 
    return 0; 
} 

// Pre-condition: A character pointer to a comma delimited string 
// Post-condition: The string is split into segments and stored into the buffer 
void getFields(char * record,char * buffer[BUFFER_SIZE]) { 
    int i = 0; 
    int buffer_i = 0; 
    int record_len = strlen(record); 
    char tmp_buffer[RECORD_SIZE+1]; 
    int tmp_i = 0; 

    for(;i < record_len;i++) { 
     if(record[i] != ',') { 
      tmp_buffer[tmp_i++] = record[i]; 
     } else { 
      tmp_buffer[tmp_i] = 0; 
      strcpy(buffer[buffer_i++],tmp_buffer); 
      tmp_i = 0; 
     } 
    } 
} 

int main(int argc,char * argv[]) { 
    //database = "test.txt"; 
    //readDB(); 
    char * buffer[BUFFER_SIZE]; 
    getFields("google,geek,pass123",buffer); 

    int i = 0; 

    for(;i<BUFFER_SIZE;i++) { 
     printf(buffer[i]); 
     printf("\n"); 
    } 

    return 0; 
} 

, 문제가되는 줄은 getFields() 함수에 : 나는 버퍼의 인덱스에 tmp_buffer의 내용을 복사하려고

strcpy(buffer[buffer_i++],tmp_buffer); 

. 내 프로그램이 계속 충돌합니다. 나는 이유를 모른다. 누군가 나를 도울 수 있을까요? 감사.

+0

'buffer [buffer_i ++]','char' 또는'char *'의 타입은 무엇입니까? strcpy에는 포인터가 필요합니다. – brokenfoot

+0

나는 그것을 알고있다. buffer [buffer_i ++]는 char * – LanceHAOH

+3

'char *'가 가리키는 메모리를 할당하는 것을 보지 못합니다. – Deduplicator

답변

1

버퍼에 세 항목 각각에 대한 메모리를 할당해야합니다. 지금 그대로 서서 문자열을 무효로 복사하고 있습니다. ,

for(i=0;i<BUFFER_SIZE;i++) { 
    free(buffer[i]); 
} 
+1

나는 포인터가 너무 끔찍해! 그 점을 지적 해 주셔서 감사합니다. 저는 Java로 변환 된 C 프로그래머입니다. 따라서 C 프로그래밍의 잘못된 스타일을 설명합니다. – LanceHAOH

+0

글쎄, 나는 자바를 빨아 .... 걱정마. – Jiminion

2

당신은 무엇을 가리 키도록 문자 * 버퍼를 초기화하지 않는 :

는이 같은 필요

for(i=0;i<BUFFER_SIZE;i++) { 
    buffer[i] = malloc(MAX_STR_SIZE); 
} 

을 그리고 당신이 말에 완료되면이를 무료 예 buffer[0] = malloc(SIZE).