Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with inputting multidimensional string arrays....
#1
Hi. I am very new to c/c++ and I need some help. Can someone show me how to make a program that has a mulidimensional array of strings so I can keep a list of names, and then input x ammount of names. So, I would have like a prompt that says "How many names do you wan't to enter: " and then you type in the names and then you go through a for loop statement and type all the names. Then it would show each name you typed in. Here's what I have so far (but I can't even get it to run because I don't know what I'm doing):

Code:
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <conio.h>

int main()
{
    int number;
    int i;
    char tname[100];

    printf("How many names do you want to enter: ");
    scanf("%d", &number);
    
    char *names[number];
    for(i=0,i<number,i++)
    { names=(char *) malloc (100); }
    
    for(i=0,i<number,i++)
    {
        printf("Name %d: ", i);
        scanf(" %s", &tname);
        strcpy(names[i], &tname);
    }

    while (!kbhit()) {}
    free(names);
    return 0;
}

also, what is stdafx.h
am: "Where should I put this thing so that it doesn't hurt anyone we know or care about?"
Max:"Out the window, Sam. There's nobody but strangers out there."
Reply
#2
just remember char arrays are "strings" so you have to have char variable[stringsNum][stringLength]
am an asshole. Get used to it.
Reply
#3
I don't understand what you are trying to tell me.
am: "Where should I put this thing so that it doesn't hurt anyone we know or care about?"
Max:"Out the window, Sam. There's nobody but strangers out there."
Reply
#4
you char tname[100] is just one string of length 100. you make 10 strings of length 100, you would have to do this: char stringArray[10][100]
am an asshole. Get used to it.
Reply
#5
Your almost there typosoft, just a few things wrong.

First off, malloc is defined in stdlib.h, including it will remove errors about malloc returning the wrong type.

You want the names array to be a two-dimensional dynamic array like names[number][100]. Because arrays must be declared to have a constant size you need to use dynamic arrays (pointers) instead. Your names declaration should look like:
Code:
char **names;
This is a pointer to pointer of char. Think of it as the first pointer pointer to a list of pointers to char. Confused, dont worry. You can index it just like a regular array later on.

After declaring the array and getting the value for number, you need to allocate space for your names array. First you need to allocate space for the first pointer:
Code:
names = malloc(number);
Which allocates space for a list of pointers of size number, then you need to allocate space for each of the strings in that list. You nearly had this correct.
Code:
for(i = 0; i < number; i++) {
  /* Allocate strings of size 100 */
  names[i] = malloc(100);  
}
Notice that the names array is being indexed like an oridinary array and that the return value of malloc is not being cast (because stdlib.h is included). In your code you used commas to separate the expressions to the for loop, you should use semicolans. Commas are used in for loops to separate multiple expressions, such as setting two variables at the start, for example:
Code:
for(i = 0, j = 0; i < 10; i++, j++);

Your name reading loop is almost correct again, except that you don't need the address (&) operator when passing tname to scanf and strcpy. Both scanf and strcpy are expecting a pointer to char, and although tname is defined as char tname[100], its first element is a pointer to the string. So change those two lines to:
Code:
scanf("%s", tname);
strcpy(names[i], tname);

For slightly more portable code you could replace:
Code:
while(!kbhit()) {}
With:
Code:
while(!getchar());
Note that the while loop consists of a single empty statement, which is more elegant (IMHO) than the empty brace set.

HTH
esus saves.... Passes to Moses, shoots, he scores!
Reply
#6
Thanks for helping out, but I am still getting 2 errors:
Quote:error C2440: '=' : cannot convert from 'void *' to 'char *'
Conversion from 'void*' to pointer to non-'void' requires an explicit cast
Quote:error C2065: 'getkey' : undeclared identifier

I remember going to a place on the net that had a list of all C's commands and what library they are in, but I don't remember the url. Here's the code now that I fixed the parts you said to fix:

Code:
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>

