반응형
문자열 배열 초기화
올바른 초기화 방법은 무엇입니까?char**
적용 범위 오류가 발생함 - 시도 시 UNinIT(초기화되지 않은 포인터 읽기)
char **values = NULL;
또는
char **values = { NULL };
이 예제 프로그램은 C 문자열 배열의 초기화를 보여줍니다.
#include <stdio.h>
const char * array[] = {
"First entry",
"Second entry",
"Third entry",
};
#define n_array (sizeof (array) / sizeof (const char *))
int main ()
{
int i;
for (i = 0; i < n_array; i++) {
printf ("%d: %s\n", i, array[i]);
}
return 0;
}
다음을 출력합니다.
0: First entry
1: Second entry
2: Third entry
그냥 해도 좋습니다.char **strings;
,char **strings = NULL
또는char **strings = {NULL}
초기화하려면 malloc을 사용해야 합니다.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(){
// allocate space for 5 pointers to strings
char **strings = (char**)malloc(5*sizeof(char*));
int i = 0;
//allocate space for each string
// here allocate 50 bytes, which is more than enough for the strings
for(i = 0; i < 5; i++){
printf("%d\n", i);
strings[i] = (char*)malloc(50*sizeof(char));
}
//assign them all something
sprintf(strings[0], "bird goes tweet");
sprintf(strings[1], "mouse goes squeak");
sprintf(strings[2], "cow goes moo");
sprintf(strings[3], "frog goes croak");
sprintf(strings[4], "what does the fox say?");
// Print it out
for(i = 0; i < 5; i++){
printf("Line #%d(length: %lu): %s\n", i, strlen(strings[i]),strings[i]);
}
//Free each string
for(i = 0; i < 5; i++){
free(strings[i]);
}
//finally release the first string
free(strings);
return 0;
}
올바른 방법은 없지만 리터럴 배열을 초기화할 수 있습니다.
char **values = (char *[]){"a", "b", "c"};
또는 각 항목을 할당하고 초기화할 수 있습니다.
char **values = malloc(sizeof(char*) * s);
for(...)
{
values[i] = malloc(sizeof(char) * l);
//or
values[i] = "hello";
}
언급URL : https://stackoverflow.com/questions/21023605/initialize-array-of-strings
반응형
'programing' 카테고리의 다른 글
oracle plsql: XML을 구문 분석하고 테이블에 삽입하는 방법 (0) | 2023.06.25 |
---|---|
C# mongodb driver 2.0 - 대량 작업에서 어떻게 뒤집습니까? (0) | 2023.06.25 |
SQLALCHEMY_TRACK_MODIES를 사용하지 않도록 설정할 수 있는지 어떻게 알 수 있습니까? (0) | 2023.06.25 |
Base64 인코딩 파일을 저장할 SQL 데이터 유형은 무엇입니까? (0) | 2023.06.25 |
Yml 구성 파일 "Inheritance"(Spring 부트 포함) (0) | 2023.06.25 |