2

Possible Duplicate:
Dynamic array using ANSI C

I am trying to fill an array with the values that the user is typing. However, I do not know in advance how many values will my array have, or how many values the user will type in. The user types in a value at a time, the value is stored in the array, and then the user is again prompted to type in another value, and so forth, until he types in a negative number. When the user types in a negative number, the program prints out all the positive values that the user has entered so far (NOT the negative one, as it is essentially only used for termination of the program).

My problem is:

1) how to declare the array without knowing in advance how big it will be?

2) how to scan for the user input? For example, I am thinking something like this for scanning the input and assigning the values to the array (this is just a part of the code, not all of it, I just want to know if this part of the code will work when I have completed the program):

...

int working = 0;
int i = 0;
do
{          
printf("Enter a positive value \n");
scanf("%d",&x);
if (x >= 0)
{
 &array[i] = x;
 i++;
}
else
{
 printf("You have entered a negative number \n");
 working = 1;
}
} while (working = 0);

Is this code correct (of course, it is not a complete program)? Also, how do I declare the array, without knowing how big it will be (I have no way of knowing in advance how many positive values the user will type in before he types in a negative one)

3
  • I think you need to provide a pre-allocated array and then realloc in blocks (say 200 elements) when input data exceed it's size. Commented Dec 20, 2012 at 9:43
  • See this: stackoverflow.com/a/8338488/991445 Commented Dec 20, 2012 at 9:43
  • Thanks @BigMike and the rest - this link about malloc/realloc seems interesting, I didn't know about it (I am just starting to learn about C). Also, what do you think about my code? Will it work? Commented Dec 20, 2012 at 9:53

5 Answers 5

3

You can allocate an initial array for user input and save it's size into a variable so then you can reallocate the array when it's full. Or you could use linked list to save input, so later you could calculate needed element count and allocate the array.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for mallocing then reallocing the array
2
int arraySize = 256; // Or whatever
int *array = malloc(arraySize * sizeof(int));
if (!array)
{
    fprintf(stderr, "Master, please buy more RAM, I can't allocate memory\n");
    return;
}

int numberOfElements = 0;
for(;;)
{          
    printf("Enter a positive value:\n");
    scanf("%d",&x);

    if (x >= 0)
    {
        if (numberOfElements == arraySize)
        {
            arraySize *= 2; // Or whatever strategy you need
            array = realloc(array, arraySize * sizeof(int));
            if (!array)
            {
                fprintf(stderr, "Master, please buy more RAM, I can't allocate memory\n");
                break;
            }
        }
        array[numberOfElements++] = x;
    }
    else
    {
        printf("You have entered a negative number \n");
        break;
    }
}

Something like. Sorry for the possible mistakes, don't check it.

4 Comments

What does the if (!array) statement do? I have never seen it before
You can think of it like if (array == 0) or if (array == NULL) if you prefer. It checks whether we can allocate memory, because if not then malloc/realloc returns 0 (or NULL if you want).
OK, thanks! What do you think of my code BTW - will it work? I used a "while-do" statement
Looks like working (can't check right now). for(;;) just looks prettier and clearer for me. Choose the one you like.
1

Better use linked list, array won't help you here.

Check this out if you are not familiar with it - http://cslibrary.stanford.edu/103/LinkedListBasics.pdf

Comments

1
   int dataarray [2];
   int no;
   int count =0;

   while(1)
   {
        printf("Enter No's = ");
        scanf("%d",&no);
        if(no<0)
             break;
       *(dataarray+count)=no;
       count++;
   }

you can use the count further to know how many elements in array.

you can get elements from this array by pointers link

no = *(dataarray+count)

Comments

1

You can use a linked list structure for that. There can be many possible implementations (simple linkedlist, double linkedlist ,etc) if you google you can find many pages about this. Here is an example (not necessarily the most optimized form, but just to give you an idea)

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

struct datalist
{
    int value;
    struct datalist *next;
};
typedef struct datalist *linkedList;


void addToList(linkedList *param_valueList, const int param_newValue)
{
    if (*param_valueList == NULL)
    {
        linkedList newItem = (linkedList)malloc(sizeof(struct datalist));
        newItem->value = param_newValue;
        newItem->next = NULL;
        *param_valueList = (linkedList)malloc(sizeof(linkedList));
        *param_valueList = newItem;
    }
    else
    {
        linkedList newList = (linkedList)malloc(sizeof(struct datalist));
        newList->value = param_newValue;
        newList->next = NULL;

        linkedList tmpList = *param_valueList;
        while (tmpList->next != NULL)
            tmpList = tmpList->next;
        linkedList *listPtr = &tmpList;
        (*listPtr)->next =  newList;
   }
}


void printList(const linkedList param_valueList)
{
    linkedList tmpList = param_valueList;
    while (tmpList != NULL)
    {
        printf("%d\n", tmpList->value);
        tmpList = tmpList->next;
    }
 }


int main(int argc, char *argv[])
{
    int inputNmbr = 0;
    linkedList numberList = NULL;
    while (1)
    {
        printf("print a number: ");
        scanf("%d", &inputNmbr);
        if (inputNmbr > 0)
            addToList(&numberList, inputNmbr);
        else
            break;
    }

    printf("Here are the numbers you entered:\n");
    printList(numberList);

    return 0;
}

Regards,

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.