Pointers 需要帮助将字符数组复制到带有字符指针的数组结构中吗
我试图将字符数组单词复制到字符指针Pointers 需要帮助将字符数组复制到带有字符指针的数组结构中吗,pointers,struct,char,copy,Pointers,Struct,Char,Copy,我试图将字符数组单词复制到字符指针s[1].c,然后是另一个单词复制到字符指针s[2].c,但当我尝试这样做时,第二个单词似乎在所有两个指针中都被复制了。我怎样才能解决这个问题?我不想使用字符串 struct Stud { char *c; } s[100]; char word[32]; int main() { strcpy(word,"one"); s[1].c=word; word={0}; strcpy(word,"two"); s[2].c=word;
s[1].c
,然后是另一个单词复制到字符指针s[2].c
,但当我尝试这样做时,第二个单词似乎在所有两个指针中都被复制了。我怎样才能解决这个问题?我不想使用字符串
struct Stud {
char *c;
} s[100];
char word[32];
int main()
{
strcpy(word,"one");
s[1].c=word;
word={0};
strcpy(word,"two");
s[2].c=word;
cout<<s[1].c<<" "<<s[2].c;
return 0;
}
struct螺柱{
char*c;
}s[100];
字符字[32];
int main()
{
strcpy(单词“一”);
s[1].c=word;
字={0};
strcpy(单词“两”);
s[2].c=word;
cout在您的代码中,您正在设置s[1].c=word;
,这意味着您正在将s[1].c设置为word的地址。然后您将s[2].c=word;
设置为相同的精确内存位置。(对于c字符串,(char*)s1=(char*)2
不会像您预期的那样进行字符串复制。它只是将一个指针分配给另一个指针)
使用strdup
分配一个新内存块,然后将字符串复制到分配的空间中
这是你修改过的代码
struct Stud
{
char *c;
} s[100];
int main()
{
char word[32];
strcpy(word, "one");
s[0].c = strdup(word); // In C/C++ the first array index is 0
strcpy(word, "two");
s[1].c = strdup(word);
// Should check to make sure s[0].c and s[1].c are not NULL....
cout << s[0].c << " " <<s [1].c;
free(s[0].c);
free(s[1].c);
return 0;
}
struct螺柱
{
char*c;
}s[100];
int main()
{
字符字[32];
strcpy(单词“一”);
s[0].c=strdup(word);//在c/c++中,第一个数组索引是0
strcpy(单词“两”);
s[1].c=strdup(word);
//应检查以确保s[0].c和s[1].c不为空。。。。
因为word的地址永远不会改变。你可以用它来完成你想要的事情。好的。别忘了内存。你能解释一下我应该如何使用strdup吗?没关系。我写了s[1]。c=strdup(word);s[2]。c=strdup(word);现在它可以工作了:)