Hi guys,
I would like to define the count of an integer array but I got stuck in that. I increased the size of the array dynamically using the possibilities of 'realloc' method.
May I mess up the number of the array with these reallocation ? Or is it an incorrect usage of 'realloc' ?
Any help would be appreciated
You can see my simplified code:
Code:
#include<stdio.h>
int main()
{
char myString[16]="cows_cats_chicks";
int c_LetterCounter = 0;
int* c_LetterPosArray = (int*)malloc(0); // the array which stores the positions of the 'c' letters
int index=0;
for (index=0;index<strlen(myString); index++)
{
if (myString[index] == 'c')
{
c_LetterCounter++;
c_LetterPosArray = realloc(c_LetterPosArray, c_LetterCounter*sizeof(int));
c_LetterPosArray[c_LetterCounter-1] = index;
printf("The current index of the 'c' letter: %d\n", c_LetterPosArray[c_LetterCounter-1]);
}
}
// just an example, the array isn't empty
printf("The 2nd position of 'c' letter in the 'cows_cats_chicks' string: %d\n", c_LetterPosArray[1]);
int len = sizeof(c_LetterPosArray) / sizeof(int);
printf("The size of the integer array: %d\n", len);
int len2 = sizeof(c_LetterPosArray) / sizeof(c_LetterPosArray[0]);
printf("The size of the integer array with different calculation: %d\n", len2);
getchar();
}
But that simple array size definition work very well in static arrays:
Code:
int arr[] ={1,2,3,4,3,3,3};
int len = sizeof(arr) / sizeof(int);
Very thanks for your help!