Basic array segmentation fault

This is a discussion on Basic array segmentation fault within the C++ Programming forums, part of the General Programming Boards category; Hi, I'm having a problem with entering numbers into an array and then printing them out again. I'm pretty new ...

  1. #1
    Registered User
    Join Date
    Nov 2007
    Posts
    2

    Question Basic array segmentation fault

    Hi,

    I'm having a problem with entering numbers into an array and then printing them out again. I'm pretty new to programming which is probably what the problem is...

    So far, I have the following:

    Code:
    #include<stdio.h>
    
    int main(){
    
    int array[10];
    int i;
    
    for (i = 0;i <= 10;i++)
    
            {
            printf("\nEnter a number:");
            scanf("%d", array[i]);
            }
    
    for (i = 0;i <= 10;i++)
    
            {
            printf("\nArray %d: %d", i, array[i]);
            }
    }

    When I compile and run the program, it asks me to enter a number. I enter the number and then it says 'Segmentation fault' and closes.

    Could anyone please advise on where I'm going wrong with this?


    Many thanks

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Code:
    for (i = 0;i <= 10;i++)
    
            {
            printf("\nEnter a number:");
            scanf("%d", &array[i]);
    Your loop runs to 10, but you onlyhave a 0..9 array [ten elements]. Remove the equal sign.

    You need to pass the address of the data you are filling in with scanf, so you need an "&" in front of your variable.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Nov 2007
    Posts
    2
    I can't believe I missed the &...

    Thank you!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Segmentation fault (pointer to an array)
    By Lang in forum C Programming
    Replies: 4
    Last Post: 04-08-2008, 01:22 AM
  2. Segmentation fault with array?
    By whiphub in forum C++ Programming
    Replies: 1
    Last Post: 09-12-2004, 02:51 PM
  3. strcat segmentation fault
    By captain-cat in forum C Programming
    Replies: 3
    Last Post: 07-20-2004, 11:29 AM
  4. Replies: 3
    Last Post: 04-19-2004, 07:42 PM
  5. Segmentation Fault printing an array of structs
    By ccoder01 in forum C Programming
    Replies: 1
    Last Post: 04-17-2004, 08:03 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21