This is my program, the part I'm having trouble with is in red:
#include<stdio.h>
int* cheese(void);
int main()
{
int n, freq[18], *pointer, i;
printf("Frequency \n");
for (n = 0; n < 18 ; n++)
{
if (n < 9)
freq[n] = (n+1)*100;
else
freq[n] = (n - 8)*1000;
}
for (n=0; n<18; n++)
{
printf("%4d \n", freq[n]);
}
pointer = cheese();
for(i=0; i<18; i++)
printf("%d \n", *(pointer + i));
return(0);
}
int* cheese(void)
{
int n, array[18];
for(n=0; n<17; n++)
{
array[n] = n;
}
return(array);
}
My issue is in the function "cheese" I have created an array of 18 integers. I want to return the pointer to the first element of the array back to the pointer variable "pointer" in main. I can print individual element values by returning a pointer but when it comes to printing out all 18 as a for loop it won't work. It prints out a list of random numbers instead. Seeing it can print out individual elements fine I don't see why it can't do the loop. Could anyone shed light on this?
#include<stdio.h>
int* cheese(void);
int main()
{
int n, freq[18], *pointer, i;
printf("Frequency \n");
for (n = 0; n < 18 ; n++)
{
if (n < 9)
freq[n] = (n+1)*100;
else
freq[n] = (n - 8)*1000;
}
for (n=0; n<18; n++)
{
printf("%4d \n", freq[n]);
}
pointer = cheese();
for(i=0; i<18; i++)
printf("%d \n", *(pointer + i));
return(0);
}
int* cheese(void)
{
int n, array[18];
for(n=0; n<17; n++)
{
array[n] = n;
}
return(array);
}
My issue is in the function "cheese" I have created an array of 18 integers. I want to return the pointer to the first element of the array back to the pointer variable "pointer" in main. I can print individual element values by returning a pointer but when it comes to printing out all 18 as a for loop it won't work. It prints out a list of random numbers instead. Seeing it can print out individual elements fine I don't see why it can't do the loop. Could anyone shed light on this?