3d array allocation

This is a discussion on 3d array allocation within the C Programming forums, part of the General Programming Boards category; Tested it. Seems to work fine. Just looking at the net I get more complicated results on how to allocate ...

  1. #16
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Tested it. Seems to work fine. Just looking at the net I get more complicated results on how to allocate a 3D array. So why not just use a single line??

  2. #17
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,437
    It only works if all the minor dimensions are compile time constants, and thus the compiler can work out the size from the declaration of the pointer.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #18
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Why? This works fine:
    Code:
    #include <stdlib.h>
    #include <stdio.h>
    
    int main()
    {
    	int x,y,z; 
    	int t;
    	int maxx, maxy, maxz;
    	scanf("%d %d %d", &maxx, &maxy, &maxz);
    	int (*p)[maxy][maxx] = malloc(maxz * sizeof(*p));
    	for (x=0; x<maxx; ++x)
    		for (y=0; y<maxy; ++y)
    			for (z=0; z<maxz; ++z)
    				t = p[x][y][z];
    }
    When I put a large number for maxx, maxxy it crushes though. But it seems to allocate a 3D array with maxx, maxy, maxz not being at constant-time valued.

  4. #19
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    You know Ptolemy's model of planet paths worked to accurately map where celestial bodies should be. Though completely wrong, it did work just fine too.

Page 2 of 2 FirstFirst 12
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dynamic allocation for array of pointers to char
    By bivhitscar in forum C Programming
    Replies: 7
    Last Post: 05-20-2006, 07:04 AM
  2. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  3. Merge sort please
    By vasanth in forum C Programming
    Replies: 2
    Last Post: 11-09-2003, 11:09 AM
  4. 3D array
    By GSLR in forum C Programming
    Replies: 2
    Last Post: 05-12-2002, 04:00 PM
  5. 3D Array
    By Alextrons in forum Windows Programming
    Replies: 4
    Last Post: 01-11-2002, 12:39 AM

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