473,396 Members | 1,996 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Array of Structure

This code runs, but doesnt prints the second string in the structure properly. Moreover if the size is increased from 2 to 3, it gives segmentation fault. Any help will be greatly appreciated. :)

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. typedef struct {
  6.   char *name;
  7.   int   number;
  8. } MyStr;
  9.  
  10. typedef MyStr* MyStrPointer;
  11.  
  12. int GetNumberOfMyStrs(void);
  13. MyStr * GetNextMyStr(void);
  14. char * GetBuffer(MyStrPointer *MyStrPtr, int *size);
  15.  
  16.  
  17. int main()
  18. {
  19.   char *str;
  20.   MyStrPointer MyStrPtr;
  21.   int numseq;
  22.   int i;
  23.  
  24.   str=GetBuffer(&MyStrPtr, &numseq);
  25.   printf("String b: %s", str);
  26.   printf("\nPrint strings (in main).\n");
  27.   for (i=0; i<numseq; i++) {
  28.     printf("String %d : %s", i, MyStrPtr[i].name);
  29.     printf("\nSize : %d\n", MyStrPtr[i].number);
  30.   }
  31.  
  32.     printf("Free memory\n");
  33.     for (i=0; i<numseq; i++) {
  34.     printf("%d ", i);
  35.     free(MyStrPtr[i].name);
  36.   }
  37.  
  38.   free(MyStrPtr);
  39.  
  40.   return 0;
  41. }
  42.  
  43. int GetNumberOfMyStrs(void) {
  44.   int value;
  45.  
  46.   /* Consider a simple case */
  47.   value = 2;
  48.   return value;
  49. }
  50.  
  51. MyStr * GetNextMyStr(void) {
  52.   char string[100];
  53.   int length;
  54.  
  55.  static MyStr seq; 
  56.  
  57.   printf("Enter string\n");
  58.   fgets(string, sizeof(string), stdin);
  59.   length = strlen(string);
  60.  length++; 
  61.   seq.name=(char*)malloc((length)*sizeof(char));
  62.  
  63.   strncpy(seq.name, string, (length-1));
  64.  
  65.   seq.name[length] = '\0';
  66.  
  67.   seq.number = length;
  68.  
  69.     printf("\nseq name: %s", seq.name);
  70.     printf("\nseq number: %d", seq.number);
  71.  
  72.   return &seq;
  73. }
  74.  
  75. char * GetBuffer(MyStrPointer *MyStrPtr, int *size) {
  76.   MyStrPointer SSPtr;
  77.  
  78.   int i;
  79.  
  80.   *size = GetNumberOfMyStrs();
  81.  
  82.   *MyStrPtr = (MyStr*)malloc((*size) * sizeof(MyStr));
  83.  
  84.     for (i=0; i<*size; i++) {
  85.  
  86.     SSPtr = GetNextMyStr();
  87.     (*MyStrPtr)[i].name = (char*)malloc(((*SSPtr).number)*sizeof(char));
  88.  
  89.  
  90.         (*MyStrPtr)[i].number = (*SSPtr).number;
  91.  
  92.     strncpy((*MyStrPtr[i]).name, (*SSPtr).name, ((*SSPtr).number-1));
  93.  
  94.     (*MyStrPtr)[i].name[(*SSPtr).number]='\0';
  95.  
  96.     printf("\ni=%d size=%d number=%d name= %s", i, *size, (*SSPtr).number, (*SSPtr).name);
  97.     printf("\nMyStrPtr[%d].name: %s", i, (*MyStrPtr)[i].name);    
  98.   }
  99.  
  100.   printf("\nOut loop");
  101.   free((*SSPtr).name);
  102.   printf("\n before return");
  103.   return ((*MyStrPtr)[0].name);
  104. }
Dec 24 '07 #1
5 1537
weaknessforcats
9,208 Expert Mod 8TB
printf("String %d : %s", i, MyStrPtr[i].name);
This says you are using an array of MyStrPtr but you have not defined any array at all. All you have is one pointer.
Dec 24 '07 #2
Thanks ... I got it! :D
Happy Holidays!
Dec 24 '07 #3
Hi! check the output of below mentioned program.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
char name[20];
int number;
} MyStr;

MyStr MyStrPointer[3];

int GetNumberOfMyStrs(void);
MyStr *GetNextMyStr(void);
//int GetBuffer(MyStrPointer *, int *);

int main()
{
char *str;
int numseq;
int i;
GetBuffer(&MyStrPointer, &numseq);
printf("\nPrint strings (in main).\n");
for (i=0; i<numseq; i++)
{
printf("String %d : %s", i, MyStrPointer[i].name);
printf("\nSize : %d\n", MyStrPointer[i].number);
}
return 0;
}

int GetNumberOfMyStrs(void)
{
int value;
/* Consider a simple case */
value = 3;
return value;
}

MyStr * GetNextMyStr(void)
{
char string[100];
int length;
static MyStr seq;
printf("Enter string\n");
fgets(string, sizeof(string), stdin);
length = strlen(string);
length++;
strncpy(seq.name, string, (length-1));
seq.name[length] = '\0';
seq.number = length;
printf("\nseq name: %s", seq.name);
printf("\nseq number: %d", seq.number);
return &seq;
}

