473,473 Members | 4,257 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

How to input strings of any lengths into arrays of type: char *array[SIZE] ?

hey everyone!
i have this little problem. consider the following declaration:

char *array[4] = {"wilson", "string of any size", "etc", "input"};

this is a common data structure used to store strings of any lengths
into an array of pointers to char type variable.

my problem is: given the declaration

char *array[SIZE];
how to store strings of any length into this array from the user input
using functions like "scanf", "gets" etc. ?

let me know if you get it!

-thanks,
arko

Nov 14 '05 #1
7 5617
ar******@gmail.com wrote:
hey everyone!
i have this little problem. consider the following declaration:

char *array[4] = {"wilson", "string of any size", "etc", "input"};

this is a common data structure used to store strings of any lengths
into an array of pointers to char type variable.
Nope. You do not store strings but pointers to the respective first
character of these strings.
Consider the difference between.
char *cannot_be_modified = "foo";
and
char just_an_array[] = "foo";

my problem is: given the declaration

char *array[SIZE];
how to store strings of any length into this array from the user input
using functions like "scanf", "gets" etc. ?
Make array[i] point to the buffer in which you want to store/have
stored the "i"th string.

let me know if you get it!


This I hereby do.

Give us your best shot at it in the form of a compilable program
and you will get more feedback.
Otherwise, there is always the ring of homework with certain
questions...
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 14 '05 #2
In article <11**********************@g47g2000cwa.googlegroups .com>,
<ar******@gmail.com> wrote:
my problem is: given the declaration char *array[SIZE];
how to store strings of any length into this array from the user input
using functions like "scanf", "gets" etc. ?


You don't. Functions "like" scanf() and gets() are functions
that may return strings of indefinite length into the user buffer
which is *assumed* to be "big enough". Clearly any assumption of
"big enough" is going to be violated in the face of your
requirement to be able to store strings of "any length" -- if
the user provided a 7.2 exabyte long buffer, the program would
fail the first time the input was 7.3 exabytes long.

If you use fgets() instead of "functions like" scanf and gets,
then you have the ability to specify a maximum input size that
will not be exceeded. That gives you a chance to read a block
of input at a time into a fixed-length buffer, then allocate
dynamic memory to hold the contents. You could either create a
linked-list of these dynamic buffers and then at the end create
a single dynamic buffer long enough to hold the end result,
or you could use realloc() as you went along -- simpler logic
but much less efficient.

Naturally, if your system only -has- 512 Mb of available memory,
then you aren't going to be able to deal with the 7.3 exabyte long
input, but at least you will be able to handle the situation
smoothly whereas if you use functions "like" scanf and gets
you would almost certainly crash in the attempt.

Handling input of "any length" is a mugs game -- no matter how
sophisticated your buffering, you are never going to be able to
read "all" of /dev/zero or /dev/random (on Unix systems).
--
Entropy is the logarithm of probability -- Boltzmann
Nov 14 '05 #3
ar******@gmail.com wrote:
.... snip ...
my problem is: given the declaration

char *array[SIZE];
how to store strings of any length into this array from the user
input using functions like "scanf", "gets" etc. ?


You can't. Obviously, once you define a SIZE that is a limit.
However there is a solution: store pointers to strings of varying
size. You can form those strings in malloced memory, which can be
adjusted to the actual string size. How do I do that, you ask?
Simple - just download ggets.zip from my site, and compile and use
it.

<http://cbfalconer.home.att.net/download/ggets.zip>

--
Some informative links:
news:news.announce.newusers
http://www.geocities.com/nnqweb/
http://www.catb.org/~esr/faqs/smart-questions.html
http://www.caliburn.nl/topposting.html
http://www.netmeister.org/news/learn2quote.html

Nov 14 '05 #4
Walter Roberson wrote:
In article <11**********************@g47g2000cwa.googlegroups .com>,
<ar******@gmail.com> wrote:
my problem is: given the declaration
char *array[SIZE];
how to store strings of any length into this array from the user input
using functions like "scanf", "gets" etc. ?


You don't. Functions "like" scanf() and gets() are functions
that may return strings of indefinite length into the user buffer
which is *assumed* to be "big enough". Clearly any assumption of
"big enough" is going to be violated in the face of your
requirement to be able to store strings of "any length" -- if
the user provided a 7.2 exabyte long buffer, the program would
fail the first time the input was 7.3 exabytes long.

If you use fgets() instead of "functions like" scanf and gets,
then you have the ability to specify a maximum input size that
will not be exceeded.


