Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Reading NULL from an array in C

Options
  • 23-02-2005 8:53pm
    #1
    Registered Users Posts: 191 ✭✭


    Maybe there's a very simple solution to this but I just can't see it, so hopefully somebody can help me out with the following problem, in C.

    I have a program letting the user input numbers into an array and then perform various operations on these values. Before selecting these options I want to test whether the user has input values or not.

    So my idea was to create an array using malloc, (which I have somehow got into my head does not initialise the array with 0, but rather NULL), and then to test the first element: if it is equal to NULL then the user has not entered anything.

    Does this make sense?! Sorry if it doesn't, I've only just recently done pointers and arrays, and my head is in knots after doing the rest of this project all day... :( Here's some code to explain what I'm trying to achieve, if somebody could tell me how to get this piece of code working it'd explain everything.

    Thanks.
    #include <stdio.h>
    #include <stdlib.h>
    #define SIZE 5
    main()
    {
    	int *array, i;
    
    	array = (int *) malloc(SIZE * sizeof(int));
    
    	if (*(array) == NULL)
    	printf("No values");
    
       for (i=0; i<SIZE; i++)
       {
       	scanf("%d", (array+i));
       }
    }
    


Comments

  • Registered Users Posts: 7,276 ✭✭✭kenmc


    Hmmm. well to start with NULL *is* 0. different names for the same thing though, and NULL is usually used for to indicate pointers, whereas 0 is used to indicate the numerical value of zero.
    Also malloc does not initialise the memory with anything, so you could get what was left over in that memory from the last time it was used. if you use calloc you will get values initialised to 0 i believe.
    Why are you mallocing this array though? you know how long it is at compile time -> you can use a static array. much simpler....


  • Registered Users Posts: 191 ✭✭Trine


    I'm afraid we haven't done static arrays yet, I'm only in first year Computer Science. That's interesting about the compile time though, although compile time isn't an issue here, it's only a very small project.

    Doesn't seem like the idea I had would work then. I was under the impression that each element of the array is filled with some NULL character, and that this could then be used for an if statment; if it was true then the user hasn't entered anything into the array.

    I'll just go about it a different way. Thanks alot for the reply though, much appreciated, saved me alot of time and a few hairs on my head.


  • Registered Users Posts: 14,339 ✭✭✭✭jimmycrackcorm


    Your first problem is a design and structure issue.

    Logically you should declare an array to fill regardless of whether it is initialized or not.

    Then loop to scanf for user inputs until the user does not enter anything indicating no more. scan a string and convert to integer to store in the array. That way an empty string measn the user is finished. Increment a counter for each non empty string to know how many numbers have been entered and don't forget to prevent the count going past the maximum array size.

    Your test on whether the user entered values or not is the counter is > 0.

    You need to think out the steps logically first before writing C.
    Also rmember with pointers what the variable points to - i.e.
    array is a pointer so:
    if (array) == NULL)
    makes sense but *array is an integer so
    if (*(array) == 0)
    stands to reason also.

    Id also advise you to be very verbose in wirting code so that the readability is much improved. e.g. when reading the user inputs, if there are values seta flag called bUserHasInputValues to true. Later on during your check it makes code more readable to write the following:

    if (bUserHasInputValues) rather than if (counter >0 )


  • Registered Users Posts: 191 ✭✭Trine


    Yeah good point about the readability, although that code I included was just something I wrote quickly to try to (badly) demonstrate what I was on about. Point taken though.

    Exactly what we were taught, an array should be filled regardless of whether it is initialized or not, guess I was trying to be too smart for my own good with all that NULL crap. :rolleyes: I've used a much simpler true/false flag approach, with the user not being able to select the other options until it becomes true (when values are entered).

    Thanks for the help.


  • Registered Users Posts: 7,276 ✭✭✭kenmc


    Trine, I find it hard to believe they're teaching you about malloc than before arrays. Anyway. I wasn't taking about the time to compile things, just the time at which you compile things. i.e. when you compile the program you know that there will be 5 elements in the array-> hence you are better off to use a fixed array.... if the user could keep on entering numbers until they got bored and entered a special number (eg -1) to indicate that they were done, then you would be justified in using a malloc'd array.

    This code here works fine for me..
    #include <stdio.h>
    #define SIZE 5
    void main(void)
    {
        int *array, i;
    
        array = (int *) malloc(SIZE * sizeof(int));
        if(array != NULL)
        {
        
            /* clear the array */
            for(i = 0; i < SIZE; i++)
            {
                *(array+i) = 0;
            }
           /* fill the array */ 
           for (i=0; i<SIZE; i++)
           {
               scanf("%d", (array+i));
           }
           /*print the array */
           for (i=0; i<SIZE; i++)
           {
               printf("%d ", *(array+i));
           }
           
           /* must remember to free up the array, else it's a memory leak. */
           free(array);
        }
        else
        {
            printf("Bummer - couldn't allocate the array for some reason\n");
        }
       
    }
    
    however, this also doe the same thing and is much simpler to read/understand esp if you're just beginning.
    #include <stdio.h>
    #define SIZE 5
    main()
    {
       int i, array[SIZE]={0};
     
       for (i=0; i<SIZE; i++)
       {
           scanf("%d", &array[i]);
       }
       
       for (i=0; i<SIZE; i++)
       {
           printf("%d ", array[i]);
       }
    
      /* no need to worry about freeing the array, it's staticly declared and goes away again when you exit the program */
       
    }
    


  • Advertisement
  • Registered Users Posts: 191 ✭✭Trine


    No you're right, we have done static arrays, I thought that was something we hadn't done yet. :p

    I understand both examples you put up there. Alot of people did it the second way, but it's just that recently we did memory allocation with arrays, so I thought I'd include what we'd recently learned.

    You reminded me to include an error message if memory can't be allocated and to free memory at the end though, just in time for the project to be handed up today, so thanks for that... ;)


  • Registered Users Posts: 7,276 ✭✭✭kenmc


    no worries. glad i could help


Advertisement