int GetBuffer(MyStr *SSPtr, int *size)
{
int i;
*size = GetNumberOfMyStrs();
for (i=0; i<*size; i++)
{
SSPtr = GetNextMyStr();
printf("\ni=%d size=%d number=%d name= %s", i, *size, (*SSPtr).number, (*SSPtr).name);
strncpy(MyStrPointer[i].name, (*SSPtr).name, ((*SSPtr).number-1));
MyStrPointer[i].name[(*SSPtr).number]='\0';
MyStrPointer[i].number = ( *SSPtr).number ;
printf("String %d : %s", i, MyStrPointer[i].name);
printf("\nSize : %d\n", MyStrPointer[i].number);
}
printf("\nOut loop");
printf("\n before return");
return 0;
}

with regards,
G. Siva Prakash Reddy.
Dec 26 '07 #4
primeSo
35
I have some doubts after reading through your program, i would like to point them out here to gain some clarification from you all.

1) Line 21 & 24
You declared a integer variable, numseq but didn't initilialize them, is it alright in the context of C programming? i thought we should always initialize any variable in C before we use them, in this case you pass the variable by reference to a function.

2) Line 75 &80
Is it good to pass the variable with undefined value to the function, namely GetBuffer() and get the value from user in that function itself? I think it is better to get the value from the user in the main() first before we proceed with the process, am i right ?

3)Line 35 & 38
According to what i have learnt, we should always malloc-ed and free-ed a variable in the same function, in other words, we should always free the same variable in the function where we malloc the variable, am i correct? If this is the case, the function MyStr * GetNextMyStr(void) and char * GetBuffer(MyStrPointer *MyStrPtr, int *size) will generate memory leak, am i right? because both of the function malloc-ed a variable but the variables were being freed in the main() instead of the called function.

4) Line 55
what is the effect of the storage type "static" in this statement ? Preserve the value in the variable in each call to the function it is declared ? can we return a static variable to a calling function ?

5) Line 103
return ((*MyStrPtr)[0].name); <---- means you always return the first element in the array to the calling function. in your case, the main()? (no matter how element in your array, always return the first one only).

6) Lastly, as what weaknessforcats mentioned, you haven't declare any array of MyStr type.
Dec 26 '07 #5
primeSo
35

MyStr MyStrPointer[3];

int GetNumberOfMyStrs(void);
MyStr *GetNextMyStr(void);
//int GetBuffer(MyStrPointer *, int *);

int main()
{
char *str;
int numseq;
int i;
GetBuffer(&MyStrPointer, &numseq);
printf("\nPrint strings (in main).\n");
for (i=0; i<numseq; i++)
{
printf("String %d : %s", i, MyStrPointer[i].name);
printf("\nSize : %d\n", MyStrPointer[i].number);
}
return 0;
}
You declare a global array of type MyStr which consists of 3 elements. But you pass them as below
Expand|Select|Wrap|Line Numbers
  1. GetBuffer(&MyStrPointer, &numseq);
is it correct? this mean "pass the address of the memory location which point to the first element of the array? hence, you need to use two * (
int GetBuffer(MyStr **SSPtr, int *size)) to receive them in the called function ? I thought we need to pass the name of the array only when we want to pass them as parameter to a function, in this case suppose to be
Expand|Select|Wrap|Line Numbers
  1. GetBuffer(MyStrPointer, &numseq);
Dec 26 '07 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

6
by: Eric Smith | last post by:
Is a structure containing an incomplete array as its last element (per paragraph 2 of section 6.7.2.1 of ISO/IEC 9899:1999 (E)) itself an incomplete type? That appears to be indicated by paragraph...
5
by: Joe Thompson | last post by:
Hi I am new to C# and am rewritting some C++ code. I want to send a byte array over a serial port. The elements of the byte array are really a structure I have populated. My question is, how do...
26
by: Brett | last post by:
I have created a structure with five fields. I then create an array of this type of structure and place the structure into an array element. Say index one. I want to assign a value to field3 of...
104
by: Leszek | last post by:
Hi. Is it possible in javascript to operate on an array without knowing how mamy elements it has? What i want to do is sending an array to a script, and this script should add all values from...
7
by: Sam | last post by:
Hello I have a structure called Company. struct Company { char *employee; char *employee_address; }; I want to build an array of this structure but the number of employees will change...
8
by: Sam | last post by:
I have a situation occuring in my code and I just can't see to figure out why I have an structure called employee that will put all of the employee id's into a char array set to 10 struct...
2
by: craig | last post by:
I'm fried on this problem...It's vb.net, dealing with a web service that requires input as an array of a particular data structure and I can't get the code to compile or run... Basically, the...
12
by: gcary | last post by:
I am having trouble figuring out how to declare a pointer to an array of structures and initializing the pointer with a value. I've looked at older posts in this group, and tried a solution that...
5
by: =?Utf-8?B?QXlrdXQgRXJnaW4=?= | last post by:
Hi Willy, Thank you very much for your work. C++ code doesnot make any serialization. So at runtime C# code gives an serialization error at "msg_file_s sa = (msg_file_s) bf.Deserialize(ms);"...
10
by: Scott Townsend | last post by:
So I need to talk to a devices that expects all of the bits and bytes I sent it to be in specific places (not yet 100% defined). I wanted to create a structure/class with all of the data in it...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.