473,405 Members | 2,261 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,405 software developers and data experts.

[Q] Initialise a struct with variable length cahracter strings

Dear Readers,

I am attempting to initialise a struct contiaing a dynamic character
string. In the example below I am trying to initialise the name field
so that my struct does not waste space. I know if I change char
name[80] this will work, but I will waste alot of space. (I am
learning so I want to learn the best way)

How can I define a struct the allows variable length character strings
in the
definition?

Thank

Stuart

#include <stdio>
#include <stdlib>

int main (int argc, char **argv)
{
struct command
{
unsigned int cmd;
unsigned int olen;
unsigned int ilen;
char name[];
} init[] = {{0,0,0,"Name A"},{0,0,0,"Name B 123"}};
}
Nov 13 '05 #1
6 5412
Stuart Norris wrote:
How can I define a struct the allows variable length character strings
in the
definition? struct command
{
unsigned int cmd;
unsigned int olen;
unsigned int ilen;
char name[]; char *name; } init[] = {{0,0,0,"Name A"},{0,0,0,"Name B 123"}};


--
Tom Zych
This is a fake email address to thwart spammers.
Real address: echo 'g******@cbobk.pbz' | rot13
Nov 13 '05 #2

"Stuart Norris" <st**********@yahoo.com.au> wrote in message
news:51**************************@posting.google.c om...
Dear Readers,

I am attempting to initialise a struct contiaing a dynamic character
string. In the example below I am trying to initialise the name field
so that my struct does not waste space. I know if I change char
name[80] this will work, but I will waste alot of space. (I am
learning so I want to learn the best way)

How can I define a struct the allows variable length character strings
in the
definition?

Thank

Stuart

#include <stdio>
#include <stdlib>

int main (int argc, char **argv)
{
struct command
{
unsigned int cmd;
unsigned int olen;
unsigned int ilen;
char name[];
const char *name;
} init[] = {{0,0,0,"Name A"},{0,0,0,"Name B 123"}};
}


Note that you must not modify what 'name' points to.

-Mike
Nov 13 '05 #3
On 24 Sep 2003 17:53:35 -0700, st**********@yahoo.com.au (Stuart
Norris) wrote:
Dear Readers,

I am attempting to initialise a struct contiaing a dynamic character
string. In the example below I am trying to initialise the name field
so that my struct does not waste space. I know if I change char
name[80] this will work, but I will waste alot of space. (I am
learning so I want to learn the best way)

How can I define a struct the allows variable length character strings
in the
definition?

Thank

Stuart

#include <stdio>
#include <stdlib>
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char **argv)
{
struct command
{
unsigned int cmd;
unsigned int olen;
unsigned int ilen;
char name[];
This is an incomplete type which means that the entire structure
will also be an incomplete type.

You cannot define an array of incomplete types. Change this
to:
char *name;
or:
char name[11];
} init[] = {{0,0,0,"Name A"},{0,0,0,"Name B 123"}};
}


Nick.

Nov 13 '05 #4


Stuart Norris wrote:
Dear Readers,

I am attempting to initialise a struct contiaing a dynamic character
string. In the example below I am trying to initialise the name field
so that my struct does not waste space. I know if I change char
name[80] this will work, but I will waste alot of space. (I am
learning so I want to learn the best way)

How can I define a struct the allows variable length character strings
in the
definition?
struct command
{
unsigned int cmd;
unsigned int olen;
unsigned int ilen;
char name[];
} init[] = {{0,0,0,"Name A"},{0,0,0,"Name B 123"}};


It it is unacceptable to declare fixed arrays then I would suggest
that you dynamically allocated space. Write a function that will
allocate and assign.

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

struct command
{
unsigned int cmd;
unsigned int olen;
unsigned int ilen;
char *name;
};

struct CommandArray
{
struct command *command;
unsigned count;
};

struct command *AddStruct(struct CommandArray *p, unsigned cmd,
unsigned olen, unsigned ilen, const char *name);
void FreeStruct(struct CommandArray *p);

int main(void)
{
struct CommandArray test = {NULL, 0};
unsigned i;

AddStruct(&test, 0,0,0, "Name A");
AddStruct(&test, 0,0,0, "Name B 123");
for(i = 0; i < test.count; i++)
printf("test.command[%u].name = \"%s\"\n",
i,test.command[i].name);
FreeStruct(&test);
return 0;
}

struct command *AddStruct(struct CommandArray *p, unsigned cmd,
unsigned olen, unsigned ilen, const char *name)
{
struct command *temp;
unsigned i = p->count;

temp = realloc(p->command, (sizeof *p->command)*(i+1));
if(temp == NULL) return NULL;
p->command = temp;
if((p->command[i].name = malloc(strlen(name)+1)) == NULL)
return NULL;
strcpy(p->command[i].name,name);
p->command[i].ilen = ilen;
p->command[i].olen = olen;
p->command[i].cmd = cmd;
p->count++;
return &p->command[i];
}

void FreeStruct(struct CommandArray *p)
{
unsigned i;

for(i = 0;i < p->count; i++)
free(p->command[i].name);
free(p->command);
p->command = NULL;
p->count = 0;
}
--
Al Bowers
Tampa, Fl USA
mailto: xa*@abowers.combase.com (remove the x)
http://www.geocities.com/abowers822/