When using scanf(), one certainly can restrict the number of
characters read.
That gives you a chance to read a block
of input at a time into a fixed-length buffer, then allocate
dynamic memory to hold the contents. You could either create a
linked-list of these dynamic buffers and then at the end create
a single dynamic buffer long enough to hold the end result,
or you could use realloc() as you went along -- simpler logic
but much less efficient.
This point certainly can be debated. Increasing the buffer size
by a factor instead of a fixed amount (maybe with a final
realloc()ation in order to reduce the amount needed to the
minimum may be more efficient).
Naturally, if your system only -has- 512 Mb of available memory,
then you aren't going to be able to deal with the 7.3 exabyte long
input, but at least you will be able to handle the situation
smoothly whereas if you use functions "like" scanf and gets
you would almost certainly crash in the attempt.

Handling input of "any length" is a mugs game -- no matter how
sophisticated your buffering, you are never going to be able to
read "all" of /dev/zero or /dev/random (on Unix systems).


Unless the system dies at a convenient moment... ;-)
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 14 '05 #5

Walter Roberson wrote:
In article <11**********************@g47g2000cwa.googlegroups .com>,
<ar******@gmail.com> wrote:
my problem is: given the declaration

char *array[SIZE];
how to store strings of any length into this array from the user inputusing functions like "scanf", "gets" etc. ?


You don't. Functions "like" scanf() and gets() are functions
that may return strings of indefinite length into the user buffer
which is *assumed* to be "big enough". Clearly any assumption of
"big enough" is going to be violated in the face of your
requirement to be able to store strings of "any length" -- if
the user provided a 7.2 exabyte long buffer, the program would
fail the first time the input was 7.3 exabytes long.

If you use fgets() instead of "functions like" scanf and gets,
then you have the ability to specify a maximum input size that
will not be exceeded. That gives you a chance to read a block
of input at a time into a fixed-length buffer, then allocate
dynamic memory to hold the contents. You could either create a
linked-list of these dynamic buffers and then at the end create
a single dynamic buffer long enough to hold the end result,
or you could use realloc() as you went along -- simpler logic
but much less efficient.

Naturally, if your system only -has- 512 Mb of available memory,
then you aren't going to be able to deal with the 7.3 exabyte long
input, but at least you will be able to handle the situation
smoothly whereas if you use functions "like" scanf and gets
you would almost certainly crash in the attempt.

Handling input of "any length" is a mugs game -- no matter how
sophisticated your buffering, you are never going to be able to
read "all" of /dev/zero or /dev/random (on Unix systems).
--
Entropy is the logarithm of probability -- Boltzmann


dear Walter,
consider the following program:

#include<stdio.h>
#define SIZE 1
int main()
{
char *array[SIZE];
scanf("%s", array[0]); // type a string of any length whatsoever.
for(int i = 0; *(array[0] + i) != '\0'; i++)
printf("%c", *(array[0] + i));

return 0;
}
when you run this program, you will find that the "printf" outputs the
whole string which you entered through "scanf", no matter how long your
string was.
now suppose you change the constant SIZE to some bigger value, 4, for
example, and then modify the program to this:

#include<stdio.h>
#define SIZE 4

int main()
{
char *array[SIZE] = {"string of any size", "type",
"praetertranssubstantiationalistically", "another string"};

for(int i = 0; i < SIZE; i++){
for(int j = 0; *(array[i] + j) != '\0'; j++){
printf("%c", *(array[i] + j));
}
printf("\n");
}
return 0;
}

then this program will output the strings with which the array has been
initialized exactly.
but if you want that the strings be entered at run time by user, rather
than be given at initialization as above, then how do you do this?
that is, during execution you type your strings one by one and they get
stored exactly as in the above program.

any ideas?

-arko

Nov 14 '05 #6
ar******@gmail.com wrote:
Walter Roberson wrote:
In article <11**********************@g47g2000cwa.googlegroups .com>,
<ar******@gmail.com> wrote:
my problem is: given the declaration
char *array[SIZE];
how to store strings of any length into this array from the user
input
using functions like "scanf", "gets" etc. ?


You don't. Functions "like" scanf() and gets() are functions
that may return strings of indefinite length into the user buffer
which is *assumed* to be "big enough". Clearly any assumption of
"big enough" is going to be violated in the face of your
requirement to be able to store strings of "any length" -- if
the user provided a 7.2 exabyte long buffer, the program would
fail the first time the input was 7.3 exabytes long.

If you use fgets() instead of "functions like" scanf and gets,
then you have the ability to specify a maximum input size that
will not be exceeded. That gives you a chance to read a block
of input at a time into a fixed-length buffer, then allocate
dynamic memory to hold the contents. You could either create a
linked-list of these dynamic buffers and then at the end create
a single dynamic buffer long enough to hold the end result,
or you could use realloc() as you went along -- simpler logic
but much less efficient.

