top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

Can we realloc a string inside a structure in C?

+5 votes
177 views

Can we realloc a string inside a structure?

struct info
{
     char name[20];
     int age;
     char address[20];
}; 

struct info d[10];

I want to realloc name, how can I do it?

posted Jun 3, 2016 by Rupali Dadhe

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button
solution:

struct info
{
     char *name;
     int age;
     char *address;
};

struct info d[10];

int main()
{
.
.
.
for(i=0; i<10; i++)
{
    d[i].name=(char *)malloc(25);
    d[i].address=(char *) malloc(25);
}
..
.
.
d[z].name=(char *) realloc(d[z].name, 20);
 d[z].address= (char *)realloc(d[z].address, diff);
.
.
.
.
for(i=0; i<10; i++)
        {
        free(d[i].name);
        free(d[i].address);
    }

return 0;
}
Thanks everyone.
And sorry, I am the one who asked the qus and also ans it.
If i think more on this, then I had got the solution on that only.

1 Answer

0 votes

use char *name in place of char name[20], then in your program you can do malloc/calloc/realloac as name = malloc(25) or something similar.

I hope I understood the query correctly, if not please comment.

answer Jun 3, 2016 by Salil Agrawal
You're right, bu it's important to remember that sizeof(struct info) will be now different if you're doing this, no matter how much memory you allocate because now it's saving the pointer's address in the struct instead of it's content, so you'll have to write more code if you want to copy the struct or save it to into file.
Hello sir. I have already done it. But i have a problem in defining realloc.
I have done:
 
d[z].name= (char*) realloc(d[z].name, 5);

Here, z is any no. from 0 to 3
As per my knowledge, realloc() works only when memory is allocated earlier by using the malloc().
I got a solution of these question.
You can put your answer here so that others can benefit from it.
I already put my ans in the comment section
Similar Questions
+8 votes

Convert the given string into palindrome with minimum number of appends(at end of the given string). O(n) algorithm will be appreciated ??

Input :=> Malayal
Output :=> Malayalam

Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...