2017-01-20 3 views
0

가변 문자열 배열을 반복하는 가장 좋은 방법은 무엇입니까? 예를 들어 내가 좋아하는 것C에서 문자열 조작 배열

struct Book{ 
    char chapter_names[20][50]; 
    int chapters; 
    ...} 

int main(){ 
    struct Book Redwall; 
    strcpy(*chapter_names, "The Wall"); 
    strcpy(*(++chapter_names), "The Grove"); 

    printf("Chapter 1: %s", chapter_names[0]); 
    printf("Chapter 2: %s", chapter_names[1]); 

    return 0; 
} 

이의 출력은 할 수 :

Chapter 1: The Wall 
Chapter 2: The Grove 

이 코드는

error: lvalue is required as increment operand 
+0

이 코드를 컴파일하려고했을 때 어떤 현상이 발생 했습니까? –

+0

질문에 편집 됨 – David

+0

'chapter_names'는 배열입니다. 배열을 증가시킬 수 없습니다 ... –

답변

1

결과 당신은 배열에 그런 증가 연산자를 사용할 수 없습니다 구조체 내에서. 다음과 같은 코드를 찾고있을 것입니다 :

struct Book{ 
    char chapter_names[20][50]; 
    int chapters; 
    }; 

    int main(){ 
     struct Book Redwall; 
     strcpy(*(Redwall.chapter_names), "The Wall"); 
     strcpy(*(Redwall.chapter_names+1), "The Grove"); 

     printf("Chapter 1: %s\n", Redwall.chapter_names[0]); 
     printf("Chapter 2: %s\n", Redwall.chapter_names[1]); 

     return 0; 
    } 
+0

'strcpy()'줄에도'Redwall.chapter_names [0]'등을 쓰지 않는 이유는 무엇입니까? 이해하는 것이 훨씬 쉬울 것이며 더 느릴 수도 없습니다. –

+0

정확하게. OP가 약간 새로운 것 같아서, 나는 단지 그가 (a [1] == (a + 1))'아이디어를 얻길 원했다. 그래서 저는 할당에서'chapter_names + 1'을, 그리고 인쇄에서'chapter_names [1]'을 사용했습니다. – 16tons

+2

좋은 습관을 그들에게 가르치는 것이 현존하는 나쁜 습관을 격려하는 것보다 낫다. –

0

가지고있는 챕터 이름을 추적 할 수있는 int가 있으므로 아마도이 코드를 사용해야합니다.

Redwall.chapters = 0; // Make sure it's initialised first 
strcpy(Redwall.chapter_names[Redwall.chapters++], "The Wall"); 
strcpy(Redwall.chapter_names[Redwall.chapters++], "The Grove"); 

그리고 for 루프를 사용하여 각각을 순환 할 수 있습니다.

for(i=0;i<Redwall.chapters;i++) { 
    printf("Chapter %d: %s", i+1, Redwall.chapter_names[i]); 
}