
Reg.allocating memory for double char pointer(char ** buf)
Hi friends,
The problem is in the below program,I need
a function passstruct() which is used to copy
the structure fields into a byte stream and must
return a pointer to that bytestream and the length
of the bytestream.The bytestream(sdbuf) and the
length must be the paramters of the function.
Can anyone give me the clear idea with
code how to allocate the memory for
the sdbuf(bytestream) and free that memory after
returning from the function.
Another issue is initially for the length
pointer I have to assign a constant value.How that
should be done?
Issue 2 is I don't know how much memory
/* THE AIM OF THE PROGRAM IS TO COPY SOME
FIELDS OF
A GIVEN STRUCTURE INTO A CHAR ARRAY(IN TERMS OF
SOCKET
COMMUNICATION SAY BYTESTREAM) AND THEN RETURN THE
POINTER TO THE BYTE STREAM AND LENGTH OF THE
BYTESTREAM
TO THE CALLING FUNCTION WHERE THERE IS FURTHER
PROCESSING OF THAT BYTE STREAM */
/* THIS IS THE PROGRAM AND TELL ME HOW
TO MODIFY THE PASSSTRUCT() FUNCTION TO ACHIEVE MY
AIM .THERE ARE ERRORS IN THE PASSSTRUCT().kINDLY
TELL ME HOW TO RECTIFY IT */
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4
5 typedef struct
6 {
7 int f1;
8 char *f2;
9 int f3;
10 }Msg;
11
12 main()
13 {
14 char *buf;
15 int len=0;
16 Msg msginst;
17 printf("enter the value for f1 field:");
18 scanf("%d",&msginst.f1);
19 printf("\nenter the value for f2 field:"
);
20 scanf("%s",msginst.f2);
21 printf("\n enter the value for f3
field:");
22 scanf("%d",msginst.f3);
23 printf("Befor calling the function\n");
24
printf("-----------------------------\n");
25 passstruct(&msginst,&buf,&len);
26 printf("After calling the function\n");
27
printf("----------------------------\n");
28 printf("The value of buf is %s \n",buf);
29 printf("The value of length is
%d\n",len);
30 }
31
32
33 void passsruct(msginst,sdbuf,buflen)
34 Msg *msginst,
35 char **sdbuf,
36 int *buflen;
37 {
38 *buflen=0;
39 /* sdbuf=(char*)malloc(sizeof(char)*24)*/
/* THIS POINT IS CONFUSING ME */
40 sdbuf[*buflen]=msginst->f1;
41 printf("The value in buffer is
%s\n",sdbuf);
42 *buflen=strlen(sdbuf);
43 printf("Thelength of buffer is
%d\n",*buflen);
44 sdbuf[*buflen+1]= msginst->f2;
45 printf("The value in buffer is
%s\n",sdbuf);
46 *buflen=strlen(sdbuf);
47 printf("The length of buffer is
%d",*buflen);
48 printf("THe end of the function\n");
49 return;
50 }
REGARDS
D.KARTHIK
--== Sent via Deja.com http://www.*-*-*.com/
---Share what you know. Learn what you don't.---