2017-11-24 15 views
0

I 가지고 끈과 다른 기능에 의해 채워C strcpy를 배열하는 배열과 같이 선언

char *array[4]; 

즉 [ "하나", "2", "세」, 「네 "].

내 목표는이 배열을 마지막 두 요소를 제외한 새로운 배열에 복사하는 것이므로 new_array에 [ "one", "two"]가 포함됩니다.

+1

'int * new_array [2];'=>'char * new_array [2];'. 그리고'strncpy'는 널을 끝내지 않을 것이고 대신에'strdup'를 사용해야합니다. –

+0

그런 어리석은 실수 ... 고마워. 답변을 추가하려면 지금 동의하겠습니다. – Paradox

답변

3

귀하의 코드,

warning: passing argument 1 of ‘strncpy’ from incompatible pointer type [-Wincompatible-pointer-types] 

note: expected ‘char * restrict’ but argument is of type ‘int *’ 

통근자의 char *의를 strncpy (숯불 * __ __dest을 제한 :

int *new_array[2]; 

for (int i = 0; i < 2; i++){ 
    strncpy(new_array[i], array[i], strlen(array[i])); 
} 

을하지만, 다음과 같은 경고를받은 :

내가 지금까지 시도한 것입니다 매우입니다.

먼저 정수 포인터의 배열을 선언합니다 (따라서 경고). 그런 다음 포인터가 초기화되지 않습니다. strncpy은 (메모리가 초기화 된 경우에도, 그것은 당신의 문자열을 null이 종료되지 것)를 호출하는 적절한 함수가 아닙니다, 당신은 적절한 할당 & 사본 않습니다 strdup 필요 : 일부에

char *new_array[2]; 

for (int i = 0; i < 2; i++){ 
    new_array[i] = strdup(array[i]); 
} 

을 (기존 시스템은 strdup 사용하지 못할 수 있습니다. 당신이이 경우에있어, 그냥 두 가지 방법이 동적 메모리를 할당하고 더 이상 사용하지 않을 때 free을 필요로하는) ​​다음 strcpy(new_array[i],array[i]);

new_array[i] = malloc(strlen(array[i]+1));를 사용합니다.

그냥 예를 들어, 포인터를 저장하려면 음은 물론, array리터럴 포함되어 있기 때문에 당신은 당신은 포인터를 복사 할 수 있습니다, 당신의 문자열을 수정하지 않을 것

:

new_array[i] = array[i]; 
+1

@DavidBowling 편집 하겠지만'strdup'가 점점 더 널리 퍼지고 있습니다. –

1

원본과 대상이 호환되지 않습니다.
char * array [4]; int * new_array [2];

int를 실수로 삽입 하시길 바랍니다.

0

진 프랑수아 파브르 (Jean-François Fabre)가 제공 한 훌륭한 답변 외에도 알려진 크기조차도 프로그램이 발전함에 따라 변경 될 수 있다는 점을 지적했습니다. 이러한 이유 때문에 알려진 종결 자 (예 : NULL 또는 NaN).

나는 C로 시작한다고 가정하지만, 모든 것을 일과성으로 찾고 코드에서 선입견을 최소화하는 습관이 있습니다.

사람들은 strdup이 표준 C가 아니라고 지적하지만, 널리 사용 가능합니다. 나는 단지 킥을 위해 그것을 피할 것이다. 오류 검사 (과도한 것일지도 모르지만 ... 실제 코드는 이러한 것들로 채워 져야 함)에 주목하시기 바랍니다.

는 다음 코드를 살펴 보자 (그러나 그것을 사용하지 않는, 그것은 약간 깨진 수 있습니다) :

그런데
#include <errno.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

char **string_array_dup(char *const *ary) { 
    int count = 0; 
    char **copy; 
    if (!ary) 
    return NULL; 
    /* count string items - this is unsafe */ 
    while (ary[count++]) 
    ; 
    if (!count) 
     return NULL; 
    /* allocate memory for array and set terminator. */ 
    copy = malloc(sizeof(*copy) * (count + 1)); 
    if (!copy) 
    perror("ERROR"), exit(errno); 
    copy[count - 1] = NULL; 
    /* itterate over array, allocate and copy strings. */ 
    count = 0; 
    while (ary[count]) { 
    int register len = (int)strlen(ary[count]); 
    copy[count] = malloc(len + 1); /* remember NUL byte */ 
    if (!ary[count]) 
     perror("ERROR"), exit(errno); 
    memcpy(copy[count], ary[count], len + 1); /* copy NUL byte */ 
    count += 1; 
    } 
    return copy; 
} 

void string_array_print(char **ary) { 
    int count = 0; 
    while (ary[count]) { 
    printf("%s ", ary[count++]); 
    } 
    printf("\n"); 
} 

void string_array_free(char **ary) { 
    int count = 0; 
    /* free each string */ 
    while (ary[count]) { 
    free(ary[count++]); 
    } 
    /* free container */ 
    free(ary); 
} 

int main(void) { 
    char *array[] = { 
     "String", "array", "is", "always", "terminated", "with", NULL, 
    }; 
    char **copy = string_array_dup(array); 
    if (!copy) 
    perror("ERROR"), exit(errno); 
    string_array_print(copy); 
    string_array_free(copy); 
    return 0; 
} 

,이 코드는 단 하나의 malloc를 사용하도록 최적화 (또는 realloc 사용) 할 수 및 단일 free -보다 복잡한 복사 프로세스 (데이터 및 데이터 액세스 시간의 지역성 향상)를 희생해야합니다.