开发者

Declare a struct with zero values instead of random memory?

I have a struct like this:

typedef struct string {
 unsigned long length;
 开发者_运维知识库unsigned *data;
} string;

Can I write something so that when I do this:

string s;

the length property is zero, instead of whatever happens to be in the memory? data works well, as it's preset to zero or a null pointer.

Example of what happens right now:

string s;
printf("length:  %lu\n", s.length);
printf("pointer: %lu\n", (unsigned long) s.data);

Result:

length:  140737488347584
pointer: 0

I want to avoid having to call an initialisation function on each new string just to set length to zero.

More information

Now that I think about it, it may not be really necessary to do this in my particular case (though it would be nice) because most people would initially set the string through ctou (which imports UTF-8 from char pointer) and that function sets length to zero anyway.


You could use

string s = {0,NULL};


To combine the two previous answers (sort of) I'd define something like

#define STRING_INITIALIZER {0, NULL}
.
.
string s = STRING_INITIALIZER;

BTW, your struct declaration itself looks weird for a string. Either this is not a string as we usually understand it in C but merely a dynamic array of unsigned, or it is really a string and then this should be char*.


The accepted answer answered the question that you asked, but didn't address whether you ought.

Your string is a class and has class semantics. The initializer may be fine for kernel code where every last instruction counts, but in application code your static initializers are ugly and error prone.

It is possible to write classes in C, the stdio FILE type is a fabulous example, and here is the same idea applied to your string class:

typedef struct {
  int length;
  char *data;
} String;

String *sopen() {
  String *s = malloc(sizeof(String));
  if(s) {
    s->length = 0;
    s->data = NULL;
  }
  return s;
}

int sclose(String *s) {
  free(s->data);
  free(s);
  return 0;
}

int main()
{
   String *s = sopen();
   return sclose(s);
}

Where I've followed the FILE* function name style for metaphoric reasons. Yep, there's more code. Yep, you have to explicitly deallocate the structure; but note that even though you were counting on auto class initialization in your code sample, if data was ever allocated, you couldn't count on leaving scope to automatically deallocate the storage for you.

This approach also has the merit of abstracting the type of data from the users of the class. As there seems to be some confusion about what type you really want to use, this flexibility may come in handy.


#define DEFINE_STRING(s) string s = {0, NULL}

{
    DEFINE_STRING(s);
}

You can use a macro to "do this automatically"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