C:标记每个struct,union,数组元素

时间:2013-10-25 06:31:41

标签: c arrays pointers

我想展示如何通过struct,union,array上的指针分配堆栈 我不知道如何接近。以下是我的尝试。

// to check the boundary
char *minimum_pointer, *maximum_pointer ;

// to check marked
void markmark(char *x, int size, char marking_address) {
  minimum_pointer = x;
  maximum_pointer = minimum_pointer + size;
  // is this correct?
  // I am trying to place marking_address 
  //   to every byte of x

  if (*minimum_pointer>marking_address || *maximum_pointer<marking_address) {
    printf("%s \n", "out of boundary");
  }

  int number_of_array_element = size/sizeof(char);
  for (int i=0; i<number_of_array_element; i++) {
    if (&x[i] >= minimum_pointer && &x[i] <= maximum_pointer) {
     x[i] = marking_address;
     // am I doing this right?
     // I need to place the address to every byte of input x
   }
  }
}

int main(int argc, const char * argv[]) {

  struct structure_example {
    char* a ;
    char b[20] ;
    float c ;
  } str_ex;
  markmark((char *) &str_ex, sizeof(str_ex), 0xa1);

  union union_example {
    float a ;
    char b ;
    int c ;
  } uni_ex;
  markmark((char *) &uni_ex, sizeof(uni_ex), 0xa2);

  char arr_ex[50] ;
  markmark((char *) &arr_ex, sizeof(arr_ex), 0xa3);

  return 0;
}

我的问题是

  maximum_pointer = minimum_pointer + size;
  // is this correct?
  // I am trying to place marking_address 
  //   to every byte of x

另一个问题是

  int number_of_array_element = size/sizeof(char);
  for (int i=0; i<number_of_array_element; i++) {
    if (&x[i] >= minimum_pointer && &x[i] <= maximum_pointer) {
     x[i] = marking_address;
     // am I doing this right?
     // I need to place the address to every byte of input x
   }
  }

让我感到困惑的是 我如何以及如何初始化struct和union和数组。

谢谢,

1 个答案:

答案 0 :(得分:-1)

如果你想要堆栈的地址然后minimum_pointer = x不正确,那只会使minimum_pointer指向x指向的同一个东西,即

char* p = "42";
markmark(p, ...

它没有说明堆栈,你需要取x的地址

minimum_pointer = &x;

我认为如果您查看标准头文件stdarg.h,您可以获得一些如何使用堆栈的提示。