Thread: pointer manipulating 2-dimensional array

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    20

    Unhappy pointer manipulating 2-dimensional array

    Hi.
    I'm beginner with C and I'm having problem with the following source code:

    Code:
    /*****************************************************************************************************/
    main()
    {
       
       unsigned int lin=10;
       unsigned int col=5;
       unsigned int i,j;
       double *grid;
       double x;
       grid=malloc(col*lin*sizeof(double));
       if(!grid)
       {
          printf("Err\n");
          exit(1);
       }
       for(i=0;i<lin;i++)
       {
          for(j=0;j<col;j++)
          {
             x=pow(i+j,2);
             *(grid+(i*col+j)*sizeof(double))=x;
          }
       }
       for(i=0;i<lin;i++)
       {
          for(j=0;j<col;j++)
          {
             printf("%10.7f\t",*(grid+(i*col+j)*sizeof(double)));
          }
       printf("\n");
       }
    
    /*****************************************************************************************************/
    It works nice for smaller lin and col but returns "segmentation fault" if them becomes lage.
    I'm using gcc 4.2 with linux kernel 2.6.22.

    Thanks.

    PS I'm beginner in english language as well... :P

  2. #2
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    Location
    On me hyperplane
    Posts
    1,218
    when you increment a double pointer you dont need to tell it how many bytes to increment by, thats done automatically.

    Here:
    Code:
      for(i=0;i<lin;i++)
       {
          for(j=0;j<col;j++)
          {
             x=pow(i+j,2);
             *(grid+(i*col+j)*sizeof(double))=x;
          }
       }
    You could do something like:
    Code:
    double *p;
    for(i=0;i<lin;i++)
       {
          for(j=0;j<col;j++)
          {
             x=pow(i+j,2);
             *p=x;
             p++;
          }
       }
    That should work and would also save some extra calculations. You generally only want to use sizeof() when allocating space.

    [edit] or doing it your way just change the pointer bit to:
    Code:
    *grid+(i*col+j)=x;
    [/edit]

  3. #3
    Registered User
    Join Date
    Jan 2008
    Posts
    20
    Thanks mike_g.
    That helped me alot!!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 05-15-2009, 08:38 AM
  2. Why does C need pointer conversion
    By password636 in forum C Programming
    Replies: 2
    Last Post: 04-10-2009, 07:33 AM
  3. Two dimensional array
    By George2 in forum C Programming
    Replies: 3
    Last Post: 11-10-2007, 05:27 AM
  4. Direct3D problem
    By cboard_member in forum Game Programming
    Replies: 10
    Last Post: 04-09-2006, 03:36 AM
  5. pointer to multidimensional array
    By Bigbio2002 in forum C++ Programming
    Replies: 4
    Last Post: 02-05-2006, 10:29 PM