指针和结构:为什么这个 C 代码不起作用?

问题描述 投票:0回答:1

我不明白为什么以下代码尽管正确打印了产品名称,但无法正确显示产品编号。你能给我解释一下吗?

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

typedef struct products
{
  char name_[4];
  int number_;
} Product;

Product* createProduct(char* name, int number)
{
  Product* new_product = malloc(sizeof(Product));
  if(new_product == NULL)
    return NULL;
  new_product->number_ = number;
  strcpy(new_product->name_, name);
  return new_product;
}

int main()
{
  Product* array[3];
  array[0] = createProduct("Product 1", 0xAABBCCDD);
  array[1] = createProduct("Product 2", 0xFFAA33EE);
  array[2] = createProduct("Product 3", 0xBBCC7799);

  for(int i = 0; i < 3; i++)
  {
    Product* product = array[i];
    printf("%s : 0x%X\n", product->name_, product->number_);
    free(product);
  }
  printf("Are all product numbers displayed correctly?\n");

  return 0;
}
c pointers struct
1个回答
0
投票

元素

Product.name_
可以容纳 3 个字符的字符串(加上
\0
),但您传递了
strlen("Product 1") == 9
,因此
strcpy()
将导致未定义的行为。考虑使用
strncpy()
memcpy()
并确保生成的数组已
\0
终止。

© www.soinside.com 2019 - 2024. All rights reserved.