2014-07-14 1 views
-1

함수, 포인터 및 배열에 대한 연습을하고 있는데이 프로그램을 실행하고 컴파일하는 데 어려움을 겪고 있습니다. 기본적으로 배열을 선언하고 함수를 사용하여 입력 배열의 값을 포인터 char 배열에 저장 한 다음 포인터 배열을 출력하지만 함수를 사용할 수는 없습니다.char 배열에서 포인터 char 배열로 문자열을 전달하는 방법은 무엇입니까?

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





void cut_alphabet(char a[]); 
char convert(char b[]); 


int main() 
{ 

    char array[10][1000]; 
    int i; 

    for(i=0; i<10; i++) 
    { 

     printf(" Please input a string value"); 
     fgets(array[i], 1000, stdin); 

    } 

    convert(array[10]); 

    return 0; 

} 



char convert(char b[]) 
{ 

    int i; 
    char *psentence[10][1000]; 


    for(i=0; i<10; i++) 
    { 

     b[i] = &psentence[i]; 

     return psentence; 

    } 
+0

호기심입니다. 왜 당신은 많은 계정을 만들고 있습니까? – ArjunShankar

+0

FYI 프로그램이 먼저 컴파일되고 실행됩니다. – gprathour

+0

특정 프로그램에 대한 도움을 요청하는 질문을 올렸습니다. 나는 downvoted되었고 더 이상 게시 할 수 없다고 말했습니다. 단지 3 개의 게시물 후에도. – user3822760

답변

0

몇 일이 잘못 그래서 나와 함께 곰이 있습니다 : 당신이 실제로 무엇을하려고하는

int main() { 

char array[10][1000]; // Ok, Note that you will use these ~10 kB of data for as long as the program runs. 

int i; 

for(i=0; i < 10; i++) { 
    printf(" Please input a string value"); 
    fgets(array[i], 1000, stdin); 
} 

// This next line has an error in your code, what you are saying here is: 
// Send in the 11th string in "array", however array only has 
// 10 strings so this will not work as intended. 
// If you wish to send in ALL 10 strings just write convert(array) 
// and change the function prototype to char ** convert(char array[][1000]). 
// Please note that the the [1000] must always match between the function and a 
// Statically allocated two-dimensional array. (One reason to prefer pointers 
// in this use-case. 

convert(array); 

return 0; 

}

내가 대해 약간 불확실 해요 여기

코드입니다 여기에서 성취하기 위해 ... 당신은 psentence를 b에 복사하고 싶습니까? 그렇다면, 당신은 어떤 방향으로 향하고 싶습니까? 현재는 초기화되지 않은 데이터이므로 코드에 불필요한 것처럼 보입니다. 대신에 2 차원 배열을 char 포인터의 배열로 변환하고 싶다면 좀 더 의미가 있습니다. 그래서 ... 그와 함께 갈

가정

  • 당신은 변환됩니다 얼마나 많은 줄 모르는 것입니다.
  • 인수 b [] []는 반환 값보다 오래 살 수 있으므로 데이터를 복제 할 필요가 없습니다.

다음은 기본적으로 동일한 작업을 수행하면서 b에있는 문자열에 대한 포인터로 배열을 채우는 것입니다.

이 버전에서는 요소를 매개 변수로 저장하기 위해 배열을 사용합니다. 포인터 배열이 함수에서 반환 된 후에도 필요하기 때문에 필요합니다. 또한이 경우 반환 값을 void로 변경할 수 있습니다.

void convert(char* ptr_arr[], char b[][1000], int lines) { 
    int i; 
    for(i=0; i<lines; i++) {   
     ptr_arr[i] = b[i]; // b[i] yields a pointer to the i'th line. 
    } 
} 

이 버전은 포인터가있는 새로운 동적 할당 배열을 반환합니다. 할당 된 데이터는 나중에 무료로 호출하여 해제해야합니다. 자세한 내용은 C의 Google 동적 메모리 할당

char** convert(char b[][1000], int lines) { 
    char **ptr_arr = malloc(sizeof(char*)*lines +1); // Allocate enough space for lines +1 pointers. 

    // Check that allocation succeeded. 
    if (ptr_arr == NULL) return NULL; 

    int i; 
    for(i=0; i<lines; i++) {   
     ptr_arr[i] = b[i]; 
    } 
    // Use a NULL ptr to mark the last element (this is optional) 
    ptr_arr[lines] = NULL; 

    // Finally, return the new table: 
    return ptr_arr; 
} 
관련 문제