在C99中使用size_t变量 [英] Using size_t variable in C99

查看:97
本文介绍了在C99中使用size_t变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近读到了关于在C99中使用 size_t 变量的信息。

我播下很多人在动态数组中使用它,有些人认为循环和其他地方(例如在功能变量中)。



我的主要问题是:



我知道 size_t 仅接受 unsigned 值,可用于替换 usigned long 变量类型。



我最近使用它,我无法理解我是否接受了主要想法。我可以在任何地方使用 size_t 我需要 unsigned int unsigned long 变量类型?



我的代码:



I read recently about the use of the size_t variable in C99.
I sow many people using it in dynamic arrays , some people for loop and others everywhere (eg in function vars).

My main question is this:

I know that size_t takes unsigned values only and that can used in replace of usigned long variable type.

I recently used it and I can't understand if I took the main idea. Can I use size_t everywhere I need a unsigned int or unsigned long type of variable?

My piece of code:

//in main function
FILE *input = fopen("input.txt","r");
size_t size = read_number(input);
int *array = malloc(size * sizeof *array);

//read the size of dynamic allocation 
size_t read_number(FILE *input) {
size_t size = 0;
fscanf(input, "%d",&size);

return size;
}

推荐答案

这不是变量,这是一个类型:http://www.cplusplus.com/reference/cstring/size_t [ ^ ]。



您应该使用此类型来计算数据大小,不是 unsigned long 或其他任何东西。

此外, sizeof * array 是元素的大小,而不是数组的大小。要获得数组大小,请将元素大小乘以元素数。(您实际上正确地获得要分配的数据大小。)



-SA
This is not a "variable", this is a type: http://www.cplusplus.com/reference/cstring/size_t[^].

You should use this type to calculate data sizes, not unsigned long or anything else.
Also, sizeof *array is a size of an element, not a size of array. To get a size of array, multiply element size by the number of elements. (You actually correctly get the size of the data to allocate.)

—SA


size_t通常是系统中最大的无符号整数类型。如果你在处理对象大小的任何地方使用它(duh,名字中的线索!)和循环索引,你的代码可能不会对你造成严重错误,你可能会受到与整数相关的可移植性问题的影响。



但如果你不知道你在做什么,它可以打开一堆虫子。例如,您的代码告诉fprintf您正在尝试将有符号整数读入size_t - 不一定是您想要的!在32位系统上添加一个有符号整数可能是size_t的一半,所以你手上有一个潜在的问题。



当你'使用C99(//评论放弃)然后你可以使用(IIRC)%z格式说明符来解决printf系列灾难,该说明符映射到任何size_t被定义为。
size_t will usually be the biggest unsigned integer type on your system. If you use it wherever you're dealing with sizes of objects (duh, clue in the name!) and loop indices your code will probably not go horribly wrong on you and you might be protected from size of integer related portability problems.

However it can open cans of worms if you don't know what you're doing. Your code for example tells fprintf that you're trying to read a signed integer into a size_t - not necessarily what you wanted! Add to that on 32 bit systems a signed integer is likely to be half the size of a size_t so you've got a potential problem on your hands.

As you're using C99 (the //comments give it away) then you can get over the printf family disaster by using the (IIRC) %z format specifier which maps to whatever size_t is defined as.


这篇关于在C99中使用size_t变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