如何将char*分配给具有唯一项的char*数组?

如何将char*分配给具有唯一项的char*数组?,c,arrays,C,Arrays,好吧,那不是很清楚。我想做的是: while (//something) { char * tempuser; char * users[100]; tempuser = "bobsmith" //I'm not actually doing this. But using a method that does the same thing users[i] = tempuser; } “bobsmith”的位置每次在循环中都是不同的。如果我按原样运行了

好吧,那不是很清楚。我想做的是:

while (//something) {    
    char * tempuser;
    char * users[100];
    tempuser = "bobsmith" //I'm not actually doing this. But using a method that does the same thing
    users[i] = tempuser;
}

“bobsmith”的位置每次在循环中都是不同的。如果我按原样运行了5次,最后一个条目是“janetsmith”,那么在此之前,数组中的所有5个位置,无论在分配时是否不同,都会以“janetsmith”结束。我应该如何分配用户[I],使其在所有索引中具有不同的值?

不要在循环体中创建数组
users
,使用
strdup
在数组中创建具有相同内容的新字符串。请记住,您使用的是指针而不是某种字符串对象。数组中的每个条目都保存内存中文本的地址

char *users[100]={0}; //one hundred pointers that are null so You don't use a wild one.
int i=0;
while(/*whatever*/) {
    char *tmp=getsometext(); //returns char pointer
    users[i++]=strdup(tmp); //copies contents pointed by tmp into new memory location and returns its address
}
//don't forget to free every pointer when You are done.

这是因为您正在分配变量tempuser的地址。最后,它将始终保留“janetsmith”的地址。尝试使用malloc()函数动态创建变量。

char*users[100]//有了这个,你可以在室外使用
而(//某物){
静态无符号整数i=0;
//字符*临时用户;
//tempuser=“bobsmith”//I实际上并没有这样做。但使用的方法与此相同
users[i]=返回字符指针()的方法;
i++;

如果(100)为什么不使用<代码> STD::字符串< /C> >?我的错误,这只是C,而不是C++ +DXX118,为什么它在C++上不被标记为C++?在这个平台上,垃圾邮件标签被禁止。谢谢!我已经在while循环之外声明了数组,但是我在最后添加了循环并忘记了。工作得很好,我以前试过,但没有成功。但现在成功了。多谢了。别忘了,我假设您希望数组中有一个副本,以防
getsometext()
返回一个指向已经堆分配的字符串的指针,您应该将其存储在数组中。通常函数不返回C字符串,而是获取一个字符指针作为参数,例如:
void getsometext(char*output)
在该指针处可以存储结果,只是为了向编写代码的人表明,他们负责内存。
char * users[100]; //with this you can use it outside while    
while (//something) {  

        static unsigned int i = 0;  
        //char * tempuser;

        //tempuser = "bobsmith" //I'm not actually doing this. But using a method that does the same thing
        users[i] = method_which_return_char_pointer();
        i++;
        if( 100 <= i)
          i=0;

    }