Thread: problem with pointers

  1. #1
    Registered User
    Join Date
    Apr 2011
    Posts
    11

    Smile problem with pointers

    hi,

    i need some help with resolving the following problem. What i have is a structure in which i have a pointer to the character array. on the other hand i have a string array like this:

    Code:
    typedef struct tmp{
    
    char *array1;
    }TMP;
    
    int main(){
    
    char *array2 = "mystring";
    
    }
    what i need to do is to make the array1 an array of pointers such that when i iterate over them like this :

    Code:
    for (i=0;i<=n;i++){
      printf("%s\n",TMP->array1[i]);
    }
    i get the result:

    Code:
    mystring
    ystring
    string
    tring
    ring
    ing
    ng
    g
    How would i do this, could anyone provide an example ??

    thank you

    baxy

  2. #2
    Bit Fiddler
    Join Date
    Sep 2009
    Posts
    79
    Your example code is quite scrappy.
    Iterate over memory instead. There is no point to assign a pointer to each character in the string.
    Code:
    for (i = 0; i < n; i++)
        printf("%s\n", TMP->array1 + i);

  3. #3
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by baxy77bax View Post
    hi,

    i need some help with resolving the following problem. What i have is a structure in which i have a pointer to the character array. on the other hand i have a string array like this:

    Code:
    for (i=0;i<=n;i++){
      printf("%s\n",TMP->array1[i]);
    }
    Did you test your own sample, above?

    It actually should work.

    The problem is that you are using typedef to design the struct but you never create an instance of the struct itself...
    Code:
    TMP Temp;   
    // or
    TMP* Temp = malloc(sizeof(TMP));
    Last edited by CommonTater; 04-13-2011 at 06:44 AM.

  4. #4
    Registered User
    Join Date
    Apr 2011
    Posts
    11

    Unhappy



    thnx, now it works!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with pointers
    By grifan526 in forum C Programming
    Replies: 2
    Last Post: 01-23-2010, 11:49 PM
  2. Problem with malloc and pointers to pointers
    By mike_g in forum C Programming
    Replies: 7
    Last Post: 03-29-2008, 06:03 PM
  3. A problem with pointers
    By vsla in forum C Programming
    Replies: 2
    Last Post: 10-10-2007, 04:14 AM
  4. problem , need pointers. thanks
    By mobius in forum C Programming
    Replies: 4
    Last Post: 09-03-2001, 05:12 AM