int main()
{
    int number, i;
    char tname[100];
        
    printf("How many names do you want to enter: ");
    scanf("%d", &number);
    char **names;
    
    for(i=0; i<number; i++) {
         names[i] = malloc(100);
    }
    
    for(i=0; i<number; i++) {
         printf("Name %d: ", i);
         scanf(" %s", tname);
         strcpy(names[i], tname);
         printf("%s", names[i]);
    }
    
    while (!getkey());
    free(names);
    return 0;
}
[/quote][/code]
am: "Where should I put this thing so that it doesn't hurt anyone we know or care about?"
Max:"Out the window, Sam. There's nobody but strangers out there."
Reply
#7
Your need two malloc statements, one for the pointer list for names and one (the loop) to malloc each of the strings. Your malloc block should look like:
Code:
names = malloc(number);
for(i = 0; i < number; i++) {
  names[i] = malloc(100);
}
I honestly don't know why the cast error is showing up, what C compiler are you using? If you still have trouble with it, try using the explicit casts (they may also help you understand how the memory allocation is working a little better):
Code:
names = (char **)malloc(number);
for(i = 0; i < number; i++) {
  names[i] = (char *)malloc(100);
}

Quote:error C2065: 'getkey' : undeclared identifier
Whoops, its getchar, not getkey. getchar is defined in stdio.h. It returns the next character read from stdin.

Quote:I remember going to a place on the net that had a list of all C's commands and what library they are in, but I don't remember the url. Here's the code now that I fixed the parts you said to fix:
Ive got the man and info pages installed (under Unix), so thats what I use, but doing a google search on "man command" should bring up the right info. The problem is that it is really only safe to do this for Standard C functions, you will need to check you specific compilers documentation for details on non-standard functions such as kbhit().
esus saves.... Passes to Moses, shoots, he scores!
Reply
#8
When you don't know where to find a concrete function, just google for it. You'll end in some .edu domain with complete help about it including, of course, which header file has to be included.

You can also try MSDN at http://msdn.microsoft.com but beware: MSVC uses some functions differently.
SCUMM (the band) on Myspace!
ComputerEmuzone Games Studio
underBASIC, homegrown musicians
[img]http://www.ojodepez-fanzine.net/almacen/yoghourtslover.png[/i
Reply
#9
My first program is coming along nicely now, thanks to the help, but I have four more questions:

1) how can I clear the screen?

2) is it better to use cout and cin rather than printf and scanf?

3) do I still have to free(names) using the way LooseCaboose malloced everything?

4) and why when I try to make a function do I get errors: wait for key undeclared identifier and redefinition: different type modifiers?
here's the end part of the main() and the wait_for_key function (it is supposed to clear the keyboard buffer and then wait for a keypress):

Code:
wait_for_key();
    return 0;
}

void wait_for_key()
{
    while (getchar());
    while (!getchar());
}
am: "Where should I put this thing so that it doesn't hurt anyone we know or care about?"
Max:"Out the window, Sam. There's nobody but strangers out there."
Reply
#10
1. It depends on the compiler and console mode. For example, in Borland console / MSDOS compiler it is "clrscr();"

2. I hate C++, so I hate cin and cout. I prefer keeping track of what I do. I'd use scanf and printf.

3. Of course you have to.

4. You have to either place your wait_for_key function before your main function (to make it visible to main) or use a prototype (like those DECLARE SUBs)...

A prototype is just locating this at the beginning or in a .H file:

Code:
void wait_for_key();

main()...

wait_for_key()
{
...
}

I am too lazy and what I do is place all the functions before the main. Only your export functions have to be in the .H, so it is the best sollution for me (I hate prototypes and typing more than inteneded Wink ).
SCUMM (the band) on Myspace!
ComputerEmuzone Games Studio
underBASIC, homegrown musicians
[img]http://www.ojodepez-fanzine.net/almacen/yoghourtslover.png[/i
Reply


Forum Jump:


Users browsing this thread: 4 Guest(s)