home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!pipex!bnr.co.uk!uknet!warwick!coventry!champion
- From: champion@cch.coventry.ac.uk (Alun)
- Newsgroups: comp.lang.c
- Subject: Re: Need help with string arrays
- Message-ID: <C0DLwq.n3@cck.coventry.ac.uk>
- Date: 5 Jan 93 10:17:13 GMT
- References: <1992Dec27.232512.22474@news.ysu.edu>
- Sender: news@cck.coventry.ac.uk (news user)
- Organization: Coventry University, Coventry, UK.
- Lines: 49
- Nntp-Posting-Host: cc_sysh
-
- In article <1992Dec27.232512.22474@news.ysu.edu> ah017@yfn.ysu.edu (John B. Lee) writes:
- ~
- ~In a current program that I am writing I have an array declaration
- ~that looks like this:
- ~
- ~char names[][4];
- ~
- ~How would I use the gets() function to put a string into this array.
- ~Am I declaring the array correctly to receive five strings? << This
- ~is what I'm trying to do.
- ~
-
- No you are not declaring it correctly.
- char names[][5];
- /* Declares an array of 5 (from 0 to 4) arrays of characters */
-
- Personally I would declare this as
- char *names[5];
-
- but you must remember that gets() is not good - it does nothing about bounds
- checking. If you type a name longer than the allocated memory then gets() will
- corrupt your program.
-
- Use fgets
-
- Example: (Not a very good one)
-
- int i;
- char *names[5]; /* 5 Names */
- char buf[MAX_NAME_SIZE + 1]; /* fgets() appends a '\0' */
-
- for(i = 0; i < 5; i++) {
- fgets(buf, MAX_NAME_SIZE, stdin);
- if(buf[strlen(buf) - 1] == '\n')
- buf[strlen(buf) - 1] == '\0';
- names[i] = malloc(sizeof(char) * (strlen(buf) + 1)); /* Test! Test! Test! */
- strcpy(names[i], buf);
- }
-
-
- Hope this helps
-
- -Alun
-
- --
- *I'm as bad as the worst - but thank God(?) I am as good as the best.*
- *People who think they know everything annoy those of us that do.*
- A.Champion | That's an interesting point, in the sense of
- (champion@uk.ac.cov.cch) | being very not interesting at all. - The Liar
-