0

I have a question just knowledge and any suggestions to my code would be appreciated. So what I have below is a user enter input and the the plan is to have the string go through a validation method. I was just printing out the size/length to see what Im looking at when I pass my array through the parameter. My questions are why does sizeof() always give me the output of 4, and strlen gives me the number of character + 1 (what is the plus one). Thank You.

#include <stdio.h>
#include <stdbool.h>

bool validate(char *s);

int main()
{
    char *input[15];
    printf("Enter your desired input: ");
    fgets(input, sizeof(input), stdin);
    validate(input);
    return 0;
}

bool validate(char *s)
{
    printf("the size of %s is %d and the length is %d\n\n", s, sizeof(s), strlen(s));
} 
Andrew Ricci
  • 475
  • 5
  • 21
  • 4
    `s` is a pointer, not an array. You're printing the size of a pointer, which is 4 bytes. – Barmar Jan 23 '15 at 03:25
  • BTW, the first argument to `fgets()` should be a `char` array, not a `char*` array. – Barmar Jan 23 '15 at 03:25
  • and the newline character `\n` probably accounts for the +1 in the `strlen` result ;) [`A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.`](http://www.cplusplus.com/reference/cstdio/fgets/) – sled Jan 23 '15 at 03:26
  • Aren't you getting lots of warnings about mismatched types? `validate()` takes `char *`, but you're passing `input`, which is `char **`. – Barmar Jan 23 '15 at 03:26
  • 1
    please tell me that code does not compile – ichramm Jan 23 '15 at 03:27
  • Thank you very much everybody. I have fixed all the issues with it. On a side note, how would one go about printing the array in that method. – Andrew Ricci Jan 23 '15 at 03:35
  • and `validate` should return true or false ;) – sled Jan 23 '15 at 03:35
  • 1
    @AndrewRicci presumably with printf or puts, same as they would in main (also, in C it's called a function, not a method) – user253751 Jan 23 '15 at 05:55

0 Answers0