동적 배열에 문제가 있으며 malloc
입니다. 나는 C에 상당히 익숙하다. 그래서 어떤 신기한 실수라도 변명해라.동적 배열 malloc이 별도의 배열을 비 웁니다.
문제는 배열 (이 경우 input_string)을 만들고 func2
에 전달하는 것입니다. 그런 다음 func2
테스트에서 input_string의 첫 번째 요소를 출력합니다.
malloc
전에 첫 번째 인쇄물에서 예상대로 작동하지만 malloc
이후에는 아무 것도 인쇄되지 않습니다. 이것은 사이에 이상한 내게 보인다 printf
진술에 나는 input_string에 아무 것도하지 않는다.
나는이 배열을 잘못 처리하고 있다고 가정하고 있지만 확실하지 않습니다. 여기
문제의 코드 조각입니다 :이
... // includes not in snippet
/* CONSTANTS */
#define LINE_LEN 80
/* Function declarations */
char* func1(void);
char* func2(int tl, char* input_string);
int main(void) {
char* input_string;
int tab_length;
char* output_string;
input_string = func1();
output_string = func2(tl, input_string);
return 0;
}
char* func1(void) {
char cur_char;
char* input_ptr;
char input_string[LINE_LEN];
while ((cur_char = getchar()) != '\n' && chars_read < 80) {
// iterate and create the array here
}
input_ptr = &input_string[0]; /* set pointer to address of 0th index */
return input_ptr;
}
char* func2(int tl, char* input_string) {
int n = 0, output_idx = 0;
char* output_ptr;
printf("\nBefore malloc: %c ", *(input_string));
output_ptr = malloc(tab_length * chars_read+1);
if (output_ptr == NULL) {
printf("Failed to allocate memory for output_ptr.\nExiting");
exit(1);
}
printf("\nAfter malloc: %c ", *(input_string));
...
return output_ptr;
}
P.s 업데이트 : 모든 선언되지 않은 변수는이 코드 조각의 외부에 선언되어있다. 모든 답변과 조언을
업데이트
감사합니다. 대단히 감사합니다.
어떻게'input_string'을 초기화합니까? 그것을 위해 메모리를 할당합니까? "아무것도 인쇄하지 않는다"는 것은 무엇을 의미합니까? – JohnB
경고와 함께 컴파일 했습니까? 나는. (gcc 사용) $ gcc -Wall -Wextra -pedantic -std = c89 ... – Morpfh
다음과 같이 input_string을 인스턴스화합니다. char * input_ptr; char input_string [LINE_LEN]; 그런 다음 몇 가지 물건을 추가하고 input_ptr을 func()에 전달합니다. – calderonmluis