I am having the following problem. I have created a char array which represents a series of characters and numbers - this was designed to model a string read or got from a text file. I wish to then search this string using the "search" function defined below, pulling out only the numbers before 'H' and assigning to a separately defined integer array. I find when I use gdb, this function works fine. However, only part of the array is ever returned - the first 8 elements to be exact. Would anyone please be able to explain why this is from looking at the code below?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void search(char buffer[], int size, int array[]);
int main (void)
{
char buffer[1000];
memset(buffer, 0, sizeof(buffer));
buffer[0] = 2;
buffer[1] = 'H';
buffer[2] = 3;
buffer[3] = 'H';
buffer[4] = 6;
buffer[5] = 'H';
buffer[6] = 4;
buffer[7] = 'H';
buffer[8] = 6;
buffer[9] = 'H';
buffer[10] = 7;
buffer[11] = 'H';
buffer[12] = 11;
buffer[13] = 'H';
buffer[14] = 12;
buffer[15] = 'H';
buffer[16] = 17;
buffer[17] = 'H';
int* array ;
array = malloc(sizeof(buffer) * sizeof(int));
search(buffer, sizeof(buffer), array);
for(int i = 0, n = sizeof(array); i < n; i++)
{
printf("array[%d] = %d\n", i, array[i]);
}
free(array);
}
void search(char buffer[], int size, int array[])
{
int position = 0;
for (int i = 0; i < size; i++)
{
if(buffer[i] == 'H')
{
*(array + position) = buffer[i-1];
position++;
}
}
}
The compiler outputs the following:
array[0] = 2
array[1] = 3
array[2] = 6
array[3] = 4
array[4] = 6
array[5] = 7
array[6] = 11
array[7] = 12
which as can be seen is missing the ninth position in the array - value 17. In fact, if I fgets into a buffer a much bigger set of numbers and 'H's, I am always returned an array of size 8. Why is this? Any help would be much appreciated.
sizeof(buffer)tosearch(), NOT the number of elements you have used - 18.buffer[i-1];is Undefined Behaviour wheni == 0sizeof(buffer)means number of elements of thearray.buffer[i-1];if(buffer[i] == 'H')i == 0, will not be access to thebuffer[i-1].