Thread: 2D array and pointer( crash exe)

  1. #1
    Registered User
    Join Date
    Jul 2011
    Location
    Pune, Maharashtra, India
    Posts
    33

    2D array and pointer( crash exe)

    Code:
    //implement 2D array& pointer,crash in execute time not complete insert elements
    #include<stdio.h>
    #include<conio.h>
    #include<malloc.h>
    void main ()
    {
                  int i,j,n,r,c;
                  int **p;
                  printf("enter the row and column of matrix:\n");
                  scanf("%d %d",&r,&c);
                  p=(int**)malloc(r*sizeof(int));
                  p=(int**)malloc(c*sizeof(int));
                  printf("enter the elements\n");
            
                   for(i=0;i<r;i++)
                      {
                          for(j=0;j<c;j++)
                              {
                                   scanf("%d",&p[i][j]);//crash section
                                  }
                                      }
                     for(i=0;i<r;i++)
                     {
    	             for(j=0;j<c;j++)
    	               {
    	                 printf("\t%d",p[i][j]);
                                   }              
                                    }
             getch();
    }

  2. #2
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    You are not correctly allocating your 2d pointer. Why are you trying to implement this anyway? Look the easiest way to do this in one shot is to use malloc(row*column*sizeof(int)). Additionally, this is C not C++. You do not need to cast the return of malloc, read about it here.

    You are using a very old programming style. For this program you should be using stdio.h and stdlib.h I suggest you read some tutorials.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  3. #3
    Registered User
    Join Date
    Apr 2010
    Posts
    88
    My guess is you're trying to allocate a 2d array so that you can access it using: array[i][j] ?

    If you want to do this you can try the following:

    Code:
    Ex) 
     
      int i, j;
      int rows = 7;
      int columns = 7;
      int ** array = NULL;
    
      array = malloc( rows * sizeof( int *) );
    
      if( array != NULL){
        for(i=0; i< rows; i++){
          array[i] = malloc( columns * sizeof( int ) );
        }
      }
      else{
        printf("Array couldn't be allocated.");
      }
    First, you declare array, a pointer capable of pointing to an int pointer. Then you malloc such that array points to rows int pointers. Using the for loop, each of these int pointers points to columns integers.

    Note that the first malloc call uses sizeof(int * ) and the subsequent calls use sizeof( int ).

    It's more code to set it up this way, but you can access elements via array[i][j] if that's what you want. It need not be a square array for this to work, meaning rows need not equal columns as it does in the example.

    You might find the graphic here useful:

    http://c-faq.com/~scs/cclass/int/sx9b.html

    If you do use the double pointer method, make sure you follow the instructions for free() at the above link. If you do it wrong, you'll lose reference to memory that is not actually freed.

    Also, as AH said this can be done with a 1D array, and accessing the "i,j th" entry using a single index is a simple relationship. Though sometimes, it is nice to be able to access elements using i,j notation as we would in linear algebra.
    Last edited by Ocifer; 08-01-2011 at 12:22 AM.

  4. #4
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    1. You first malloc call needs to be of int* not int. Additionally the way you are describing is overly complicated since each column would have to be freed individually to prevent a memory leak. The only reason to implement it this way is if you do not know the size until runtime. However for this case it is better to simply make an extremely large array that is capable of holding whatever you may need, e.g. max case scenario.

    2. You can access any array via array[i][j] by one malloc call malloc(rows*columns*sizeof(int)) as I stated above. This has the advantage of only requiring one free call.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  5. #5
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by AndrewHunter View Post
    1. You first malloc call needs to be of int* not int. Additionally the way you are describing is overly complicated since each column would have to be freed individually to prevent a memory leak. The only reason to implement it this way is if you do not know the size until runtime. However for this case it is better to simply make an extremely large array that is capable of holding whatever you may need, e.g. max case scenario.

    2. You can access any array via array[i][j] by one malloc call malloc(rows*columns*sizeof(int)) as I stated above. This has the advantage of only requiring one free call.
    Careful: If you only do one malloc, you only get one set of [brackets]. [NOTE for the pedantic: it is possible to get two sets of brackets out of one malloc call, but the row lengths have to be the same and known at compile time.] In that case you have to array[i*n+j] instead.

  6. #6
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Thank you for expanding on that tabstop.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  7. #7
    Registered User
    Join Date
    Apr 2010
    Posts
    88
    Quote Originally Posted by AndrewHunter View Post
    2. You can access any array via array[i][j] by one malloc call malloc(rows*columns*sizeof(int)) as I stated above. This has the advantage of only requiring one free call.
    I'm with you on the free() advantages, but I just want to clarify one thing. Maybe i'm misunderstanding you, but when I use the declaration

    Code:
    int * ptrArray = malloc( 3 * 3 * sizeof( int) );
    any attempt to reference its contents by ptrArray[][] (that is using two separate indices) results in a compilation error. Of course one could use ptrArray[rows*i + j]. Is this what you meant?

    EDIT: I guess maybe tabstop can help clarify

    Tabstop , when you wrote

    [NOTE for the pedantic: it is possible to get two sets of brackets out of one malloc call, but the row lengths have to be the same and known at compile time.]
    Do you mean that columns = rows, or that each row must be of the same length ( ie not a jagged array)? Do you perhaps have a code snippet using only one malloc call followed by array[i][j] use?
    Last edited by Ocifer; 08-01-2011 at 03:02 PM.

  8. #8
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    I mean that the row lengths have to be the same (i.e. not jagged) and they have to be known at compile time, which may be more than is possible. If you do know the row lengths, then it looks like
    Code:
    #include <stdio.h>
    
    typedef int row[20]; /*however many you need in the row -- must be a real number*/
    
    int main(void) {
        int cols;
        scanf("%d", &cols);
        row* bob = malloc(cols * sizeof(*bob));
        /* You can now access elements of bob like bob[6][14] or whatever. */
        bob[6][14] = 3;
        return 0;
    }
    (ETA: Yes I like C99. Deal.)

  9. #9
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    I misspoke and tabstop was pointing that out. You are correct on the way to access the array. The topic is explained quite clearly in C-FAQ 6.16
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Graceful Crash on Bad Pointer
    By leeor_net in forum C++ Programming
    Replies: 55
    Last Post: 03-19-2009, 01:30 PM
  2. Replies: 1
    Last Post: 03-24-2008, 10:16 AM
  3. Why this (dynamic array) doesn't crash ?
    By soothsayer in forum C Programming
    Replies: 13
    Last Post: 01-26-2006, 10:01 PM
  4. Dynamic array sizing causes crash
    By Mithoric in forum C++ Programming
    Replies: 3
    Last Post: 12-30-2003, 07:46 AM
  5. Filling a 2d Array cause program to crash
    By Geo-Fry in forum C++ Programming
    Replies: 2
    Last Post: 05-22-2003, 07:00 AM

Tags for this Thread