0

The function getStringEnd() doesn't work correctly but I don't know why. The function does not return the correct value of the string end. I already found out that the variable max is not calculated right.

But int max = sizeof str / sizeof (char); should work, shouldn't it?

Do you have any ideas?

#include <stdio.h>
#define MAX_FIGURES 30  

int getStringEnd(const char * str);

int getStringEnd(const char * str)
{
    int max = sizeof str / sizeof (char);

    int counter = 0;
    while (counter <= max -1)
    {
        if ((str[counter] == '\0') || (str[counter] == '\n')) return counter;
        counter += 1;
    }
    return 0;
}

int main(void)
{
    char figures[MAX_FIGURES];
    for (int i = 0; i <= MAX_FIGURES - 1; i++) figures[i] = '\0';

    fgets(figures, MAX_FIGURES, stdin);

    int stringEnd = getStringEnd(&figures);
}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Domi
  • 9
  • 1
  • 3
  • Please find the answer to this question in any C FAQ, such as [this](http://c-faq.com/aryptr/aryparmsize.html). – Lundin Apr 16 '15 at 11:27

1 Answers1

6

In getStringEnd() function, str is a const char *, nothing else. sizeof operator gives back the size of the datatype, not the amount of memory pointed by the variable.

You need to use strlen() to get the length of the string. You need to write something like

int max = strlen(str); // sizeof(char) == 1, fixed, can be ommitted

Note: FWIW, Remember, strlen() does not take into account the terminating null.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • That fixes the problem. I just wonder why my code do not work, I have a book of C programming and the author used the code `sizeof array / array[0]` to get the elements of a array. I not understand what the real problem of my program is. – Domi Apr 16 '15 at 11:24
  • @Domi it is possible when `array` if of type `[n]`. In case of a pointer, sizeof won't work as you might expect. – Sourav Ghosh Apr 16 '15 at 11:30