는 :strcpy가 작동하지 않지만 직접 할당이 작동하는 이유는 무엇입니까? 다음 코드에서
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char** tab;
int n;
}slist;
void print(slist* p);
void add(slist* p, const char* s);
void add(slist* p, const char* s)
{
if(p->n==0)
{
p->tab=(char**)malloc(sizeof(char**));
}
strcpy(p->tab[p->n],s);
p->n=p->n+1;
}
void print(slist* p)
{
int i;
printf("[");
for(i=0;i<p->n;i++)
printf(" %s",p->tab[i]);
printf(" ]");
}
int main()
{
char s1[25] = "Picsou";
char s2[25] = "Flairsou";
slist* p = (slist*)malloc(sizeof(slist));
p->n=0;
p->tab=NULL;
add(p,s1);
add(p,s2);
print(p);
return 0;
}
기능 add()
이 작동하지 않습니다,하지만 난 그것을 변경하는 경우 :
void add(slist* p, const char* s)
{
if(p->n==0)
{
p->tab=(char**)malloc(sizeof(char**));
}
p->tab[p->n]=s;
p->n=p->n+1;
}
완벽하게 잘 작동하는 것 같다. 첫 번째 경우 출력은 " ["
입니다. 두 번째 경우에는 이되어야합니다. " [ Picsou Flairsou ] "
이어야합니다. 이유를 이해할 수 없습니다. 포인터를 다루는 새로운 사람들과 공통되는, 여기에 오류
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char** tab;
int n;
}slist;
void print(slist* p);
void add(slist* p, const char* s);
void print(slist* p)
{
int i;
printf("[");
for(i=0;i<p->n;i++)
printf(" %s",p->tab[i]);
printf(" ]");
}
void add(slist* p, const char* s)
{
slist* tmp = (slist*)malloc(sizeof(slist));
tmp->tab=(char**)malloc(sizeof(char*)*(p->n+1));
int i;
for(i=0;i<p->n;i++)
tmp->tab[i]=(char*)malloc(sizeof(char));
strcpy(tmp->tab[p->n],s);
tmp->n=p->n+1;
p = tmp;
}
int main()
{
char* s1 = "Picsou";
char* s2 = "Flairsou";
slist* p = (slist*)malloc(sizeof(slist));
p->n=0;
p->tab=NULL;
add(p,s1);
add(p,s2);
print(p);
return 0;
}
포인터 컬렉션을위한 공간을 할당하지만, 포인터를 가리 키도록 아무 것도 할당하지 마십시오. – John3136
나는 게시물을 편집했지만, 당신이 말한 것을 시도했지만, 여전히 작동하지 않는다. 나는 무엇을 해야할지 모르겠다. ... 대답 해 주셔서 감사합니다. ^^ –
@ Maxime Fleury : 당신은 1에 대한 메모리를 할당합니다. char을 입력 한 다음 전체 문자열을 해당 메모리로 복사하려고 시도합니다. 당연히 작동하지 않는 것은 당연합니다. 그리고 왜 당신은'malloc'의 결과를 캐스팅하고 있습니까? – AnT