views:

127

answers:

3

This is part of an assignment so please dont post solutions, just point me in the right direction if possible?

I am passing a pointer to a char array to my method, as well as a value for the actual height of the char array. I am looping through to see if all values are 0, if they are then return 0, esle return one

The method is used as a test to see if i should free memory or not and set the pointer to null if it is full of 0's. The issue i am having is that the programme should have "some unfree" memory at the end, so i have no idea whether or not its doing it correctly - and gdb i struggle with immensley.

Thanks for reading

int shouldBeNull(char *charPointer, int sizeOfCharArray)
{
    int isIn = 0;
    int i = 0;

    while(i < sizeOfCharArray){
        if(*charPointer != '0'){
            isIn = 1;
            break;
        }
        i++;
        charPointer++;
    }   
    return isIn;     
}
+4  A: 

You are not incrementing charPointer

Adil
i am, at the end?
sbsp
@sbsp : Your original version didn't show that. The edited version now shows that correctly.
Scott Smith
+5  A: 

When you say "...all values are zero...", I was assuming that you meant binary values of zero, rather than the character '0'...

if(*charPointer != '0'){

This is the character zero (0x31) rather than a null character (0x00). If you were trying to check for zero bytes, try the following:

if (*charPointer != '\0') {

Also, you're not incrementing or offsetting your character pointer charPointer, so you're always testing the first character.

if (*charPointer++ != '\0) {

...or...

if (*(charPointer + i) != '\0) {
Scott Smith
Or just `if (*charPointer)` or `if (*charPointer != 0)`
Gabe
so if i am checking for the charachter 0 then my way was correct?also, i am incrementing the pointer at the end?
sbsp
@sbsp : yes, your code was checking for the zero digit character correctly, with the possible exception that it doesn't account for a terminating null character (0x00) at the end of the string - assuming that your buffer points to a null-terminated string...
Scott Smith
+1  A: 
  • You're not returning 1 if not all the values are 0
  • Instead of setting isIn and breaking out of the loop, you can just return 1 from the condition
Eli Bendersky