Copying names into a array

Folks,
I'm faced with this very simple but challenging problem that I need to implement in a chat client I am developing. The sub-task I'm trying to solve is saving a series of names in an array.

Here is a test code that I have written..once I have this working I will transport it to my system.
Take a look..
This piece of code is supposed to keep prompting the user to enter names and update and display the array as the user enters names. Instead, it just keeps overwritting all the former elements in the array.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char ** argv){
char * clients[25];
int j = 0;
for(j; j < 25;j++) {
char tempArr[20];
clients[j] = tempArr;
}

int count = 0;
while(1){
char firstName[20];
printf("What is your first name? ");
scanf("%s", firstName);
printf("This is the firstName : %s \n", firstName);
clients[count]=firstName;

//printf(clients[count]);

printf("This is the updated list: \n");
int i;
for (i=0;i<=count;i++){
//printf("count is: %i\n",count);
printf("element at index %i is %s\n",i,clients[i]);
}

count++;
}
}


Would really appreciate you help and advice...Thankyou
AI
char* is not a string. Wipe this out of your mind. Pointers and strings are two very different things.

You only have 1 actual string here (or really, you have one char buffer), and that buffer is 'firstName'. You also have tempArr, but you don't seem to be using it.

You then have 'clients', which are 25 pointers (read: not strings). You then do this: clients[count]=firstName;, which tells clients[count] (read: a pointer, not a string) to point to 'firstName'.

Ultimatley what is happening is all of your clients end up pointing to firstName. So whenever firstName changes, all of them appear to change because they're all accessing the same data.

The easy solution here is to use std::string:

1
2
3
4
5
#include <string>
...
string clients[25];
...
clients[count] = firstName;


But since you seem to be more of a C man, rather than C++, the C alternative would be to use char buffers and strcpy:

1
2
3
char clients[25][20];  // 25 buffers, each 20 characters wide
...
strcpy( clients[count], firstName );
Great insight. Thankyou. Works like a charm.
Topic archived. No new replies allowed.