Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

array

Status
Not open for further replies.

cat5ive

MIS
Dec 3, 2004
184
0
0
US
Hi,

How can I declare a char array that will contain 50 names and max. length of each name is 30.

Thanks in advance.
 
The simple way is

#define N 50
#define MAX_LENGTH 31

char names[N][MAX_LENGTH];

This gives you an array of 50 arrays of 30 characters. But if the maximum length of each name is 30 and the expected length is considerably less, you might be better off with dynamic allocation:

#define N 50
#define MAX_LENGTH 31

char *names[N];

Then for each new name, you use a buffer of length MAX_LENGTH to read the name, and malloc to simulate arrays that are "just big enough" for each name on an idividual basis:

char buffer[MAX_LENGTH];
int i = 0;

while (fgets(buffer, sizeof buffer, stdin) != NULL) {
names = malloc(strlen(buffer) + 1);
if (names == NULL)
panic();
strcpy(names, buffer);
++i;
}

But if you do it that way, don't forget to release your memory when you're done with it:

while (--i >= 0)
free(names);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top