我不明白为什么以下代码尽管正确打印了产品名称,但无法正确显示产品编号。你能给我解释一下吗?
#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;
}
元素
Product.name_
可以容纳 3 个字符的字符串(加上 \0
),但您传递了 strlen("Product 1") == 9
,因此 strcpy()
将导致未定义的行为。考虑使用 strncpy()
或 memcpy()
并确保生成的数组已 \0
终止。