Thread: question on pointer

  1. #1
    Registered User blob84's Avatar
    Join Date
    Jun 2010
    Posts
    46

    question on pointer

    This code works, but i don't understand why the loop works.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    int main() {
    	char **arr;
    	size_t size = 200 * sizeof(size);
    	arr = malloc(size);
    	arr[0] = "cane";
    	arr[1] = "dog";
    	while( *arr != NULL )
    		printf("%s\n", *arr++);
    
    }
    Last edited by blob84; 09-09-2010 at 05:24 AM.

  2. #2
    Novice
    Join Date
    Jul 2009
    Posts
    568
    != is saying not.
    The code can be further reduced.
    Code:
    while (*arr++) {
        printf("%s\n", *arr);
    }

  3. #3
    Registered User blob84's Avatar
    Join Date
    Jun 2010
    Posts
    46
    nice msh, but inverting arr position:
    Code:
    while (*arr) 
          printf("%s\n", *arr++);

  4. #4
    Novice
    Join Date
    Jul 2009
    Posts
    568
    Quote Originally Posted by blob84 View Post
    nice msh, but inverting arr position:
    Code:
    while (*arr) 
          printf("%s\n", *arr++);
    Yea. You're right.

    But you can't really use this here; it'll segfault if it fails to run across a null byte before reaching the end of arr.

    This is probably more correct.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
        const int entries = 2;
        char** arr = (char**)malloc(entries * sizeof(*arr));
        arr[0] = "cane";
        arr[1] = "dog";
    
        int i;
        for (i = 0; i < entries; ++i)
        {
            printf("%s\n", arr[i]);
        }
    
        return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sorting number
    By Leslie in forum C Programming
    Replies: 8
    Last Post: 05-20-2009, 04:23 AM
  2. Easy pointer question
    By Edo in forum C++ Programming
    Replies: 3
    Last Post: 01-19-2009, 10:54 AM
  3. char pointer to pointer question
    By Salt Shaker in forum C Programming
    Replies: 3
    Last Post: 01-10-2009, 11:59 AM
  4. Pointer question
    By rakan in forum C++ Programming
    Replies: 2
    Last Post: 11-19-2006, 02:23 AM
  5. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM