0

The program should be able to make an array of numbers from a text file which reads like this The data is given as this 123 2132 1100909 3213 89890

my code for it is

char a;
char d[100];
char array[100];
a=fgetc(fp) // where fp is a file pointer 

if (a=='')
{
d[count1]='/0';
strcpy(&array[count],d);
count=count+1;
memset(d,'\0',100)
count1=0;
}

else 
{
d[count1]=a;
count1=count1+1;
}
a=fgetc(fp);

i am getting segmentation fault now . want to store each number in the array so that i can do sorting on it

3
  • Please tell us more about 1) exactly what result you want and 2) what result you are currently getting and why you don't like it. Commented May 27, 2010 at 16:02
  • And the question is... ? Commented May 27, 2010 at 16:03
  • I have tagged it as homework. If not, we can revert it. Commented May 27, 2010 at 16:11

3 Answers 3

2

Your (first) problem is here:

d[count1]='/0';
strcpy(&array[count],d);

You have written '/0', which isn't what you think it is. Assuming you meant '\0' (a null char literal), then you appear to be trying to manually terminate the string d before calling strcpy(). The problem is that what actually gets written to d is not a null byte, and so d is not null-terminated, and then strcpy() goes off and starts reading random memory after it, and copying that memory into array, until either the reading or the writing ends up outside of memory you're allowed to access, and you get a segmentation fault.

You also have some confusion about that array is. It's declared as an array of 100 chars, but you're treating it like it's an array of strings. Perhaps you meant to declare it as char *array[100] ?

Sign up to request clarification or add additional context in comments.

Comments

2

Hmm...as a first approximation, to read a single number, consider using fscanf("%d", &number);. To store the numbers you read, you'll probably want to create an array of numbers (e.g., int numbers[100];). To read more than one number, use a loop to read the numbers into the array.

Sidenote: fscanf isn't particularly forgiving of errors in the input (among other things) so for production code, you probably want to read a string, and parse numbers out of that, but for now, it looks like you probably just need to get something that works for correct input, not worry about handling incorrect input gracefully.

Comments

0

Is this actually how the code is written?

In d[count1]='/0'; I think you mean d[count1]='\0'; (already mentioned by Daniel Pryden).

There is also a semicolon missing at the end of memset(d,'\0',100)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.