Erratic behavior with NULL '\0' when printing combinations of letters - c

My intention with this code is to print all possible combinations between the letters of the alphabet, **including single letters.**I wrote this part of a program from CS50x course (week 2 - crack)
I include the use of '\0' in order to get as well the single letters. It all works well until it starts working on the uppercase letters, after then it will skip '\0' once every two loops. The result is I am missing half of single uppercase letters and I have no idea why it acts this way.
This is an extract of the result I get (this part is correct, notice single letters 'g', 'h', 'i' all get printed):
Blockquote fZ g ga gb gc gd ge gf gg gh gi gj gk gl gm gn go gp gq gr gs gt gu gv gw gx gy gz gA gB gC gD gE gF gG gH gI gJ gK gL gM gN gO gP gQ gR gS gT gU gV gW gX gY gZ h ha hb hc hd he hf hg hh hi hj hk hl hm hn ho hp hq hr hs ht hu hv hw hx hy hz hA hB hC hD hE hF hG hH hI hJ hK hL hM hN hO hP hQ hR hS hT hU hV hW hX hY hZ i ia ib ic
But after a while it starts skipping letters (it prints 'W' and 'Y' but not 'X')
Blockquote VZ W Wa Wb Wc Wd We Wf Wg Wh Wi Wj Wk Wl Wm Wn Wo Wp Wq Wr Ws Wt Wu Wv Ww Wx Wy Wz WA WB WC WD WE WF WG WH WI WJ WK WL WM WN WO WP WQ WR WS WT WU WV WW WX WY WZ Xa Xb Xc Xd Xe Xf Xg Xh Xi Xj Xk Xl Xm Xn Xo Xp Xq Xr Xs Xt Xu Xv Xw Xx Xy Xz XA XB XC XD XE XF XG XH XI XJ XK XL XM XN XO XP XQ XR XS XT XU XV XW XX XY XZ Y Ya
This is the original code:
int main(void)
{
char abc[52] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
char xyz[3];
char null = '\0';
for (int i = 0; i < 52; i++)
{
xyz[0] = abc[i];
xyz[1] = null;
printf("%s ", xyz);
for (int j = 0; j < 52; j++)
{
xyz[1] = abc[j];
printf("%s ", xyz);
}
}
printf("\n");
}'''

With
xyz[1] = abc[j];
you overwrite the null terminator you just set.
Better to initialize the whole array to zero (the null terminator)
char xyz[3] = { '\0' };
Then you don't need to explicitly set a null terminator a second time for the inner loop.

OK, so I moved on to the next week of the course and they introduced an IDE which I used to try on this. As #Weather Vane points out, it works perfectly this time. So I assume the code was not entirely wrong, just somehow the previous sandbox on which I was compiling and running the program may be the problem here. Thanks to all who posted!

Related

MATLAB - Index in position 2 exceeds array bounds (must not exceed 1)

This code tries to solve 6 ODEs with 6 state variables [horizontal position (x1 and x2), altitude (x3), the true airspeed (x4), the heading angle (x5) and the mass of the aircraft (x6)] and 3 control inputs [engine thrust (u1), the bank angle (u2) and the flight path angle (u3)] by using Euler's Method.
Different flight maneuvers are performed for the specified time intervals.
Velocities.m, Cruise_Vel.m, Des_Vel.m, Thr_cl.m, Thr_cr.m, Thr_des.m, fuel_cl.m, fuel_cr.m, fuel_des.m,den.m,den_cr.m,den_des.m,drag.m,drag_cr.m,drag_des.m,lift.m,lift_cr.m,lift_des.m are functions in seperate tabs.
Main code is:
% Climb from h1=1100 [m] to h2=1600 [m] with α=5 flight path angle.
% Perform cruise flight for t=60 minutes.
% Turn with β=30 bank angle until heading is changed by η=270◦.
% Descent from h2=1600 [m] to h1=1100 [m] with ζ=4◦ flight path angle.
% Complete a 360◦ turn (loiter) at level flight.
% Descent to h3=800 [m] with κ=4.5◦ flight path angle.
% Aircraft Properties
W = .44225E+06; % .44225E+03 tons = .44225E+06 kg
S = .51097E+03; % Surface Area [m^2]
g0 = 9.80665; % Gravitational acceleration [m/s2]
% solving 1st order ODE using numerical methods
t0=0;
tend=3960;
h=0.05;
N=(tend-t0)/h;
t=t0:h:tend;
% Preallocations
x = zeros(6,length(t));
x1 = zeros(1,length(t));
x2 = zeros(1,length(t));
x3 = zeros(1,length(t));
x4 = zeros(1,length(t));
x5 = zeros(1,length(t));
x6 = zeros(1,length(t));
u1 = zeros(1,length(t));
u2 = zeros(1,length(t));
u3 = zeros(1,length(t));
C_D= zeros(1,length(t));
p = zeros(1,length(t));
Cl = zeros(1,length(t));
f = zeros(1,length(t));
dx1dt = zeros(1,length(t));
dx2dt = zeros(1,length(t));
dx3dt = zeros(1,length(t));
dx4dt = zeros(1,length(t));
dx5dt = zeros(1,length(t));
dx6dt = zeros(1,length(t));
% Initial conditions
x(:,1)=[0;0;3608.92;1.0e+02 * 1.161544478045788;0;W];
for i=2:length(t)
if and (t(1,i-1) >= 0,t(1,i-1)<60) % Climb from h1=1100 [m] to h2=1600 [m] with α=5 flight path angle.
x3 = linspace(3608.92,5249.3,79201);
x4 = Velocities(x3); % Changing speed [m/s]
x5 = 0; % Changing head angle [deg]
f = fuel_cl(x3); % Changing fuel flow [kg/min]
u1 = Thr_cl(x3); % Changing thrust [N]
u2 = 0; % Changing bank angle [deg]
u3 = 5; % Changing flight path angle [deg]
V_ver = x4*sin(u3); % Changing vertical speed [m/s]
C_D = drag(x3,x4); % Changing drag coefficient
Cl = lift(x3,x4); % Changing lift coefficient
p = den(x3); % Changing density [kg/m3]
elseif and (t(1,i-1) >= 60,t(1,i-1)<3660) % Perform cruise flight for t=60 minutes.
x3 = 5249.3;
x4 = Cruise_Vel(x3); % Changing speed [m/s]
x5 = 0; % Changing head angle [deg]
f = fuel_cr(x3); % Changing fuel flow [kg/min]
u1 = Thr_cr(x3); % Changing thrust [N]
u2 = 0; % Changing bank angle [deg]
u3 = 0; % Changing flight path angle [deg]
V_ver = x4*sin(u3); % Changing vertical speed [m/s]
C_D = drag_cr(x3,x4); % Changing drag coefficient
Cl = lift_cr(x3,x4); % Changing lift coefficient
p = den_cr(x3); % Changing density [kg/m3]
elseif and (t(1,i-1) >= 3660,t(1,i-1)<3720) % Turn with β=30 bank angle until heading is changed by η=270◦.
x3 = 5249.3;
x4 = Cruise_Vel(x3); % Changing speed [m/s]
x5 = 0:30:270; % Changing head angle [deg]
f = fuel_cr(x3); % Changing fuel flow [kg/min]
u1 = Thr_cr(x3); % Changing thrust [N]
u2 = 30; % Changing bank angle [deg]
u3 = 0; % Changing flight path angle [deg]
V_ver = x4*sin(u3); % Changing vertical speed [m/s]
C_D = drag_cr(x3,x4); % Changing drag coefficient
Cl = lift_cr(x3,x4); % Changing lift coefficient
p = den_cr(x3); % Changing density [kg/m3]
elseif and (t(1,i-1) >= 3720,t(1,i-1)<3780) % Descent from h2=1600 [m] to h1=1100 [m] with ζ=4◦ flight path angle.
x3 = linspace(5249.3,3608.92,79201);
x4 = Des_Vel(x3); % Changing speed [m/s]
x5 = 270; % Changing head angle [deg]
f = fuel_des(x3); % Changing fuel flow [kg/min]
u1 = Thr_des(x3); % Changing thrust [N]
u2 = 0; % Changing bank angle [deg]
u3 = 4; % Changing flight path angle [deg]
V_ver = x4*sin(u3); % Changing vertical speed [m/s]
C_D = drag_des(x3,x4); % Changing drag coefficient
Cl = lift_des(x3,x4); % Changing lift coefficient
p = den_des(x3); % Changing density [kg/m3]
elseif and (t(1,i-1) >= 3780,t(1,i-1)<3900) % Complete a 360◦ turn (loiter) at level flight.
x3 = 3608.9;
x4 = Cruise_Vel(x3); % Changing speed [m/s]
lon = [270 300 360 60 120 180 240 270];
x5 = wrapTo360(lon); % Changing head angle [deg]
f = fuel_cr(x3); % Changing fuel flow [kg/min]
u1 = Thr_cr(x3); % Changing thrust [N]
u2 = 0; % Changing bank angle [deg]
u3 = 0; % Changing flight path angle [deg]
V_ver = x4*sin(u3); % Changing vertical speed [m/s]
C_D = drag_cr(x3,x4); % Changing drag coefficient
Cl = lift_cr(x3,x4); % Changing lift coefficient
p = den_cr(x3); % Changing density [kg/m3]
elseif and (t(1,i-1) >= 3900,t(1,i-1)<3960) % Descent to h3=800 [m] with κ=4.5◦ flight path angle.
x3 = linspace(3608.92,2624.67,79201);
x4 = Des_Vel(x3); % Changing speed [m/s]
x5 = 270; % Changing head angle [deg]
f = fuel_des(x3); % Changing fuel flow [kg/min]
u1 = Thr_des(x3); % Changing thrust [N]
u2 = 0; % Changing bank angle [deg]
u3 = 4.5; % Changing flight path angle [deg]
V_ver = x4*sin(u3); % Changing vertical speed [m/s]
C_D = drag_des(x3,x4); % Changing drag coefficient
Cl = lift_des(x3,x4); % Changing lift coefficient
p = den_des(x3); % Changing density [kg/m3]
else
fprintf("A problem occured.");
end
dx1dt = x4 .* cos(x5) .* cos(u3);
dx2dt = x4 .* sin(x5) .* cos(u3);
dx3dt = x4 .* sin(u3);
dx4dt = -C_D.*S.*p.*(x4.^2)./(2.*x6)-g0.*sin(u3)+u1./x6;
dx5dt = -Cl.*S.*p.*x4./(2.*x6).*sin(u2);
dx6dt = -f;
x(1,i)= x(1,i-1) + h * dx1dt(1,i-1); %%%%%%%%% line 138 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
x(2,i)= x(2,i-1) + h * dx2dt(1,i-1);
x(3,i)= x(3,i-1) + h * dx3dt(1,i-1);
x(4,i)= x(4,i-1) + h * dx4dt(1,i-1);
x(5,i)= x(5,i-1) + h * dx5dt(1,i-1);
x(6,i)= x(6,i-1) + h * dx6dt(1,i-1);
end
tot=cell2mat(f); % Total fuel consumption during mission [kg/min]
Tot_fuel=sum(tot);
figure(1)
plot3(x1(:),x2(:),x3(:)); % 3D position graph
figure(2)
plot(t,x4(:)); % Vtas − Time graph
figure(3)
plot(t,V_ver(:)); % V_vertical − Time graph
figure(4)
plot(t,x5(:)); % Heading − Time graph
figure(5)
plot(t,x6(:)); % Mass − Time graph
figure(6)
plot(t,u1(:)); % Thrust − Time graph
figure(7)
plot(t,u2(:)); % Bank Angle − Time graph
figure(8)
plot(t,u3(:)); % Flight Path Angle − Time graph
fprintf('Total fuel consumption during mission is %.2f [kg]',Tot_fuel*tend/60);
The reason why I used 79201 sized array is length(t) = 79201.
And when I run:
Index in position 2 exceeds array bounds (must not exceed 1).
Error in forum (line 138)
x(1,i)= x(1,i-1) + h * dx1dt(1,i-1);
What should I do?
One of the functions in separate tabs is below, the rest is similar:
function [Vtas_cl] = Velocities(x3)
%%%%%%%%%%%%%%%%%%%% Constants %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Vcl_1 = 335; % Standard calibrated airspeed [kt]
Vcl_2 = 172.3; % Standard calibrated airspeed [kt] -> [m/s] (To find the Mach transition altitude)
Vcl_2_in_knots = 335; % Standard calibrated airspeed [kt] (To find the result in knots, if altitude is between 10,000 ft and Mach transition altitude)
M_cl = 0.86; % Standard calibrated airspeed [kt]
K = 1.4; % Adiabatic index of air
R = 287.05287; % Real gas constant for air [m2/(K·s2)]
Bt = - 0.0065; % ISA temperature gradient with altitude below the tropopause [K/m]
T0 = 288.15; % Standard atmospheric temperature at MSL [K]
g0 = 9.80665; % Gravitational acceleration [m/s2]
a0= 340.294; % Speed of Sound [m/s]
Vd_CL1 = 5; % Climb speed increment below 1500 ft (jet)
Vd_CL2 = 10; % Climb speed increment below 3000 ft (jet)
Vd_CL3 = 30; % Climb speed increment below 4000 ft (jet)
Vd_CL4 = 60; % Climb speed increment below 5000 ft (jet)
Vd_CL5 = 80; % Climb speed increment below 6000 ft (jet)
CV_min = 1.3; % Minimum speed coefficient
Vstall_TO = .14200E+03; % Stall speed at take-off [KCAS]
CAS_climb = Vcl_2;
Mach_climb = M_cl;
delta_trans = (((1+((K-1)/2)*(CAS_climb/a0)^2)^(K/(K-1)))-1)/(((1+(K-1)/2*Mach_climb^2)^(K/(K-1)))-1); % Pressure ratio at the transition altitude
teta_trans = delta_trans ^ (-Bt*R/g0); % Temperature ratio at the transition altitude
H_p_trans_climb = (1000/0.348/6.5)*(T0*(1-teta_trans)); % Transition altitude for climb [ft]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% End of constants
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
H_climb = x3; %%%%%% Input %%%%%%%%%%%%%%%%%%%
Vnom_climb_jet = zeros(1, length(H_climb));
for k1 = 1:length(H_climb)
if (0<=H_climb(k1)&&H_climb(k1)<1500)
Vnom_climb_jet(k1) = CV_min * Vstall_TO + Vd_CL1;
elseif (1500<=H_climb(k1)&&H_climb(k1)<3000)
Vnom_climb_jet(k1) = CV_min * Vstall_TO + Vd_CL2;
elseif (3000<=H_climb(k1)&&H_climb(k1)<4000)
Vnom_climb_jet (k1)= CV_min * Vstall_TO + Vd_CL3;
elseif (4000<=H_climb(k1)&&H_climb(k1)<5000)
Vnom_climb_jet (k1)= CV_min * Vstall_TO + Vd_CL4;
elseif (5000<=H_climb(k1)&&H_climb(k1)<6000)
Vnom_climb_jet(k1) = CV_min * Vstall_TO + Vd_CL5;
elseif (6000<=H_climb(k1)&&H_climb(k1)<10000)
Vnom_climb_jet (k1)= min(Vcl_1,250);
elseif (10000<=H_climb(k1)&&H_climb(k1)<=H_p_trans_climb)
Vnom_climb_jet(k1) = Vcl_2_in_knots;
elseif (H_p_trans_climb<H_climb(k1))
Vnom_climb_jet(k1) = M_cl;
end
Vcas_cl(k1) = Vnom_climb_jet(k1)* 0.514; % [kn] -> [m/s]
H_climb (k1)= H_climb(k1) * 0.3048; % [feet] -> [m]
K = 1.4; % Adiabatic index of air
R = 287.05287; % Real gas constant for air [m2/(K·s2)]
Bt = - 0.0065; % ISA temperature gradient with altitude below the tropopause [K/m]
deltaT = 0; % Value of the real temperature T in ISA conditions [K]
T0 = 288.15; % Standard atmospheric temperature at MSL [K]
P0 = 101325; % Standard atmospheric pressure at MSL [Pa]
g0 = 9.80665; % Gravitational acceleration [m/s2]
p0 = 1.225; % Standard atmospheric density at MSL [kg/m3]
visc = (K-1)./K;
T(k1) = T0 + deltaT + Bt * H_climb(k1); % Temperature [K]
P (k1)= P0*((T(k1)-deltaT)/T0).^((-g0)/(Bt*R)); % Pressure [Pa]
p (k1)= P(k1) ./ (R*T(k1)); % Density [kg/m^3]
Vtas_cl(k1) = (2*P(k1)/visc/p(k1)*((1 + P0/P(k1)*((1 + visc*p0*Vcas_cl(k1)*Vcas_cl(k1)/2/P0).^(1/visc)-1)).^(visc)-1)).^(1/2); % True Air Speed [m/s]
end
% Output
end
Index in position 2 exceeds array bounds (must not exceed 1).
This is an error that occurs when you are trying to access and element
that does not exist. For instance, if I initialize a variable of x
to be sized (3,1), then try to extract a value from index (4,4),
it will throw this error.
x = zeros(3,1)
y = x(4,4)+1; % ERROR
There is an issue with your indexing of the variable dx1dt at line 138. It is trying to access element (1,2) which does not exist when i=3.
At the beginning of your code, you have initialized the size of dx1dt to a size of (1, 79201):
dx1dt = zeros(1,length(t));
However, when you compute each value, you overwrite the size of this array to (1,1):
dx1dt = x4 .* cos(x5) .* cos(u3);
So when i=3, the following indexes are called, and dx1dt does not have any value placed in the (1,2) location. This will throw you an error that the index exceeds the bounds.
x(1,i)= x(1,i-1) + h * dx1dt(1,i-1);
x(1,3)= x(1,2) + h * dx1dt(1,2);
The question is: Is the variable of dx1dt supposed to be an array of size (1,79201) or simply a double?

Why does printing a 2D array of characters give garbage values?

I am implementing a function that prints a 2D array of characters only using a double-pointer and pointer notation. When I run the code, it prints a bunch of garbage values in the format I want instead of the correct characters.
My professor instructed me not to use arr[row][col], instead, I must access it using ((arr+i)+j) or similar
This is a project for a class and I can't change any of the code outside of this function. The characters are meant to be formatted like a word search puzzle. The arguments passed to my function are char** arr, int size.
This is my function:
for(int i = 0; i < size; i++){
printf("%c %c %c %c %c %c %c %c %c %c %c %c %c %c %c\n", *(arr+i), *(arr+i)+1, *(arr+i)+2, *(arr+i)+3, *(arr+i)+4, *(arr+i)+5, *(arr+i)+6, *
(arr+i)+7, *(arr+i)+8, *(arr+i)+9, *(arr+i)+10, *(arr+i)+11, *(arr+i)+12, *(arr+i)+13, *(arr+i)+14 ); }
Expected output:
W D B M J Q D B C J N Q P T I
I R Z U X U Z E A O I O R T N
M N Z P L R N H L Y L X H M D
M Y E K A I D P I U L Y O W I
A O A B A R K U F V I H L A A
L O N M R X K I O J N A V R N
A E P T A A R A R T O W A I A
S U C Z A U S I N A I A L Z V
K O T A O N R K I S S I A O N
A H X S V K A I A E A I B N E
U D S X N X C C D W G S A A V
O I S D W L E J N J T X M H A
M O X W T N H Q D X O Q A Q D
R U U V G E O R G I A Q V D A
V F L O R I D A L G L W O X N
Actual output:
░ ▒ ▓ │ ┤ ╡ ╢ ╖ ╕ ╣ ║ ╗ ╝ ╜ ╛
≡ ± ≥ ≤ ⌠ ⌡ ÷ ≈ ° ∙ · √ ⁿ ² ■
0 1 2 3 4 5 6 7 8 9 : ; < = >
P Q R S T U V W X Y Z [ \ ] ^
p q r s t u v w x y z { | } ~
É æ Æ ô ö ò û ù ÿ Ö Ü ¢ £ ¥ ₧
░ ▒ ▓ │ ┤ ╡ ╢ ╖ ╕ ╣ ║ ╗ ╝ ╜ ╛
╨ ╤ ╥ ╙ ╘ ╒ ╓ ╫ ╪ ┘ ┌ █ ▄ ▌ ▐
≡ ± ≥ ≤ ⌠ ⌡ ÷ ≈ ° ∙ · √ ⁿ ² ■
0 1 2 3 4 5 6 7 8 9 : ; < = >
P Q R S T U V W X Y Z [ \ ] ^
└ ┴ ┬ ├ ─ ┼ ╞ ╟ ╚ ╔ ╩ ╦ ╠ ═ ╬
` a b c d e f g h i j k l m n
If arr is really a char**, then you need to dereference twice to get a char.
So, in your statement, arr+i is another char**, pointing at a char* i steps further along from the one arr points at. Hopefully arr points at the beginning of an array of char* at least size long.
Now *(arr+i) dereferences it, fetching the char* pointed to by arr+i, giving you a char*.
Now *(arr+i)+7, for example, is another char*, pointing at a char 7 steps further along from the one *(arr+i) points at. Hopefully *(arr+i) points at the beginning of an array of char at least 15 long.
But you don't dereference it, so you're attempting to print the value of the pointer (i.e. the address it holds), not the value it points to (the char).
Try *(*(arr+i)+7).

How to get character like go down stairs in Google Sheets

I want to get a character from string but the path is like going downstairs in Google Sheets
The string is like:
y C I 6 8 V 5
~5 Z n I L w f
V ~s i w J d _
o R ~4 2 i v f
9 ^ j ~h r u #
Z y Q 7 ~1 u a
T t z u _ ~! Q
G Y n r * t ~^
J A l v F j d
a 2 l - y O B
h B w % n a 4
M t _ P D W a
And expect the output is:
5 s 4 h 1 ! ^
I put ~ in front of the character that demo the path I want to get.
The logic is I will find the first column which cell is 5 and then get start from that cell.
Example sheet link
https://docs.google.com/spreadsheets/d/1UQEGEl_rqAMFePDAGoueTI47xF8T_DyrvJ3de5pkLRA/edit#gid=306981885
I tried auto-fill but it could only incrementally either row or column. And I hope to incremental both row and column.
={INDIRECT("A"&MATCH(5, A1:A14, 0)),
INDIRECT("B"&MATCH(5, A1:A14, 0)+1),
INDIRECT("C"&MATCH(5, A1:A14, 0)+2),
INDIRECT("D"&MATCH(5, A1:A14, 0)+3),
INDIRECT("E"&MATCH(5, A1:A14, 0)+4),
INDIRECT("F"&MATCH(5, A1:A14, 0)+5),
INDIRECT("G"&MATCH(5, A1:A14, 0)+6)}
for a large scale scenario you can use this one and drag it to the right:
=INDIRECT(ADDRESS(MATCH(5, $A1:$A14, 0)+COLUMN()-1, COLUMN(), 4))
You can also do it with an array formula if you want to:
=ArrayFormula(hlookup(column(A2:G13),{column(A2:G13);A2:G13},match(5,A2:A13,0)+column(A2:G13)))

summing numerical data using for loop

I have this data file, for Matlab:
A 12 E 24
B 34 F 67
C 23 G 88
D 56 H 33
I would like to use a for loop to find the sum of the numbers in the 2nd and 4th column. I would really appreciate the help. Thank you.
This is what I have so far
`fid = fopen('patwts.dat')
if fid == -1
disp ('File open not successful')
else
disp ('File open is successful')
mat = textscan(fid,'%c %f %c %f')
[r c] = size(mat)
for i = 1:r
for j = 1:c
sum(j)
end
end
fclose(fid)
end`

Cropping a .ppm file in C

I'm working on a C program that crops .ppm files from a starting point pixel (x,y) (top left corner of cropped image) to an end point pixel (x+w,x+h)(bottom left corner of cropped image).
The data in .ppm files is of the following format:
r g b r g b r g b r g b r g b r g b
r g b r g b r g b r g b r g b r g b
r g b r g b r g b r g b r g b r g b
r g b r g b r g b r g b r g b r g b
Is there a simple way, wich avoids the use of 2 dimensional arrays, to do this using scanf()?
One easy way would be to simply keep track of your pixel coordinate as you read the file in. If you're currently in the crop rectangle, store the pixel; otherwise, skip it.
If you want to get more fancy: figure out the byte offset for the start of each row, seek to it, then read in the whole row.
Warning, some pnm files are in binary mode (they differ by magic number in the beginning of the file contents).
Maybe lookup the sources of pnmcrop would help?

Resources