IT计算机 primitive(原始的)_第1页
IT计算机 primitive(原始的)_第2页
IT计算机 primitive(原始的)_第3页
IT计算机 primitive(原始的)_第4页
IT计算机 primitive(原始的)_第5页
已阅读5页,还剩89页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Chapter6

Cb/XCA,,S叶,Pro0grammingD

DataTypesLanguages

SIXTHEDITION

RobertW.Sebesta

PEARSON

Afklison

Copyrightc2004PiurwaAddHon-Wrdry.»MIright*mrnvd.ISBN0-321-19362-8

Chapter6Topics

•Introduction

•PrimitiveDataTypes

•CharacterStringTypes

•User-DefinedOrdinalTypes

•ArrayTypes

•AssociativeArrays

•RecordTypes

•UnionTypes

•PointerTypes

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-2

Introduction

•ThisChapterintroducestheconceptof

adatatypeanddiscusses:

-Characteristicsofthecommonprimitive(原始的)

datatypes.

-Characterstrings

一Userdefineddata-types

-Designofenumerations(歹u聚)andsub-rangedata

types

-Designofstructureddatatypesincludingarrays,

records,unionsandsettypes.Heap堆稹

在相郝信者存军元中存放资料,

-Pointersandheapmanagement很像一槿堆叠操作。

但是,堆稹指上票保持指向

堆稹的第一彳固罩元,而不是

下一他可用的堆叠罩元。

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-3

DataType

•Adatatypedefinesacollectionofdataobjects

andasetofpredefinedoperationsonthose

objects

•EveryPLneedsavarietyofdatatypesinorder

tobettermodel/matchtheworld

•Moredatatypesmakesprogrammingeasierbut

toomanydatatypesmightbeconfusing

•Whichdatatypesaremostcommon?Which

datatypesarenecessary?Whichdatatypesare

uncommonyetuseful?

•HowaredatatypesimplementedinthePL?

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-4

EvolutionofDataTypes

•FORTRANI

-INTEGER,REAL,arrays

•COBOL

-Programmerscouldspecifyaccuracyofdecimal

-Introducedstructureddatatypesforrecords

•PL/I

-Extendedaccuracyspecificationtointegerandfloating­

point

•ALGOL68

-User-defineddatatypes

•Ada83

-Usercancreateuniquetypesforeveryclassofvariables

andthesystemenforces渤行)theuniquenessofthe

types.

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-5

Descriptors

•Adescriptoristhecollectionofattributes

ofavariable

•Inanimplementation,adescriptoristhe

collectionofmemorycellsthatstore

variableattributes(燮数的腐性)

-Ifallattributesarestatic,thedescriptoris

requiredonlyatcompiletime

-Ifattributesaredynamic,partorallofthe

descriptormustbepresentduringexecution

-Inallcases,descriptorsareneededfor

•Typechecking

•Allocationanddeallocation信己意||的配置典解除)

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-6

EvolutionofDataTypes

•DesignIssuesforalldatatypes:

-Whatisthesyntaxofreferencestovariables?

一Whatoperationsaredefinedandhowarethey

specified?

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-7

Primitivedatatypes

•Aprimitivedatatypeisonethatisnotdefinedin

termsofothertypes

•Often,primitivetypesareareflectionofthe

underlyinghardware:

-Integer

-Floatingpoint

•Otherprimitivetypesrequirealittlenon-hardware

supportfortheirimplementation,Majorcategories

include

-Numeric(数彳直)

-Boolean(布林彳直)

-Character(字元)

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-8

PrimitiveDataTypes

.:-Integer:ShortInt,Integer;LongInt(etc)

:-FloatingPoint:Real,DoublePrecision

Storedin3parts,signbit,exponentand

mantissa(seefig6.1)

-Decimal:BinaryCodedDecimal,BCD

(COBOL,C#,2digitsperbyte)

usedinbusinesslanguageswithasetdecimal

fordollarsandcents

-Boolean:(TRUE/FALSE,1/0,YES/NO)

':-Character:UsingEBCDIC,ASCII,UNICODE,

etC.Mantissa尾数

由已知浮黑占数中的最高有效数位

系且成的定黑占数。浮黑占表示法中,

指一数值的小数部分。封数表示

法中,指非负值的小数部分。

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-9

Numerictypes

•Integer:ShortInt,Integer,LongInt(etc)

-Almostalwaysanexactreflectionofhardware

•Twoscomplement件甫敷)tosavenegativeintegers,

whichisconvenientforadditionandsubtraction.

Intwos<omplementnotation,therepresentationofa

negativeintegerisformedbytakingthelogical

complementofthepositiveversionofthenumber

andaddingone.

•Chas8differentintegertypesbycombining

-char,short,int,long

一signedandunsigned

•AdaallowsSHORTINTEGER,INTEGER,LONG

-Somelanguagessupportintegersofunlimited

magnitude(implementedinsoftware)

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-10

Numerictypes

Floating-point:Real,DoublePrecision

-Storedin3parts,signbit,exponentandmantissa(尾数)

-Modelrealnumbers,butareonlyapproximations

-Valuesaredefinedintermsofprecisionandrange

•Precisionistheaccuracyofthefractionalpart(小数部份)

•Rangeisacombinationoftherangeoffractionsand

exponents

•Adaexamples:

typeSPEEDisdigits7range0.0..1000.0;

typeVOLTAGEisdelta0.1range-0.0..5.0;

-Hardwaresupport:IEEEFloating-Point

Standard754:

•Singleprecision:32bits

-Signbit,8-bitexponent,23bitsignificand

•Doubleprecision:64bits

-Signbit,11-bitexponent,52bitsignificand

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-11

IEEEFloatingPointStandard

•Singleprecision:32bitrepresentationwith1bit

sign,8bitexponent,23bitmantissa

•Doubleprecision:64bitrepresentationwith1bit

sign,11bitexponent,52bitmantissa

8bits23bits

ExponentFraction

tSignbit

Mantissa尾数

(a)由已知浮黑占数中的最高有效数位

系且成的定黑占数。浮黠表示法中,

指一数值的小数部分。卦数表示

,法中,指非负值的小数部分。

11bits52bits

ExponentFraction

tsignbit

(b)

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-12

Numerictypes

•Decimal(十迤制)

-Usedmostlyforbusinessapplications

-Storesafixednumberofdecimaldigits,withthe

decimalpointatafixedposition

-Decimaldigitsarecoded(BinaryCodedDecimal,BCD

with2digitsperbyte,e.g.COBOL,C#)

-Arecapableofpreciselystoringdecimalvalueswithina

restrictedrange,especially,usedinbusinesslanguages

withasetdecimalfordollarsandcents

-Operationsaredoneinhardwareonmachinesthat

supportit;insoftwareonthosethatdonot

-ExamplefromPL/I:

DCLPAYRATEFIXEDDECIMAL(7,2);

-Advantage:accuracy

-Disadvantages:\\mtedrange,wastesmemory

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-13

BooleanTypes

•Simplestofalltypes

•Rangeofvalueshasonly2elements,trueand

false

•IntroducedinALGOL60

•Couldberepresentedasasinglebit,butmost

oftenasabyte(thesmallestefficiently

addressablecellofmemory)

•CdoesdonotincludeaBooleantype;instead,

numericexpressionsareusedasconditionals

•Advantage:readability

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-14

CharacterStrings

•Charactersareanotherprimitivedatatypewhichmapeasily

intointegers.Characterdataarestoredasnumericcodings

-ASCII

•8-bitallows256characters

•Inadequate(不遹)forglobalcommunication

-Unicode

•16-bitallows655536characters

•Includescharsctersfrommostoftheworld'snatural

languages

•Neededascomputersbecomelesseurocentric(西方的)to

representthefullrangeofnon-romanalphabetsand

pictographs(象形文字).

•Javawasthefirstwidely-usedlanguagetousetheUnicode

characterset

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-15

Characterstringtypes

•Valuesareasequenceofcharacters

•Designissues:

-Ischaracterstringaprimitivetypeorjustaspecial

kindofarray?

-Isthelengthofcharacterstringobjectsstaticor

dynamic?

•Operationsoncharacterstrings:

-Assignment

-Comparison(=,>,etc.)

-Concatenatione.g.(Ada)N:=N1&N2(字串结合)

-Substringreferencee.g.(Ada)N(2..4)

-Patternmatching

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-16

CharacterstringsinAda

-STRINGisasomewhatprimitivetype

-STRINGisatypethatispredefinedasaone­

dimensionalarrayofCHARACTERelements:

S:STRING(l.-lO);

一Operationsinclude

•Substringreference:S(1..3)="Bob";

•Concatenation:S:="Bob"&"Alooga";

•Comparison:=,/=,<,<=,>,>=

-StringshavefixedlengthinAda

Concatenation512置

按规定的次序把雨他I字串结合篇一彳固

字串的一槿操作,所横成字串的畏度

等於甬彳固字串畏度之和。

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-17

Characterstrings

inCandC++

一Notaprimitivetype

-chararraysstorecharacterstrings

I一Stringsareterminatedby、\0'->stringshave

limiteddynamiclength

-Thestandardlibrarystring.hincludesa

collectionofstringoperations,whichinclude

•strlen(stringlength)

■MffX•strcat(stringconcatenation)

•strcmp(stringcomparison)

•strcpy(stringcopy)

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-18

CharacterstringsinJava

一Stringsareimplementedby2classes

•String—valuesareconstantstrings

•StringBuffer—valuesarechangeable

一Objectswhichareimmutable(tochangethe

length,youhavetocreateanewstringobject)

and+istheonlyoverloadedoperatorfor

string(concat),nooverloadingfor<,>,etc

一Operationsareprovidedviaclassmethods:

一Example:

Stringsi,s2,s3;

si="BobAlooga”;

s2=si+)Jr/7;

s3=sl.substring(0,3);

intp=sl.indexOfCAK');//p=4

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-19

Characterstringsinothers

•Perl

-Patternsaredefinedintermsofregularexpressions

providingaverypowerfulfacility!

-Patternforidentifier:/[A-Za-z][A-Za-z\d]+/

-Patternfornumericliteral:/\d+\.?d*|\.\d+/

•SNOBOL4

-Theultimatestringmanipulationlanguage

-Stringisaprimitivetype

-Therearemanystringmanipulationoperations,

includingegborage信辛翥的)pattern-matching

•StringsinPerl,LISPandSNOBOL4have

dynamiclength.

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-20

Characterstringsinothers

•FORTRAN77/90,COBOL,Ada-static

lengthstrings

e.g.InFORTRAN90

CHARACTER(LEN=15)NAME;

•PL/I,Pascal-variablelengthwithstatic

fixedsizestrings

•Somelanguages,e.g,Snobol,PerlandTel,

haveextensivebuilt-insupportforstrings

andoperationsonstrings.

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-21

Evaluationofcharacterstring

•Characterstringsareimportanttothe

writabilityofalanguage.

•Dealingwithstringsasarraysmore

cumbersome(黄隹虑理的)thandealingwitha

primitivestringtype.

•Ifimplementedasaprimitivetypewith

staticlength,theyareinexpensive.Thus,

itisdifficulttojustifytheiromission.

•Dynamic-lengthstringsprovideadditional

flexibility,butaremoreexpensiveto

implement.

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-22

Implementingcharacterstrings

•Staticlengthstrings

-Requireadescriptoronlyatcompiletime:

•Length(incharacters)

•Address(ofthefirstcharacter)

•Limiteddynamiclengthstrings

-Needaruntimedescriptorthatstores:

•Fixedmaximumlength

•Currentlength

•Addressoffirstcharacter

-CandC++stringsdonotrequirearun-timedescriptor

becausetheendofastringismarkedwiththenull

character

•Neitherstaticlengthnorlimiteddynamiclength

stringsrequireruntimestoragemanagement.

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-23

descriptorcharacterstrings

Limiteddynamicstring

Maximumlength

Currentlength

Address

Compile-timeRun-timedescriptor

descriptorforstaticforlimiteddynamic

stringsstrings

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-24

Implementingcharacterstrings

•Dynamic-lengthstringsrequiremorecomplex

storagemanagement.

•2approaches:linked时速系吉串列,^表(二讪海.)

_Linkedlist一系且资料元素目的集合‘其J嗔序排列方法是使

-每他项目包含下一偃P嗔目在重月窗存信者器中的位址。

•Advantage:

-Allowsnewlyrequiredcellstocomefrom

anywhereintheheap

•Drawbacks(不利脩件):

-Storageoccupiedbylinks

-Someoperationsareslowedbythisrepresentation

-Storecompletestringsinadjacentcells(相鄢倨者存格)

•Advantage:

-Operationsarefaster

•Drawbacks:

-Whenstringgrowstheruntimesystemmustfinda

largeenoughblockofadjacentcells

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-25

User-definedordinaltypes

•Anordinaltypeisoneinwhichtherangeof

possiblevaluescanbeeasilyassociatedwiththe

setofnonnegativeintegers

•Twocommonlyimplementedordinaltypes

一Enumeration(歹f]聚)type

•oneinwhichtheuserenumeratesallthepossible

values,whicharenamedsymbolicconstants

•CanbeusedinFor-loops,casestatements,etc.

•UsuallycannotbeI/Oeasily

•Mainlyusedforabstraction/readabiIity

ExampleinC#

enumdays{Mon,Tue,Wed,Thu,Fri,Sat,Sun};

0,1,2,3,4,5,6

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-26

CandC++enumerationtypes

•Enumerationvaluesareimplicitlyconverted

tointeger.

•Namescannotbereusedwithsamescope

•Enumerationvaluesaresubjecttotherules

governingintegers.

•C++example:

enumcolortype{red,blue,green,yello,black);

colortypemyColor=blue,yourColor=red;

myColor++;wouldassigngreentomyColor.

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-27

Pascalenumerationtypes

•Enumerationtypescanbeusedfor

-Arraysubscripts

-Forstatementvariables

-Casestatementselectors

•Cannotbeinputoroutput

•Namescannotbereusedinotherenumeration

types

•Pascalenumerationexample

typecolortype=(red,blue,green);

varcolor:colortype;

■■■

color:=blue;

ifcolor>red...

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-28

Adaenumerationtypes

、•CanbeusedasinPascal

•Canbeinput/output(viaEnumeration_IO).

•Namescanbereused;disambiguationis

accomplishedbycontextorbyusing

type_namez

•Example:

鼠弋]typeDAYSis(MonzTue,WedzThuzFri,Sat,Sun);

0*typeWEEKDAYSis(MonJue,Wed,ThuzFri);

today,tomorrow:Day;

■■■

MflwforDayinWEEKDAYSloop...

JMSforDayinDAYSTue..DAYSTriloop...

today:=DAYSTREDftomorrow);

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-29

Javaenumerationtypes

•Javadoesnotincludeanenumerationtype

•Enumerationtypesareclassesthatimplement

theEnumerationinterface

Classcolors{

Publicfinalintred=0;

Publicfinalintblue=1;

)

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-30

User-definedordinaltypes

一Subrangetype:acontiguous(!®近的)

subsequenceofanordinaltypes

•Limitsalargetypetoacontiguoussubsequenceof

valueswithinthelargerrange

•providingadditionalflexibilityinprogrammingand

readability/abstraction

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-31

Subrangetypes

•Pascal:

type

uppercase=

index=1..100;

•Ada:

subtypeWEEKDAYSisDAYSrangeMon..Fri;

subtypeINDEXisINTEGERrange1..100;

-Note:WEEKDAYSiscompatiblewithDAYS

INDEXiscompatiblewithINTEGER

-Ada'sderivedtypeisdifferentfromsubtype:

typeINDEX2isnewINTEGERrange1..100;

-notcompatiblewithINTEGERorINDEX

•Asisthecasewithenumerationtypes,

subrangetypesaidreadabilityandreliability.

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-32

Implementingordinaltypes

•Enumerationtypesareimplementedas

integers,withthefirstvaluerepresented

as0,thenextvalueas1,etc,

•Thepermittedoperationsaredifferent

fromthoseofinteger.

•Subrangetypesareimplementedusing

theparenttypewithcodeinsertedbythe

compilertorestrictassignmentto

subrangevariables.

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-33

Evaluationofenumerationtypes

Aidtoefficiency-e.g.,compilercanselectand

useacompactefficientrepresentation(e.g,,

smallintegers)

Aidtoreadability-Symbolicconstantsare

mucheasiertounderstandandrememberthan

integerliterals(e.g,,noneedtocodeacoloras

anumber)

Aidtomaintainability-e.g,zaddinganew

colordoesn'trequireupdatinghard-coded

constants.

Aidtoreliability-eg,compilercancheck

operationsandrangesofvalue.

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-34

Arraytypes

•Anarrayisahomogeneousaggregate(聚集)of

dataelementsinwhichanelementisidentified

byitspositionintheaggregate,relativetothe

firstelement

•Referencestoelementsincludeoneormore

subscripts

•Referencesrequirearuntimecomputationto

determinethelocationbeingreferenced

•Arraytypesareimplementedinmost

programminglanguages

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-35

Arraytypes

•Designissues

一Whattypesarelegalforsubscripts?

一Aresubscriptexpressionsrangechecked?

一Whenaresubscriptrangesbound?

一Whendoesallocationtakeplace?

一Whatisthemaximumnumberofsubscripts?

一Canarraysbeinitializedwhentheyhavetheir

storageallocated?

-Arearrayslicesallowed?

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-36

ArraysandIndexes

•Indexingisamappingfromindicestoelementsin

anarray:

map(arrayName,indexValue)—>arrayelement

•Syntaxofindexingisfairlyuniversal:

arraynamefollowedbylistofindices,

eachsurroundedbyparenthesesorbrackets

-Ada,FORTRAN,PL/Iuseparentheses:()

-Otherlanguagesusebrackets:[]

•Subscripttypes

-FORTRAN,C,C++,andJavaallowintegersubscriptsonly

-Pascalallowsanyordinaltype

(int,boolean,char,enum)

-Adaallowsintegerorenumeration(歹U聚)types

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-37

Fourcategoriesofarrays

•4categoriesofarraysbasedonsubscriptrange

bindingandstoragebinding:

-Static

-Fixedstackdynamic

-Stackdynamic

-Heapdynamic

•Insomelanguagesthelowerboundofthe

subscriptrangeisimplicit

-C,C++,Java—fixedat0

-FORTRAN—fixedat1

-Otherlanguagesrequireprogrammertospecifythe

subscriptrange.

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-38

Staticarrays

•Staticarraysarethoseinwhich

一Rangeofsubscriptsisstaticallybound

一Storagebindingsarestatic

•Advantage:executionefficiencysinceno

dynamicallyallocation/deallocationis

required

•FORTRANarraysandsomearraysinAda

arestatic

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-39

Fixedstack-dynamicarrays

•Fixedstack-dynamicarraysarethosein

which

-Subscriptrangesarestaticallybound

-Allocationisdoneatdeclarationelaborationtime

•Advantageisspaceefficiency

-Storageisallocatedonlywhileblockinwhicharrayis

declaredisactive.

-Storageforlargearraysin2differentprocedurescan

besharedaslongasbotharenotactive

simultaneously

•PascallocalarraysandClocalarraysthat

arenotstaticarefixedstack-dynamic

arrays

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-40

Stack-dynamicarrays

•Astack-dynamicarrayisoneinwhich

-Subscriptrangesaredynamicallybound

-Storageallocationisdoneatruntime

-Bothremainfixedduringthelifetimeofthevariable

•Advantage:flexibility

•Adahasthiskindofarray:

declare

ARR:array(l..N)ofINTEGER;

begin

■■■

end;

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-41

