add to array 
Author Message
 add to array

I am trying to start off with an array with nothing in it and I want to add
strings of chracters and it is not working:
but if I just make it so
char *array[]={"ab","cab","dsfsad"}; it works fine, so how do I make it so I
start our tithw *array[]={} and have the user enter those values???

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//sort the array
void sort(char *array[], int size)
{
  char *temp;
  int i, j;

  for (i=0;i<size;i++)
    for(j=0;j<size;j++)
      if (strcmp(array[i],array[j])<0)
 {
   temp=array[i];
   array[i]=array[j];
   array[j]=temp;
 }

Quote:
}

main()
{
  //variable declaration
  int i=0;
  int num=0;
  char *array[]={};

  printf("Please enter a string to be sorted: ");
  while(array[i]!="\n")
    {
      scanf("%s",array[i]);
      printf("%s",array[i]);
      i++;
    }

  num=sizeof(*array)-1;

  //sort function call
  sort(array,num);
  i=num-1;

  //print out array in alphabetical order
  for (i=0;i<num;i++)
    {
      printf("%s ",array[i]);
    }

Quote:
}



Sat, 12 Feb 2005 09:30:21 GMT  
 add to array

Quote:
>I am trying to start off with an array with nothing in it

An array doesn't have "nothing in it".  An array has some number
of elements with some data type, and unless you're using realloc(),
that size doesn't change once the array is created.  You can have
char * elements with values of NULL, or long elements with values
of -42, but that is not equivalent to "nothing".

Quote:
>and I want to add
>strings of chracters and it is not working:
>but if I just make it so
>char *array[]={"ab","cab","dsfsad"}; it works fine, so how do I make it so I
>start our tithw *array[]={} and have the user enter those values???

You could start out with:
        char *array[] = {NULL, NULL, NULL};

Quote:

>#include <stdio.h>
>#include <stdlib.h>
>#include <string.h>

>//sort the array
>void sort(char *array[], int size)
>{
>  char *temp;
>  int i, j;

>  for (i=0;i<size;i++)
>    for(j=0;j<size;j++)
>      if (strcmp(array[i],array[j])<0)

This is going to blow up if array[i] is NULL, so make sure that the
size you pass doesn't include elements you haven't filled in yet.

Quote:
> {
>   temp=array[i];
>   array[i]=array[j];
>   array[j]=temp;
> }
>}

>main()
>{
>  //variable declaration
>  int i=0;
>  int num=0;
>  char *array[]={};

>  printf("Please enter a string to be sorted: ");
>  while(array[i]!="\n")
>    {
>      scanf("%s",array[i]);

You need to allocate some memory to put the string the user is going
to enter, and assign that to array[i] before calling scanf() (fgets()
is preferable).  You also can't grow the array:  if it starts out
with one element, it doesn't get bigger (unless you use realloc,
which requires that it be initially allocated with malloc).

- Show quoted text -

Quote:
>      printf("%s",array[i]);
>      i++;
>    }

>  num=sizeof(*array)-1;

>  //sort function call
>  sort(array,num);
>  i=num-1;

>  //print out array in alphabetical order
>  for (i=0;i<num;i++)
>    {
>      printf("%s ",array[i]);
>    }

>}

                                                Gordon L. Burditt


Sat, 12 Feb 2005 10:11:16 GMT  
 add to array

Quote:

> I am trying to start off with an array with nothing in it and I want to add
> strings of chracters and it is not working:

http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=4...

is a generic resizable container written in C.



Sat, 12 Feb 2005 14:08:06 GMT  
 add to array

Quote:

> I am trying to start off with an array with nothing in it and I want to add
> strings of chracters and it is not working:
> but if I just make it so
> char *array[]={"ab","cab","dsfsad"}; it works fine, so how do I make it so I
> start our tithw *array[]={} and have the user enter those values???

In C (at least in C89), arrays are not resizable.  You must either
declare an array of a fixed size, or declare a pointer and use
malloc() and realloc() to create and extend the buffer.  As it is, you
will need to use malloc() to allocate space for each string you enter.

The reason

    char *array[] = {"ab", "cab", "dsfsad"};

works is that you have supplied enough information in the initializer
for the compiler to properly allocate and initialize the array.  The
reason

    char *array[] = {};

won't work is that the compiler is given no information about the
array size.

If you're going to use an array for this, you must specify a maximum
size when you declare it:

    #define MAXELEMENTS 100 /* for example */
    ...
    char *array[MAXELEMENTS] = {NULL}; /* initializes all array
elements */
                                       /* to a NULL pointer */
    unsigned int curpos = 0;
    unsigned int arrsize = MAXELEMENTS;

