Beginner struggling with pointer and string arrays

R

Riaan C

Hi

I'm new to C. Here's the problem. I understand the whole concept of
pointers and can easily use it with normal non-array variables.

I want to declare a array of strings, thus multidimensional character
array, in my int main();

Then I want to pass this to a function that will scanf all the values.
I also want another function to display all the names but I just can
get it working.

How do yo do it?

Thanks

Riaan
 
O

osmium

Riaan said:
I'm new to C. Here's the problem. I understand the whole concept of
pointers and can easily use it with normal non-array variables.

I want to declare a array of strings, thus multidimensional character
array, in my int main();

Then I want to pass this to a function that will scanf all the values.
I also want another function to display all the names but I just can
get it working.

Fill in the blanks.

#include <stdlio.h> // exit()

void chat(char t[][20])
{
}
/*-------------------------*/
void display(char u[][20])
{
}
/*-------------------------*/
int main()
{
char s[3][20];
chat(s);
display(s);
}
 
M

Micah Cowan

Hi

I'm new to C. Here's the problem. I understand the whole concept of
pointers and can easily use it with normal non-array variables.

I want to declare a array of strings, thus multidimensional character
array, in my int main();

No, more likely you want to declare an array of *pointers* to
strings. An array of strings is awkwards if the strings are of
different lengths, since you would still be forced to allocate
exactly the same amount of space for each string.

(Example of an array of strings:)

char aos[][6] = {
"Hello",
"there",
"bud"
};

As you can see, "bud" above still gets 6 bytes even though it
only uses 4 (counting the terminating null character). Compare
with:

(Example of an array of pointers-to-string:)

char *aopts[] = {
"Hello",
"there",
"bud"
};

The disadvantage to the above is that you must either point the
strings to string literals (as above), in which case you
shouldn't try to modify them; or you need to dynamically
(probably) allocate space for each and every element (and,
therefore, free() them also).
Then I want to pass this to a function that will scanf all the values.
I also want another function to display all the names but I just can
get it working.

I'm not sure what exactly you mean here. Please explain in more
detail what you wish to do.

-Micah
 

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

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,044
Latest member
RonaldNen

Latest Threads

Top