Thread: weird two dimensional array

  1. #1
    and the hat of copycat stevesmithx's Avatar
    Join Date
    Sep 2007
    Posts
    587

    weird two dimensional array

    Hi guys,

    I am very new to C.I simply cannot understand how the following code works.

    Code:
    #include <stdio.h>
    #include <conio.h>
    #include <string.h>
    int map(char c);
    void main(){
    char link[8][15]={"AB5C2D3","BA5C4E3","CA2B4E4","DA3","EB3C4"};
    int adj[4][4],i,j,m,n;
    printf("%s\n",link[0]);
    printf("%s\n",link[1]);
    printf("%s\n",link[2]);
    printf("%s\n",link[3]);
    printf("%s\n",link[4]);
    
    for(i=0;i<5;i++){
    for(j=0;j<5;j++){
    adj[i][j]=0;
    }
    }
    
    printf("After\n");
    printf("%s\n",link[0]);
    printf("%s\n",link[1]);
    printf("%s\n",link[2]);
    printf("%s\n",link[3]);
    printf("%s\n",link[4]);
    }
    I get the output as
    AB5C2D3
    BA5C4E3
    CA2B4E4
    DA3
    EB3C4
    After
    BA5C4E3
    CA2B4E4
    DA3
    EB3C4
    Can somebody pl explain wat happens to link[0] after the initialization to the array adj[][].
    Thanks in advance.

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    the initialization of adj has a buffer overrun, overwriting memory, presumably link[0].

    actually, that would just result in a blank line, but it's undefined behavior, so it doesn't really matter.
    Last edited by robwhit; 09-18-2007 at 07:48 PM.

  3. #3
    and the hat of copycat stevesmithx's Avatar
    Join Date
    Sep 2007
    Posts
    587

    Suggestions for changing

    Thank you robwhit.
    Wat can I do to avoid this buffer overrun.
    That is to retain the value of link[0].
    Last edited by stevesmithx; 09-18-2007 at 07:51 PM.

  4. #4
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    Code:
    for(i=0;i<4;i++){
        for(j=0;j<4;j++){
            adj[i][j]=0;
        }
    }
    http://faq.cprogramming.com/cgi-bin/...&id=1043284376
    Last edited by robwhit; 09-18-2007 at 07:55 PM.

  5. #5
    and the hat of copycat stevesmithx's Avatar
    Join Date
    Sep 2007
    Posts
    587
    Thanks once again robwhit.
    It worked.
    This one almost drove me crazy.
    Thank u very much.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How To pass 2 dimensional array of strings to a function
    By chottachatri in forum C Programming
    Replies: 15
    Last Post: 01-25-2008, 02:20 PM
  2. Replies: 1
    Last Post: 04-25-2006, 12:14 AM
  3. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  4. Merge sort please
    By vasanth in forum C Programming
    Replies: 2
    Last Post: 11-09-2003, 12:09 PM
  5. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM