90 likes | 102 Views
Learn about pointers and strings in Windows programming using C language. Understand the basics of pointers, declaration of pointers, pointer operators, pointers and arrays, dynamic allocation, characters and strings, and AnsiString class.
E N D
Chapter 10 Pointers and Strings Windows Programming, C.-S. Shieh, KUAS EC, 2005
10.1 What Is a Pointer? • A pointer is a variable containing the address of another variable. Windows Programming, C.-S. Shieh, KUAS EC, 2005
10.2 Declaration of Pointers int i; float x; int* ip; float* xp; Windows Programming, C.-S. Shieh, KUAS EC, 2005
10.3 Pointer Operators int* ip; Int i,j; i=3; ip=i; // Illegal ip=&i; // &: 取址運算子 (*ip)=5; // *: 間接運算子 ip=&j; printf(”%d”,i); Windows Programming, C.-S. Shieh, KUAS EC, 2005
10.4 Pointers and Arrays • Static Allocation • float x[10]; • x is actually a pointer pointing to the first element. • *(x+i) is equivalent to x[i] • Array as parameter in function call is in effect call-by-address. Windows Programming, C.-S. Shieh, KUAS EC, 2005
10.4 Pointers and Arrays (cont) • Dynamic Allocation #include <stdio.h> #include <stdlib.h> void main(void) { int i,j; float* xp; scanf("%d",&i); xp=(float*)malloc(i*sizeof(float)); for(j=0;j<i;j++) *(xp+j)=j; for(j=0;j<i;j++) printf("%f ",*(xp+j)); } Windows Programming, C.-S. Shieh, KUAS EC, 2005
10.5 Characters and Strings • In BASIC DIM str1 AS STRING DIM str2 AS STRING DIM str3 AS STRING str1 = "Hello" str2 = "world" str3 = str1 + ", " + str2 + "!" PRINT str3 Windows Programming, C.-S. Shieh, KUAS EC, 2005
10.5 Characters and Strings (cont) • There is no “string” type in C, but array of characters. char str1[16]= ”love”; // Only valid in declaration char str2[16]; str2= ” hello”; // Illegal strcpy(str2,”hello”); // Correct str1[0]=‘a’;str1[1]=‘b’;str1[2]=‘c’;str1[3]=‘\0’; printf(“%s”,str1); • String function • strlen(), strcpy(), strcat(), strcmp() Windows Programming, C.-S. Shieh, KUAS EC, 2005
10.6 AnsiString Class • AnsiString class facilitate string processing. AnsiString s1,s2,s3; s1= ”Hello”; s2= ”world”; s3=s1+”, ”+s2+”!”; • Member Functions • c_str(), Length() FILE* fileptr; OpenDialog1->Execute(); fileptr=fopen((OpenDialog1->FileName).c_str(),"w"); StrPas() Windows Programming, C.-S. Shieh, KUAS EC, 2005