0

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

Killer_B
  • 61
  • 4
  • 9
  • the array is this int* scores = malloc(51 * sizeof(int)); – Killer_B May 03 '15 at 01:42
  • Assuming with "space" you refer to the `' '` character: Filling an `int` with such would lead to the `int` carrying the value of `538'976'288` (aka `0x20202020`) assuming it is a 32bit `int`. Are sure you want this? – alk May 03 '15 at 07:54

2 Answers2

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().

int* scores = calloc(51 * sizeof(int));
memset(scores, ' ', 50*sizeof(int));
// no longer needed
// scores[50] = '\0';
Algonaut
  • 349
  • 4
  • 7
0

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?.

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 fill int array with some non-zero number like 42)
  • track how many elements are used in the array instead filling whole array with defaults.
Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179