Angus
Angus

Reputation: 12631

Strings and structures in c

#include "stdafx.h"
#include <stdio.h>

struct s 
{
  char *st;
  struct s *sp; 
};

struct s *p1,*p2;
void swap(struct s *p1,struct s *p2);

int main()
{
    int i;
    struct s *p[3];
    static struct s a[]={
        {"abc",a+1},{"def",a+2},{"ghi",a}
    };
    for(i=0;i<3;i++)
    {
     p[i]=a[i].sp;
    }
    swap(*p,a);
    printf("%s %s %s\n",p[0]->st,(*p)->st,(*p)->sp->st);
    return 0;
}
void swap(struct s *p1,struct s *p2)
{
    char *temp;
    temp = p1->st;
    p1->st = p2->st;
    p2->st = temp;
}

This program outputs as abc,abc,ghi. My doubt is what does p[0]->st,(*p)->st,(*p)->sp->st outputs.we havent intialised st with abc or ghi.How does it outputs the string?

Upvotes: 3

Views: 502

Answers (2)

sergio
sergio

Reputation: 69047

I haven't analysed all the statements, but assignment to ->st and ->sp happens here:

static struct s a[]={
    {"abc",a+1},{"def",a+2},{"ghi",a}
};

the rest are games with pointers so the output is what you see. So, say:

  1. the a array is created and initialized;

  2. in the for loop the p array is also initialized;

  3. noticing that sp recursively points to struct s instances, p and a have the same structure;

  4. each elements of p is made point to a struct s instance taken from one of the elements of a.

Upvotes: 2

Jason
Jason

Reputation: 32538

We havent intialised st with abc or ghi. How does it outputs the string?

The value of the st member for each structure in the statically allocated array a is actually initialized through an initialization list. Writing

static struct s a[]={
    {"abc",a+1},{"def",a+2},{"ghi",a}
};

has the same effective meaning after its execution as writing the following:

static struct s a[3];
a[0].st = "abc";
a[0].sp = a+1;
a[1].st = "def";
a[1].sp = a+2;
a[2].st = "ghi";
a[2].sp = a;

And what's effectively happened after both methods of initialization is you have a statically-allocated circular linked list of struct s, where the data-members of each node in the list (the st member) is pointing to a string literal like "abc", "def", etc. The sp data member is pointing to the next node in the linked list.

Upvotes: 4

Related Questions