Thread: Pointers As 2D arrays

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User TieFighter's Avatar
    Join Date
    Feb 2010
    Location
    La Crosse, WI
    Posts
    32

    Pointers As 2D arrays

    So, I wrote some code trying to teach myself how to use pointers as 2D arrays a little better, but I'm confused by the output. It should be really simple code - just trying to make a two dimensional array (first value holds pointers to strings, the second is the array of characters that compose the string), then fill it up with values stating what the array index is within each string. Anyway, code is as follows:

    Code:
    #include <strings.h>
    #include <stdlib.h>
    
    int arraysize = 6;
    char **myArr;
    
    int
    main(int argc, char **argv)
    {
      myArr = (char**)malloc(arraysize);
      int i, j;
      for(i = 0; i < arraysize; i++){
    	myArr[i] = "\n Slotfilled. %d\n", i;
    	printf(myArr[i]);
      }
    
      for(j = 0; j < arraysize; j++){
    	free(myArr[j]);
      }
      free(myArr);
      exit(0);
    }
    and what it printed out in the terminal was:

    Code:
     Slotfilled. 9400308
    
     Slotfilled. 9400308
    
     Slotfilled. 9400308
    
     Slotfilled. 9400308
    
     Slotfilled. 9400308
    
     Slotfilled. 9400308
    Segmentation fault
    So, why isn't it the numbers 0 through 5? int i isn't even a pointer, so it's not a pointer address, right? Why is it giving me a segmentation fault, am I trying to access something outside of the array?

    Also, the values entered into the array change for each time I run it, and is this thing leaking memory?
    Last edited by TieFighter; 03-04-2010 at 06:05 PM. Reason: Adding information (Also)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. pointers to arrays
    By rakeshkool27 in forum C Programming
    Replies: 1
    Last Post: 01-24-2010, 07:28 AM
  2. 2d array of object pointers
    By Potterd64 in forum C++ Programming
    Replies: 17
    Last Post: 07-20-2006, 01:27 PM
  3. Pointers to Multidimensional Arrays
    By kidburla in forum C Programming
    Replies: 10
    Last Post: 10-29-2005, 10:45 PM
  4. returning 2D arrays
    By ... in forum C++ Programming
    Replies: 2
    Last Post: 09-02-2003, 12:28 PM
  5. Initialising 2D and 3D arrays
    By fry in forum C++ Programming
    Replies: 5
    Last Post: 08-01-2002, 04:34 AM