Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strings and structures in c

Tags:

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?

like image 843
Angus Avatar asked Jul 09 '26 20:07

Angus


1 Answers

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.

like image 92
Jason Avatar answered Jul 14 '26 09:07

Jason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!