Beginner array question

S

Stang1

In the following code, can someone please explain to me what exactly
is happenening as far as accessing a 2-dimensional array with a 1-
dimensional index? What is the benifit of this?

Thanks in advance!


ck_name (name_list, max_num, item, index)

char item[];
char name_list[MXMARK][MXNAME]; /* MXMARK=80, MXNAME=24 */
short max_num;
short *index;

{ /* ck_name.c */

int np;

for (*index = 0; *index < max_num; (*index)++)
{
if (strcmp (name_list[*index], item) == 0)
return (0);
}
return (1);

} /* ck_name.c */
 
W

Walter Roberson

In the following code, can someone please explain to me what exactly
is happenening as far as accessing a 2-dimensional array with a 1-
dimensional index? What is the benifit of this?
char name_list[MXMARK][MXNAME]; /* MXMARK=80, MXNAME=24 */
if (strcmp (name_list[*index], item) == 0)

Hint: strcmp is expecting the *address* of a string.
name_list[*index] is not addressing an individual 'char'.
 
M

Malcolm McLean

Stang1 said:
In the following code, can someone please explain to me what exactly
is happenening as far as accessing a 2-dimensional array with a 1-
dimensional index? What is the benifit of this?

Thanks in advance!
The important thing to remember is that in C two-dimensional arrays and
higher are quite advanced. The basic idea is simple enough, the syntax for
accessing rows or other elements gets very difficult very quickly.
ck_name (name_list, max_num, item, index)

char item[];
char name_list[MXMARK][MXNAME]; /* MXMARK=80, MXNAME=24 */
In this case you have declared a contiguous block of memory, 80 * 24 chars
wide, or an array of 80 arrays of 24 chars.
short max_num;
short *index;

{ /* ck_name.c */

int np;

for (*index = 0; *index < max_num; (*index)++)
{
if (strcmp (name_list[*index], item) == 0)
return (0);
}
return (1);

} /* ck_name.c */
Now we are hittling another complexity, which is array-pointer equivalence.
In most situations, the name of an array is the same thign as a pointer to
the first element of that array. so

name_list[12]

is the same as a pointer to the first char in the thirteenth na,e in your
list. You can then manipulate it as you would any other string, for instance
by passing it to strcmp(). If you try to write beyond element 23 you will
corrupt the next name in the list.

In real programs you only rarely want a hard-coded limit of 80 names. So you
would calculate the number of names needed and then call malloc(). However
that's a whole new topic.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,430
Messages
2,571,676
Members
48,796
Latest member
Greg L.

Latest Threads

Top