Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

char arrays in C

Name: Anonymous 2012-09-12 20:46

So, I'm trying to learn C, and currently I'm testing out characters and character arrays. I've put together this code:


#include <stdio.h>
int main()
{
    char hello[7];
    int a, b;
   
    puts("Enter to start:\n");
    getchar();
    fflush(stdin);
   
    puts("Intiated:");

    for(a = 0; a <= 7; ++a){
          hello[a] = getchar();
      }
      fflush(stdin);
     
      for(a = 0; a <= 7; ++a){
            putchar(hello[a]);
            }
           
            fflush(stdin);
            getchar();
            return(0);
}


And it works well (or as well as it is suppose to), but if I change the char array hello's size to something smaller than 7, or change the 7 in both the 'for' parts, than I'll capture more than the number the char array was set to.

So, for example:


#include <stdio.h>
int main()
{
    char hello[3];
    int a, b;
   
    puts("Enter to start:\n");
    getchar();
    fflush(stdin);
   
    puts("Intiated:");

    for(a = 0; a <= 9; ++a){
          hello[a] = getchar();
      }
      fflush(stdin);
     
      for(a = 0; a <= 9; ++a){
            putchar(hello[a]);
            }
           
            fflush(stdin);
            getchar();
            return(0);
}


This will capture 9 characters, even though 'hello' is set to 3. Frankly, I don't mind this. It's better than an overflow or some other error. But what exactly happens? Does it just change the amount of characters the array can hold?

Name: twkm.freeshell.org/c.html 2012-09-12 20:56

>>1
kid, you are gonna get raped.

Is it not /prog/help/, this is dis[/cussion]/4chan.org/[about]prog[/ramming]

Go get a teacher/professor to help you with your code homework.

Also, there are other boards, and IRC channels for this. Do not spam this thread with jimmy code.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List