malloc char* 형 나누기

Kikialoa의 이미지

char* arrint;
arrint = (char*)malloc(sizeof(char) * 100);
memset(pBuf, '0', sizeof(char) * 100);
 
int n1 = 8;
int n2 = 4;
 
memcpy(pBuf, &n1, sizeof(int));
memcpy(pBuf, &n2, sizeof(int));

이런식으로 접근해서 100바이트 char*형을 int형 변수 25개로 바꿔
하나하나 값을 처리하고 싶은데 방법이 있을까요
처음 값 n1은 정상적으로 가능한데 나머지를 할 방법을 모르겠습니다..

익명 사용자의 이미지

이렇게 하면 깔끔합니다.

#include <stdio.h>
#include <memory.h>
 
#define SIZE 100
 
typedef union {
	char char_array[SIZE];
	int int_array[SIZE / sizeof(int)];
} buffer_t;
 
int main(void) {
	buffer_t *pbuffer = (buffer_t *)malloc(sizeof(buffer_t));
 
	for (int i=0; i != SIZE; ++i) pbuffer->char_array[i] = i;
 
	for (int i=0; i != SIZE / sizeof(int); ++i) printf("%#010x ", pbuffer->int_array[i]);
	puts("");
	return 0;
}
라스코니의 이미지

아마 arrint 와 pBuf 가 혼용되는 것 같네요. 일단 arrint 가 pBuf라고 보면
memcpy() 사이에 pBuf += sizeof(int)를 넣어보세요. 4개씩 건너뛰어야 다음 변수가 들어가겠죠. 같은 메모리에 계속 복사하면 덮어씌어지게 됩니다.