1

I'm making a program capable to use some statistics functions. For that, I used malloc for the array that the numbers of the sample to operate on, as I want it's size to be based on users' input. It's not the first time I do this, and it worked fine, but this time I can't set the size as needed and I can't find the flaw.

Below is the necessary code for the creation and printing of the array, skipping main() as it only runs the functions.

int *sample;

int MakeSample()
{
    int sampleSize;
    int valueN;

    printf("Enter size of your sample: ");

    scanf("%d", &sampleSize);

    sample = malloc(sampleSize * sizeof(int));

    for (int i = 1; i <= sampleSize; i++)
    {
        printf("Enter value #%d: ", i);

        scanf("%d", &valueN);

        sample[i - 1] = valueN;
    }
}

int PrintSample()
{
    for (int k = 1; k <= sizeof(sample); k++)
    {
        printf("Value #%d: %d\n", k, sample[k - 1]);
    }
}

If I enter size 1 for the array, that should be the amount off values asked for and printed, instead I got this:

Value #1: 1
Value #2: 0
Value #3: 0
Value #4: 0
Value #5: 0
Value #6: 0
Value #7: 133057
Value #8: 0
AlexaN
  • 15
  • 3
  • Maybe you should try to print the array in your function, so you can use your sampleSize. In main function, just call the function. – yupe Oct 15 '19 at 15:53
  • Good idea, but the program should do all operations, including printing the array, by separate. sampleSize could also help for future operations like the average where it divides another value, what if I make it global? I could solve the problem here and keep both functions. – AlexaN Oct 15 '19 at 15:56
  • The global variable is declared out of the function, you can try to merge two functions into one. – yupe Oct 15 '19 at 16:06
  • Ok, thanks for the help. XD – AlexaN Oct 15 '19 at 16:07

1 Answers1

1

sample is an int pointer; sizeof(sample) is always 8. You need to store the sampleSize variable somewhere and use that instead - there's no way for your program to know how big your array is otherwise, since it's not really an "array", it's a pointer to memory that happens to hold an array.

Nick Reed
  • 4,989
  • 4
  • 17
  • 37