Nov 13 '05 #5
On Thu, 25 Sep 2003 04:39:42 +0100, Nick Austin
<ni**********@nildram.co.uk> wrote:
On 24 Sep 2003 17:53:35 -0700, st**********@yahoo.com.au (Stuart
Norris) wrote: <snip>
struct command
{
unsigned int cmd;
unsigned int olen;
unsigned int ilen;
char name[];


This is an incomplete type which means that the entire structure
will also be an incomplete type.

In C90, that is a constraint violation; a struct (or union) member
cannot have incomplete type at all. In C99, as the last member, that
is a flexible array member, the blessed form of the struct hack. It
does not make the containing struct incomplete; instead the struct
type has only the size of the fixed header, and you the programmer are
responsible for allocating/managing memory space for any objects that
also contain the variable part.
You cannot define an array of incomplete types.
True, but irrelevant in either case. You *can* have an array of
FAMiful elements, but they do not allow any space for the variable
parts, as is needed in this application.
Change this
to:
char *name;
or:
char name[11];
} init[] = {{0,0,0,"Name A"},{0,0,0,"Name B 123"}};
}

Right. Of course the former wastes space, which is what the OP asked
to avoid, although unless there are thousands of these or the maximum
length is (and needs to be) much more than the 11 shown or this is a
very constrained embedded system I wouldn't worry about it; and the
latter wastes a pointer in each struct as well as making the targets
not (safely) writable, if that matters.

The FAMly alternative, which cannot be initialized in the language
sense, but only set at runtime perhaps startup:
struct command * array[WHATEVER];
/* error checking omitted */
array[0] = malloc(sizeof(struct command)+strlen(str1)+1);
array[0]->cmd = 0; ... strcpy(array[0]->name, str1);
array[1] = malloc(sizeof(struct command)+strlen(str2)+1);
array[1]->cmd = 0; ... strcpy(array[1]->name, str2);
etc.
- David.Thompson1 at worldnet.att.net
Nov 13 '05 #6
mushu
2
On Thu, 25 Sep 2003 04:39:42 +0100, Nick Austin
<nickDIGITONE@nildram.co.uk> wrote:
[color=blue]
> On 24 Sep 2003 17:53:35 -0700, stuie_norris@yahoo.com.au (Stuart
> Norris) wrote:[/color]
<snip>[color=blue][color=green]
> > struct command
> > {
> > unsigned int cmd;
> > unsigned int olen;
> > unsigned int ilen;
> > char name[];[/color]
>
> This is an incomplete type which means that the entire structure
> will also be an incomplete type.
>[/color]
In C90, that is a constraint violation; a struct (or union) member
cannot have incomplete type at all. In C99, as the last member, that
is a flexible array member, the blessed form of the struct hack. It
does not make the containing struct incomplete; instead the struct
type has only the size of the fixed header, and you the programmer are
responsible for allocating/managing memory space for any objects that
also contain the variable part.
[color=blue]
> You cannot define an array of incomplete types.[/color]

True, but irrelevant in either case.
- David.Thompson1 at worldnet.att.net
Sorry for gravedigging, but this post was relevant to a question I have.

I need to copy a file into a buffer that is part of a struct, then pass a reference to the struct into a callback function (for an audio API). So, could I use this code (abridged):

Expand|Select|Wrap|Line Numbers
  1. typedef struct
  2. {
  3.     int channels;
  4.     double samplerate;
  5.     unsigned double framesToGo;
  6.     char *buffer;
  7. }
  8. PlaybackData;
  9.  
  10. int main()
  11. {
    int filesize; /* this would be the size of the file once loaded*/
  12. PlaybackData data;
  13. data.buffer = malloc( filesize );
  14. }
  15.  
Would I also need to malloc for the entire struct, so the actual pointer would have some space?

Thanks.
Jun 17 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Gordon Scott | last post by:
Hi All, I've got a problem I'm seeing when trying to use the struct module to send data to a different machine. Actually I'm making a condensed file that gets transferred to and read on a BREW...
5
by: Geoffrey | last post by:
Hope someone can help. I am trying to read data from a file binary file and then unpack the data into python variables. Some of the data is store like this; xbuffer:...
5
by: MLH | last post by:
I'm working with lots of long strings now, it seems. I have to import them & parse them constantly. The A97 memo field type supports only 32768 chars. What happens when this is processed... Dim...
18
by: Panchal V | last post by:
I want to access a variable length record in C, the format is as follows : +---+---+-----------+ | A | L | D A T A | +---+---+-----------+ A - Some Data (1 BYTE) L - Length the Data that...
7
by: Mo | last post by:
I am having problem with marshaling struct in C#. //the original C++ struct typedef struct _tagHHP_DECODE_MSG { DWORD dwStructSize; // Size of decode structure. TCHAR ...
10
by: Giovanni Bajo | last post by:
Hello, given the ongoing work on struct (which I thought was a dead module), I was wondering if it would be possible to add an API to register custom parsing codes for struct. Whenever I use it...
5
by: jaso | last post by:
Hi, If have a structure of a database record like this: struct record { char id; char title; ... }; Is there some way to find out how many member variables there is in the struct and then...
14
by: Frederick Gotham | last post by:
How do we initialise an aggregate member object of a class? The following won't compile for me: struct MyStruct { int i; double d; }; class MyClass { private:
19
by: bowlderyu | last post by:
Hello, all. If a struct contains a character strings, there are two methods to define the struct, one by character array, another by character pointer. E.g, //Program for struct includeing...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.