Thread: Quick question with pointers, arrays, and malloc. malloc space for array of pointers

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    It's all wrong because you can't have a zero-sized array. But let's pretend it's an array of one.

    1. It's undefined behavior to access beyond the end of an array. You might get a segfault, you might not. That's the nature of undefined behavior.

    2. Not sure what you want. Currently it's a memory leak. You can just do pointers[0] = &a and now the first (and only) element of your array points to the local variable “a”.

    3. See 1.

    When you say that you want to “manage an array of pointers that is flexible”, perhaps you mean something like this:
    Code:
    void **pointers;
    
    pointers = malloc(5 * sizeof *pointers);
    pointers[0] = some_memory_location;
    pointers[1] = some_memory_location;
    ...
    pointers[4] = some_memory_location;
    Like any “dynamic array”, you create a pointer to the type you want to store. Since you want to store void*, you create a pointer to a pointer to void. Then allocate space.

  2. #2
    Registered User
    Join Date
    Jul 2009
    Posts
    35
    Thanks!

    One other question if you wouldn't mind indulging me.

    Code:
    Code:
    int main(int argc, char * argv[]) {
    	int a = 5;
    	int b = 6;
    	
    	void ** pointers = malloc(2 * sizeof(void *));
    	pointers[0] = &a;
    	pointers[1] = &b;
    	
    	int test[2];
    	test[0] = 4;
    	test[1] = 8;
    	
    	printf("%lu\n", sizeof(test) / sizeof(int) );
    	printf("%lu\n", sizeof(pointers));
    	printf("%lu\n", sizeof(pointers) / sizeof(void *));
    	printf("%lu\n", sizeof(*pointers) / sizeof(void *));
            
    	return 0;
    }
    Is it possible to get the number of items for dynamic arrays like this? I can do it with the var "test" above, but am not sure if you can even do it with the "pointers" var.

    Thanks again

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. Quick question on malloc and strings
    By officedog in forum C Programming
    Replies: 20
    Last Post: 11-06-2008, 05:14 PM
  3. Structures, arrays, pointers, malloc.
    By omnificient in forum C Programming
    Replies: 9
    Last Post: 02-29-2008, 12:05 PM
  4. pointers & arrays and realloc!
    By zesty in forum C Programming
    Replies: 14
    Last Post: 01-19-2008, 04:24 PM
  5. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM