ptr1++;
을 쓰면 ptr1 = ptr1 + 1;
과 같습니다. 정수에 포인터를 추가하면 포인터의 메모리 위치가 가리키는 유형의 크기 (바이트)만큼 이동합니다. ptr1
이 0x5678
값을 갖는 char
포인터 인 경우 sizeof(char) == 1
이기 때문에 1을 증가 시키면 0x5679
이됩니다. 그러나 ptr1
이 Foo *
이고 sizeof(Foo) == 12
인 경우 포인터를 증가 시키면 해당 값은 0x5684
이됩니다.
이미 포인터가있는 요소에서 3 요소 떨어진 지점을 가리 키려면 해당 포인터에 3을 추가하면됩니다. 귀하의 질문에, 당신이 쓴 :
같은 일이다
char *ptr1 = &string1[start]; // array notation
:
char *ptr1 = string1 + start; // pointer arithmetic
다음과 같이 다시 쓸 수
:
const
를 사용
int main(void)
{
char string1[] = "something"; //[s][o][m][e][t][h][i][n][g][\0]
int start = 2, count = 3;
char string2[10] = {0};
// Ensure there is enough room to copy the substring
// and a terminating null character.
assert(count < sizeof(string2));
// Set pointers to the beginning and end of the substring.
const char *from = string1 + start;
const char *end = from + count;
// Set a pointer to the destination.
char *to = string2;
// Copy the indicated characters from the substring,
// possibly stopping early if the end of the substring
// is reached before count characters have been copied.
while (from < end && *from)
{
*to++ = *from++
}
// Ensure the destination string is null terminated
*to = '\0';
printf("%s",&string2);
}
하고 의미있는 변수 이름을 (from, to
, 또는 src, dst
대신 ptr1, ptr2
) 실수를 피하는 데 도움이됩니다. assert
을 사용하고 문자열이 null로 끝나는 지 확인하면 segfault와 다른 이상한 점을 디버깅하지 않아도됩니다. 이 경우 대상 버퍼는 이미 0으로 설정되어 있지만이 코드의 일부를 복사하여 다른 프로그램에서 사용할 때 그렇지 않을 수도 있습니다.
출처
2010-02-21 16:44:26
Dan
더 빠른 방법은 strncpy (string2, string1 + start, count) 일 것입니다. – zebrabox