#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    1
    Rep Power
    0

    Question about pointers


    I'm having some doubts about pointers, the following code:

    Code:
    #include<stdio.h>
    
    #include<stdlib.h>
    
     
    
    int * allocate(unsigned int number_bytes)
    
       {
    
       return (int *)malloc(sizeof(int)*number_bytes);
    
       }
    
     
    
    int main(void)
    
       {
    
        
    
       int (*a)[3]; // A pointer to vector of 3 positions
    
       int n, m;
    
     
    
       a = allocate(2*3);//matrix 2x3
    
        
    
       a[0][0] = 1;
    
       a[0][1] = 2;
    
       a[0][2] = 3;
    
       a[1][0] = 4;
    
       a[1][1] = 5;
    
       a[1][2] = 6;
    
        
    
       printf("The value a[0][0] is %d\n", a[0][0]);
    
       printf("The value a[0][1] is %d\n", a[0][1]);
    
       printf("The value a[0][2] is %d\n", a[0][2]);
    
       printf("The value a[1][0] is %d\n", a[1][0]);
    
       printf("The value a[1][1] is %d\n", a[1][1]);
    
       printf("The value a[1][2] is %d\n", a[1][2]);
    
        
    
        
    
       char (*words)[4] = {"dog", "cat" "fish", "rabbit", "lizzard"};
    
        
    
       for(n = 0; n<10; n++)
    
          {
    
          printf("The name is: %s\n", words[n]);
    
          }
    
       return 0;
    
       }


    questions:
    1) How would the correct statement of return of function 'allocate' and how would the correct type conversion (cast) within the function 'allocates'? I need a solution using int (* a) [3] because it is just a pointer to vector 3 position. I tried using the cast and the return of function like int (*) [3] but it does not work too!

    2) In part because of strings is printed a piece of code?

    Thank you
  2. #2
  3. No Profile Picture
    I haz teh codez!
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Dec 2003
    Posts
    2,547
    Rep Power
    2337
    Turn up your warnings and fix them!

    Code:
    $ gcc -Wall -pedantic --std=c99 -o foo foo.c
    foo.c: In function ‘main’:
    foo.c:29: warning: assignment from incompatible pointer type
    foo.c:63: warning: initialization from incompatible pointer type
    foo.c:63: warning: excess elements in scalar initializer
    foo.c:63: warning: (near initialization for ‘words’)
    foo.c:63: warning: excess elements in scalar initializer
    foo.c:63: warning: (near initialization for ‘words’)
    foo.c:63: warning: excess elements in scalar initializer
    foo.c:63: warning: (near initialization for ‘words’)
    foo.c:25: warning: unused variable ‘m’
    I ♥ ManiacDan & requinix

    This is a sig, and not necessarily a comment on the OP:
    Please don't be a help vampire!

IMN logo majestic logo threadwatch logo seochat tools logo