If you don't want to be constrained to a fixed upper size, you'll need
to allocate your buffer dynamically with malloc() and extend it with
realloc():

    #include <stdlib.h>

    #define START_SIZE  10
    #define EXTEND_SIZE 5
    char **array = NULL;
    unsigned int arrsize = 0;
    unsigned int curpos  = 0;

To allocate and initialize the buffer:

    /*
    ** Create a buffer to hold START_SIZE pointers to char.
    */
    array = malloc (START_SIZE * sizeof *array);
    if (!array)
    {
        /* handle memory allocation failure */
    }
    else
    {
        int i;
        for (i = 0; i < START_SIZE; i++)
            array[i] = NULL;
        arrsize = START_SIZE;
        curpos = 0;
    }    

To extend the buffer:

    /*
    ** Expand the existing buffer to hold EXTEND_SIZE more pointers to
char
    */
    char **tmp;

    tmp = realloc (array, (arrsize + EXTEND_SIZE) * sizeof *array);
    if (!tmp)
    {
        /* could not extend buffer, handle error */
    }
    else
    {
        int i;

        array = tmp;
        for (i = arrsize; i < arrsize + EXTEND_SIZE; i++)
            array[i] = NULL;

        arrsize += EXTEND_SIZE;
    }

For either method above, when your user enters a string, you will have
to allocate memory for the string and save a pointer to that memory in
the array:

    char inbuf[82]; /* Holds 80 chars + '\n' + 0 terminator */
    ...
    if (curpos == arrsize)
    {
        /*
        ** We've filled up the array.  If you're using the dynamic
buffer,
        ** you would try to extend it here.  If you're using the
static
        ** array, you're stuck and need to tell the user there's no
more
        ** room and exit this operation.
        */
    }

    if (fgets (inbuf, sizeof inbuf, stdin))
    {
        if (strlen (inbuf) > 1)
        {
            /*
            ** If inbuf contains more than just a newline character,
            ** strip the newline and save the buffer to the array
            */
            char *newline = strchr (inbuf, '\n');

            if (newline)
            {
                char *newstr = malloc (strlen (inbuf) + 1);
                if (newstr && curpos < arrsize)
                {
                    strcpy (newstr, inbuf);
                    array[curpos++] = newstr;
                }
                else
                {
                    /* handle memory allocation failure */
                }
            }
            else
            {
                /*
                ** User entered a string longer than our input
                ** buffer, which we aren't set up to handle properly.
                ** Use fgets() to repeatedly read from stdin until
                ** the newline is seen, then print an error message
                ** and ask the user to try again.  Or, of course,
                ** you could do the whole malloc/realloc dance
                ** for this as well.
                */
            }
        }
        else
        {
            /*
            ** User just hit Return, which we interpret as the end of
            ** input
            */
        }
    }
    else
    {
        /*
        ** Some error occurred while reading from stdin
        */
    }

Hopefully that made sense and actually answered your question.



Sat, 12 Feb 2005 22:52:02 GMT  
 add to array

Quote:

>     if (fgets (inbuf, sizeof inbuf, stdin))
>     {
>         if (strlen (inbuf) > 1)
>         {
>             /*
>             ** If inbuf contains more than just a newline character,
>             ** strip the newline and save the buffer to the array
>             */
>             char *newline = strchr (inbuf, '\n');

>             if (newline)
>             {

Crap.  I knew I was forgetting something.  Part of the reason we look
for the newline character is to remove it from the entry string.  So
the line

Quote:
>                 char *newstr = malloc (strlen (inbuf) + 1);

needs to be replaced with

                  char *newstr;

                  *newline = 0; /* removes '\n' from inbuf */
                  newstr = malloc (strlen (inbuf) + 1);

Okay, carry on...



Sun, 13 Feb 2005 02:56:12 GMT  
 add to array
Thanks!!!  I appreciate it.


Sun, 13 Feb 2005 15:46:04 GMT  
 
 [ 6 post ] 

 Relevant Pages 

1. Question about adding an array to existing array.

2. Add to array together

3. Adding one array as element of SafeArray.

4. Adding to array in class, which also has an array.

5. Multiply and Add matrices with 2d array WITHOUT ARRAY INDEXING

6. Why does an array have no ADD method?

7. Adding new elements to array class instance?

8. PROBLEM TO ADD DATA IN AN ARRAY

9. Adding Arrays, anyone?

10. Adding Element To An Array

11. Adding diagonal in multi-array

12. How to add I dynamically resize an array ?

 

 
Powered by phpBB® Forum Software