On 16 Apr 2003 00:23:54 GMT
Quote:
> I am new to C and trying to write a little utility programme to
> manipulate records in a file. I have written some code to get input
> on the number of fields in a record and their size. I want to
> dynamically declare an array to hold the field sizes and have used
> realloc() in the code below but have a strong feeling that I am doing
> something wrong (i.e. I could be writing over other data). Could do
> with an opinion. (I have removed the indents to avoid too many split
> lines hope this does not cause a problem.
Please don't remove all indenting, it makes it MUCH harder to read. In
lines being split is a problem then reformat the code manually splitting
the lines as required, make sure it still compilers, then submit it.
Quote:
> /*********************************************/
> #include <stdio.h>
> #include <stdlib.h>
> int main(int argc,char *argv[]) {
> unsigned short int i, no_fields, fieldsize[1], x = 0; // x is for
^^^^^^^^^
unsigned short *temp, *fieldsize=NULL;
/* You can't realloc an array, only space that was allocated by realloc
or malloc */
Quote:
> debuging only
// style comments are a pain when posting to Usenet.
Quote:
> /*if(argc != 3){
> printf("\nIncorrect usage:\n\nCorrect usage = exe filename
> [InputFilename] [OutputFilename]\n\nTry again please\n");
> exit(0);
> }*/
> printf("\nHow many fields are there in a record?");
> scanf("%d",&no_fields); printf("\n");
> realloc(fieldsize,sizeof(unsigned short int)*no_fields);
/* Realloc returns a pointer to the memory on success or NULL on
failure, it does not EVER modify its parameters. */
temp=realloc(fieldsize, fields * sizeof *fieldsize);
if (temp==NULL) {
/* handless failed realloc */
Quote:
}
fieldsize=temp;
/* I've not checked the rest. However, I suggest you read up further
on memory allocation. */
// <snip rest of code>
--
Mark Gordon
Paid to be a Geek & a Senior Software Developer
Currently looking for a new job commutable from Slough, Berks, U.K.
Although my email address says spamtrap, it is real and I read it.
--