-
Dynamic Array
In this part of my program i -obviously- want to create a dynamic array.
But somewhere there is a problem(the array is allocacated but not returned), can anyone help me, is there any problem with the pointers?
I have a warning into the main that A hasn't been initialized
Code:
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
int FillStruct(int A[]);
int main(void){
int megethos,*A,epilogi;
srand(time(NULL));
do{
printf("--------------------------\n Main Menu\n--------------------------\n");
printf("Give a choice: ");
scanf("%d",&epilogi);
switch (epilogi) {
case 1:
megethos=FillStruct(A);
break;
.
.
.
.
.
}
return 0;
}
int FillStruct(int A[])
{
int type,zevgaria,thesi,temp,i,megethos;
printf("Please give the length of the struct:");
scanf("%d",&megethos);
A=(int*)calloc(megethos,sizeof(int));
if (A==NULL){
printf("ALLOCATING MEMMORY ERROR");
exit(1);
}
return megethos;
}
-
>I have a warning into the main that A hasn't been initialized
This is correct. A new address is given to A in function FillStruct, but since C passes arguments by value, this new address is never seen once the function returns to main(). Try this instead.
Code:
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
int FillStruct(int **A);
int main(void){
int megethos,*A,epilogi;
srand(time(NULL));
do{
printf("--------------------------\n Main Menu\n--------------------------\n");
printf("Give a choice: ");
scanf("%d",&epilogi);
switch (epilogi) {
case 1:
megethos=FillStruct(&A);
break;
.
.
.
.
.
}
return 0;
}
int FillStruct(int **A)
{
int type,zevgaria,thesi,temp,i,megethos;
printf("Please give the length of the struct:");
scanf("%d",&megethos);
*A = calloc(megethos,sizeof(**A));
if (*A==NULL){
printf("ALLOCATING MEMMORY ERROR");
exit(1);
}
return megethos;
}
-
Thanks, you are right! And if i want to refer to the array in that function, i have to write *A[]??
For example why something like that is wrong??
Code:
int FillStruct(int **A)
{
int type,zevgaria,thesi,temp,i,megethos;
printf("Please give the length of the struct:");
scanf("%d",&megethos);
*A = calloc(megethos,sizeof(**A));
if (*A==NULL){
printf("ALLOCATING MEMMORY ERROR");
exit(1);
}
for(i=0;i<megethos;i++) *A[i]=i ;
return megethos;
}
I don't have any errors but it can't be executed either
-
>And if i want to refer to the array in that function, i have to write *A[]??
Almost. You need (*A)[]:
Code:
for(i=0;i<megethos;i++) (*A)[i]=i ;