Naturally, if your system only -has- 512 Mb of available memory,
then you aren't going to be able to deal with the 7.3 exabyte long
input, but at least you will be able to handle the situation
smoothly whereas if you use functions "like" scanf and gets
you would almost certainly crash in the attempt.

Handling input of "any length" is a mugs game -- no matter how
sophisticated your buffering, you are never going to be able to
read "all" of /dev/zero or /dev/random (on Unix systems).
--
Entropy is the logarithm of probability -- Boltzmann

dear Walter,
consider the following program:

#include<stdio.h>
#define SIZE 1
int main()
{
char *array[SIZE];
scanf("%s", array[0]); // type a string of any length whatsoever.


Undefined behavior -- array[0] is an uninitialized pointer. In this case
it just *happened* to *seem* to work. Basically, you got unlucky. for(int i = 0; *(array[0] + i) != '\0'; i++) printf("%c", *(array[0] + i));

return 0;
}
when you run this program, you will find that the "printf" outputs the
whole string which you entered through "scanf", no matter how long your
string was.
Dumb luck (or lack of same).
now suppose you change the constant SIZE to some bigger value, 4, for
example, and then modify the program to this:

#include<stdio.h>
#define SIZE 4

int main()
{
char *array[SIZE] = {"string of any size", "type",
"praetertranssubstantiationalistically", "another string"};

for(int i = 0; i < SIZE; i++){
for(int j = 0; *(array[i] + j) != '\0'; j++){
printf("%c", *(array[i] + j));
}
printf("\n");
}
return 0;
}

then this program will output the strings with which the array has been
initialized exactly.
but if you want that the strings be entered at run time by user, rather
than be given at initialization as above, then how do you do this?
that is, during execution you type your strings one by one and they get
stored exactly as in the above program.

any ideas?


Sure. See the following for a thorough discussion of the subject:

http://users.powernet.co.uk/eton/c/fgetdata.html

HTH,
--ag

--
Artie Gold -- Austin, Texas
http://it-matters.blogspot.com (new post 12/5)
http://www.cafepress.com/goldsays
Nov 14 '05 #7

<ar******@gmail.com> wrote
char *array[SIZE];
how to store strings of any length into this array from the user input
using functions like "scanf", "gets" etc. ?

char *array[SIZE];
char buff[1024];

for(i=0;i<SIZE;i++)
{
fgets(buff, 1024, stdin);
ptr = strchr(buff, '\n');
/* this is absolutely vital. fgets() is no improvement whatsoever over
gets() unless
you handle buffer overflow correctly. Wrong results are often worse than a
crash which is the most likely result of gets() being fed an over-long
line. */
if(ptr == 0)
{
printf("Your line was over 1024 characters long. I will have to look
up realloc"
"and do a bit more work to solve this problem. For now let's quit\n");
exit(EXIT_FAILURE);
}
*ptr = 0;
array[i] = mystrdup(buff);
if(!array[i])
{
printf("Out of memory\n");
exit(EXIT_FAILURE);
}
}

char *mystrdup(const char *str)
{
char *answer = malloc(strlen(str) + 1);
if(answer)
strcpy(answer, str);
return answer;
}
Nov 14 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Jeff | last post by:
Hello everybody, I'm kind of new to C programming, but here's a little question. Usually, when you have an array of chars, you put a \0 at the end of it to terminate the string. That way, it is...
11
by: Walter Dnes (delete the 'z' to get my real address | last post by:
I've noticed a few threads (full of sound and fury, signifying nothing) here recently about allocation of large memory blocks. I'm about to start on a personal pet project where I'll be using...
9
by: dati_remo | last post by:
Hi, is it possible to find the dimension of an array using a pointer? main() { int a; f(a); return; }
29
by: shmartonak | last post by:
For maximum portability what should the type of an array index be? Can any integer type be used safely? Or should I only use an unsigned type? Or what? If I'm using pointers to access array...
12
by: arkobose | last post by:
my earlier post titled: "How to input strings of any lengths into arrays of type: char *array ?" seems to have created a confusion. therefore i paraphrase my problem below. consider the...
2
by: vikas | last post by:
I have following structure in c++. typedef struct MMF_result_struct { int action; char text; int cols,rows; int month,day,year; } MMF_result; Now this structure is shared between C++ and C#...
2
by: Potiuper | last post by:
Question: Is it possible to use a char pointer array ( char *<name> ) to read an array of strings from a file in C? Given: code is written in ANSI C; I know the exact nature of the strings to be...
13
by: Superman859 | last post by:
Hello everyone. Heads up - c++ syntax is killing me. I do quite well in creating a Java program with very few syntax errors, but I get them all over the place in c++. The smallest little things...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.