0

Morning, I hope somebody is here suppose I have the following structure or even better an array of structures

struct foo {
  int a;
  char b[10];
  char c;
};

struct foo* bar;
bar = (struct foo*) malloc(sizeof(struct foo)*10);
memset(bar, -1, sizeof(struct foo)*10);

instead of

for (counter = 0; counter < 10; ++counter)
      memset(bar[counter],0,sizeof(char)*10);

how to a set b member to 0 in all array of char / b member in all array?

basically my question is a bit similar to this one

Community
  • 1
  • 1

2 Answers2

1

I'd like to suggest that rather than using a C-style array of int b[10]; that you use std::array<char,10> b; instead.

Then you can fill it with zeros this way: b.fill(0);. If you need to pass the address of the storage to a C-style function you can do that using b.data(). And of course, you can still access its content using b[i], but if you want more safety, use b.at(i).

http://en.cppreference.com/w/cpp/container/array

IanM_Matrix1
  • 1,564
  • 10
  • 8
0

You can set the b member of each array element to zero by setting the b member of each array element to zero. You were almost there, but:

  1. You only wanted to zero the b member.
  2. The thing you're zeroing isn't 8 bytes long.

 

for (counter = 0; counter < 10; ++counter)
    memset(bar[counter].b, 0, sizeof bar[counter].b);
user253751
  • 57,427
  • 7
  • 48
  • 90