Thread: char pointer to pointer question

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Jan 2009
    Posts
    2

    char pointer to pointer question

    Hi everyone,

    I've been playing around with pointer to pointers recently and stumbled upon a weird problem I can't figure out.

    Code:

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    
    int main ()
    {
            char **test;
            char *str1 = "string 1";
            char *str2 = "string 2";
            char *str3 = "string 3";
            int i = 0;
    
            test = malloc(3 * sizeof(char *));
    
            test[0] = str1;
            test[1] = str2;
            test[2] = str3;
    
            while (*test++) {
                    printf("%d\n",i);
                    ++i;
            }
    
            return 0;
    }

    Compiling with "gcc -O2 -Wall -pedantic -ansi -g test.c -o test" which results in:

    0
    1
    2
    3

    Even though there are only 3 char pointers assigned, shouldn't it stop if i == 2 ?
    Changing the malloc to malloc(4 * sizeof(char *)) seems to be fixing the problem, but that can't be right, making room for four char pointers but only using three?

    Also if I'm assigning one, two, four or more char pointers to test it counts correctly. It only fails when assigning 3 pointers to test.

    Can someone please point out to me what I'm missing here?

    salt shaker
    Last edited by Salt Shaker; 01-10-2009 at 11:57 AM. Reason: Ah yes my bad, had a little typo, st3 instead of str3 :)

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. C++ ini file reader problems
    By guitarist809 in forum C++ Programming
    Replies: 7
    Last Post: 09-04-2008, 06:02 AM
  3. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  4. Basic things I need to know
    By maxorator in forum C++ Programming
    Replies: 53
    Last Post: 10-15-2006, 04:39 PM
  5. Question About Pointer To Pointer
    By BlitzPackage in forum C++ Programming
    Replies: 2
    Last Post: 09-19-2005, 10:19 PM