Heap-dynamicarrays

•Aheap-dynamicarrayisoneinwhich

-Subscriptrangebindingisdynamic

-Storageallocationisdynamic

-Eithercanchangeanynumberoftimesduringexecution

•Arrayscangrowandshrinkastheneedarises

•FORTRAN90hasdynamicarrays:

INTEGER,ALLOCATABLE,ARRAY%:)::MAT

ALLOCATE(MAT(10,20))

DEALLOCATE(MAT)

•CandC++allowdynamicarraysvia

-mallocandfree

-newanddelete

•APLandPerlarrayschangesizesasneeded

•Javaarraysareobjects(heapdynamic)

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-42

Numberofsubscripts

Arraydimensions

•FORTRANI

一Allowedupto3subscripts

•FORTRAN77

一Allowsupto7subscripts

•C,C++,Java

-limitedto1butarrayscanbenested

(i,e.arrayelementisanarray)allowing

foranynumberofdimensions

•Otherslanguages

一Nolimitisspecified

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-43

Arrayinitialization

FORTRAN:initializationatthetimestorageisallocated

INTEGERLIST⑶

DATALIST/10,20,30/

C,C++:lengthofarrayisimplicitbasedonlengthof

initializationlist

intlist[]={10,20,30);

charname[]=''bob";

char*names[]={''bob",〃sue”,〃tom〃};

Java

String[]names={''bob","sue","tom2;

AdadikeCbutyoucanspecifywhicharrayelementsare

assignedvalues(insteadofassigningallvalues)

LIST:array(1..5)ofINTEGER:=(1,2,3,4,5);

LIST2:array(l„10)ofINTGEGER:=

(1=>10,2..5=>100,others=>0);

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-44

ArrayOperations

•APLhasmanyarrayoperations:

-+,・,*,/forvectors,matrices,andscalars

-Unaryoperatorsforreversingvectors,columnsorrows

ofmatrices

-Transposeorinvertamatrix

•Ada

-Array-arrayassignment

-Concatenationforany1-dimensionalarraytype

-Relationaloperators(=and/=)

•CandC++

-Notmuchinthewayofarrayoperations

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-45

ArrayOperations

•Operationsthatapplytoanarrayasaunit(as

opposedtoasinglearrayelement)

•Mostlanguageshavedirectassignmentofone

arraytoanother(A:=B)ifbotharraysare

equivalent

•FORTRAN:AllowsarrayadditionA+B

•FORTRAN90:libraryofArrayopsincludingmatrix

multiplication,transpose

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-46

ArrayOperationsinJava

•InJava,arraysareobjects(sometimescalled

aggregatetypes)

•Declarationofanarraymayomitsizeasin:

-int[]arrayl;

-arraylisapointerinitializedtonil

-atalaterpoint,thearraymaygetmemory

allocateditaswith

-arrayl=newint[100];

•Arrayoperationsotherthanaccess(arrayl[2])are

throughmethodssuchasarrayl.length

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-47

Arrayslices

•Asliceissomesubstructureofanarray;

nothingmorethanareferencing

mechanism

•Examples:

-FORTRAN90

INTEGERMAT(1:4,1:4)

MAT(1:4,1)(1stcolumn)

MAT(2,1:4)(2ndrow)

一Ada

LIST(4..1O)

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-48

ExampleslicesinFortran95

CUBE(2,1:3,1:4)CUBE(1:3,1:3,2:3)

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-49

Arrayimplementation

•Compile-timedescriptorfora

1-dimensionalarraymayinclude:

一Elementtype

一Indextype

一Indexlowerbound

一Indexupperbound

一Address

•Formulti-dimensionalarrays,information

abouteachindexrangemustbestored.

Copyright©2004PearsonAddison-Wesley.Allrightsreserved.6-50

Arrayimplementation

•Anaccessfunctionisusedtomaparray

subscriptstoaddresses.

•Fora1-dimensionalarray,theaccess

functionforarrayarris

address(arr[k])=

addr(arr[lower_bound])+(k-

lower_bound)*element_size

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论