weird thing about arrays

+1 Compodulator Compodulator · January 17, 2015

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <string.h>

main()
{
    char pass[5];

    printf("Welcome to the registration procedure. \n");
    printf("Password requirements: One uppercase,\n one digit,\n one special character,\n up to 30 characters\n");
    scanf(" %s", pass);
    printf(" %s", pass);
    return 0;
}


I've gone reasonably far into the C tutorial and am trying to do the first challenge. I've decided to try and also limit the user's size of password because that's what websites often do.
However, here comes my first issue. Despite the array's size being 6 bits long, it still accepts all lengths of string i feed into it and does not trim them.
Question is then asked: why preassign a size to an array if C takes more space when it feels like doing so?

Post a Reply

Replies

Oldest  Newest  Rating
0 c student · January 17, 2015
you might also want to look up on how strings work in c.  it will explain a bit on what happened with the random characters at the end.  as for the array overflow, you might want to look under the hood of programs and see what is happening inside memory when you give inputs and receive outputs. it'll expand your knowledge and give you a much clearer image of what you are doing.
0 Compodulator Compodulator · January 17, 2015
ok, so i got a bit confused on the sizing bit. fine. i forgot that part.
still, if i enter, say 1234567890
it does output 1234567890 and not 12345 as it should, to my understanding.

edit: further playing around revealed that if the array is preset with something that is bigger then 5 elements, then yes, it's being trimmed.
However, if scanf() is being used the string is not being trimmed.
Also, when the element is present, instead of being trimmed nicely, what I get is "( (" at the end of the string.
  • 1

C

106,953 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator