so i read in integers into an array, how do i fill the empty elements with spaces. i know that they get initialized with that long negative number. do i check if they have that and then fill those elements with spaces?
所以我将整数读入数组,如何用空格填充空元素。我知道他们用那么长的负数初始化了。我检查他们是否有那个,然后用空格填充这些元素?
int* scores = malloc(51 * sizeof(int));
FILE* fp;
char* string = malloc(21 * sizeof(char));
int length;
int* plength = &length;
int number_of_conversions;
long offset = 0;
long* poffset = &offset;
int* scores = malloc(51 * sizeof(int));
scores[50] = '\0';
int total;
int* ptotal = &total;
int i = 0;
this is the array
这是阵列
2 个解决方案
#1
First, consider using calloc() since you're using the allocated memory to hold a null terminated string. If you want to initialize memory with a specific value, including \32 or ' ' try using memset().
首先,考虑使用calloc(),因为您使用分配的内存来保存空终止字符串。如果要使用特定值初始化内存,包括\ 32或''尝试使用memset()。
int* scores = calloc(51 * sizeof(int));
memset(scores, ' ', 50*sizeof(int));
// no longer needed
// scores[50] = '\0';
#2
malloc
does not set memory to anything in particular. Depending on runtime and operating system you may get some consistent implementation specific pattern like zeros, specific filler, but you should not rely on it - malloc zeroing out memory?.
malloc没有特别设置内存。根据运行时和操作系统,您可能会获得一些一致的特定于实现的模式,如零,特定填充,但您不应该依赖它 - malloc清零内存?
To set array to something particular you can either
要将数组设置为特定的值,您可以
- use
memset
that let you set memory to particular byte (0 seem to be what you are looking for) - use
for
loop to set values you want (i.e. if you want fillint
array with some non-zero number like 42) - track how many elements are used in the array instead filling whole array with defaults.
使用memset,你可以将内存设置为特定的字节(0似乎是你正在寻找的)
使用for循环来设置你想要的值(即如果你想要填充int数组有一些非零数字,如42)
跟踪数组中使用了多少元素,而不是使用默认值填充整个数组。
#1
First, consider using calloc() since you're using the allocated memory to hold a null terminated string. If you want to initialize memory with a specific value, including \32 or ' ' try using memset().
首先,考虑使用calloc(),因为您使用分配的内存来保存空终止字符串。如果要使用特定值初始化内存,包括\ 32或''尝试使用memset()。
int* scores = calloc(51 * sizeof(int));
memset(scores, ' ', 50*sizeof(int));
// no longer needed
// scores[50] = '\0';
#2
malloc
does not set memory to anything in particular. Depending on runtime and operating system you may get some consistent implementation specific pattern like zeros, specific filler, but you should not rely on it - malloc zeroing out memory?.
malloc没有特别设置内存。根据运行时和操作系统,您可能会获得一些一致的特定于实现的模式,如零,特定填充,但您不应该依赖它 - malloc清零内存?
To set array to something particular you can either
要将数组设置为特定的值,您可以
- use
memset
that let you set memory to particular byte (0 seem to be what you are looking for) - use
for
loop to set values you want (i.e. if you want fillint
array with some non-zero number like 42) - track how many elements are used in the array instead filling whole array with defaults.
使用memset,你可以将内存设置为特定的字节(0似乎是你正在寻找的)
使用for循环来设置你想要的值(即如果你想要填充int数组有一些非零数字,如42)
跟踪数组中使用了多少元素,而不是使用默认值填充整个数组。