Amit Singh Tomar
Amit Singh Tomar

Reputation: 8610

Can we pass structure member this way?

I have a below given structure which is having array of pointer its member

char input[128];

struct Stu

{

char *argv[];

int a;

};

struct stu *ptr=&stu;

ptr->argv[0]="name";

ptr->argv[1]=input;

fun(2,(**)ptr);     //is 2nd argument are we passing member of array input[128] ??

fun(int argc,char *argv[]){}  

how can 2nd argument passed from fun is stored in char*argv[]?

Upvotes: 0

Views: 139

Answers (2)

Jonathan Ben-Avraham
Jonathan Ben-Avraham

Reputation: 4841

AFAIK this is what you intend:

struct stu
{
    char **argv;    // *argv[] will give you "error: flexible array member not at end of struct"
    int a;
};

struct stu Stu;    // Allocate Stu as a global stu struct

fun(int argc, char * argv[]) {}

int main()
{
    char input[128];
    char *argies[2];        // Static allocation of space for argv to point to
    struct stu *ptr = &Stu;

    ptr->argv = argies;     // You need to assign argv to point to allocated space

    ptr->argv[0] = "name";
    ptr->argv[1] = input;

    fun(2, ptr->argv);    // is 2nd argument we passing member of array argv??
}

If you do not declare an actual stu struct, then ptr wiill be initialized to zero. Also if you do declare a static struct stu (Stu above) but do not initialize the argv pointer, the argv pointer will be initialized to zero. Not pointing to "who knows where" but pointing to a very specific place.

Note that input is not NULL terminated, in fact it is not initialized, so the variable name "argv" might be misleading because most programmers might assume that any char **argv holds NULL terminated C strings. Also, you probably want to dimension argies to 3 and put a NULL in the third position.

You can pass ptr->argv[0] (the string "name") as *(ptr->argv), but the fun prototype would have to be fun(int argc, char * argv).

**ptr->argv is a char.

*ptr is a struct stu.

**ptr is an error.

Upvotes: 0

Steve Wellens
Steve Wellens

Reputation: 20638

Your code is invalid:

struct stu *ptr;

ptr->argv[0]=2;

You have a pointer to a structure....but you don't have a structure allocated anywhere. You are pointing off into who knows what.

Upvotes: 2

Related Questions