Thread: Segmentation fault in arrays

  1. #1
    Registered User
    Join Date
    Nov 2018
    Posts
    1

    Question Segmentation fault in arrays

    I'm trying to assign a '?' to each of my character in the matrix.
    Following is my code:

    Code:
    int main() {
    
    char board[3][3];
    
    for (int i = 0; i < 3; i++){
    
    for (int j = 0; i < 3; j++) {
    
    board[i][j] = '?';
    
    }
    
    }
    
    printf("%c\n", board[2][2]);
    
    return 0;
    
    }
    

    The code compiles but when I run it, I get a segmentation fault. Can anyone help me with what's wrong with this code?

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    1,108
    Look very carefully at every single character. Do you see it?
    The best argument against democracy is a five minute conversation with the average voter. - Churchill

  3. #3
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    808
    Quote Originally Posted by john.c View Post
    Look very carefully at every single character. Do you see it?
    Misleading. "every single character" Every data character, or code character?

    Actually:
    Look very carefully at the second for() loop statement! Now do you see it?

  4. #4
    Registered User Kernelpanic's Avatar
    Join Date
    Sep 2018
    Location
    Berlin
    Posts
    105
    Code:
    for (int j = 0; i < 3; j++) 
    Why here "i"?
    I get no a segmentation fault but I see also no output. Your indentation style is not beneficial.
    For "printf" is missing <stdio.h>. Your code with printf:

    Code:
    for (int i = 0; i < 3; i++)
    {
    for (int j = 0; i < 3; j++) 
    {
    board[i][j] = '?';
    printf("%c ", board[i][j]);
    }
    }
    And this is the output now:
    Segmentation fault in arrays-matrixorg2018-11-23_173718-jpg

    And now:

    Code:
    for (int i = 0; i < 3; i++)
    {
    
    for (int j = 0; j < 3; j++) 
    {
    
    board[i][j] = '?';
    printf("%c ", board[i][j]);
    }
    }
    And the output:
    Segmentation fault in arrays-matrixorgneu-jpg

    Ten instead of nine.
    Attached Images Attached Images Segmentation fault in arrays-matrixvip-jpg 

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. In GDB no segmentation fault but while running segmentation fault
    By Tamim Ad Dari in forum C++ Programming
    Replies: 2
    Last Post: 12-10-2013, 11:16 AM
  2. Segmentation Fault!!
    By pbjorkman in forum C Programming
    Replies: 4
    Last Post: 12-07-2011, 11:49 PM
  3. Replies: 4
    Last Post: 10-22-2011, 04:29 AM
  4. another segmentation fault
    By bazzano in forum C Programming
    Replies: 8
    Last Post: 10-01-2005, 10:20 AM
  5. segmentation fault and memory fault
    By Unregistered in forum C Programming
    Replies: 12
    Last Post: 04-02-2002, 11:09 PM

Tags for this Thread