Tuesday, July 14, 2009

I have c++ problem here is the function and its error how can I change my function?

void codfile(int *a,int n,int codlength)


{


const int memory=n*codlength/8;


int finalCod [memory]={0};


int k=0,fptr=0,cptr=0;


for(int i=0;i%26lt;n;i++)


{


int temp=a[i];


while(cptr%26lt;codlength)


{


if(fptr==8){ fptr=0;


k++;


}


finalCod [k]=finalCod[k] | temp/2;


finalCod[k]%26gt;%26gt;1;


temp/=2;


cptr++;


fptr++;


}


error in line 4: constant expression required

I have c++ problem here is the function and its error how can I change my function?
The statement


int finalCod [memory]={0};


is illegal because "memory" is a variable.


You need dynamic memory allocation:


either


int *finalCod = new int[memory];


or


int *finalCod = calloc( memory, 1 );


Do not forget to free the memory: for "new" use "delete", for "calloc" use "free()".
Reply:Yeah, what the heck is {0}?


You mean 0? Or 0th element of some array?
Reply:the code seems fine to me. chk whether the main program which generates a function call to codfile changes teh value of codlength? is codlength of type const?? u can try doing two things to remove ther error....first is directly initialize teh array to NULL and second u may try removing the const keyword.
Reply:The error is in this line:


const int memory=n*codlength/8;





memory is a const type. You cannot decide what goes into a constant type at run time. It has to be pre-decided.
Reply:Yeah, just remove const in line 3. The reason why it can't work is because you would be changing the value of memory every time you call the function, so just get rid of const. Or maybe in order for your array to work (int finalCod) with memory, it has to be also constant. So try getting rid of const when declaring memory.





Good Luck
Reply:the problem with ur function is that ur allocating memory statically without knowing exactly how much memory to allocate. this is not possible in c++. try the same thing dynamically using the 'new' operator.for eg int n=new int[];


No comments:

Post a Comment