(dynamic link)char array, in C language

Its no "string" data style in C language.

If you really want string,then use 

typedef char* string;

So we have to use char array.Beginner always has some mistake here.

e.g:

Introduction
char s1[] = "Hello World";
char *s2  = "Hello World";

size of s1: 12   // s1 is a array
size of s2: 
4    //  s2 is a pointer to array

They can be use by following:

for(i =0;i<6;i++)
    putchar(s1[i]);
putchar('\n');

for(i =0;i<6;i++)
    putchar(s2[i]);
putchar('\n');

How different are they?   Only s2 (i,e:The pointer statment can use by following)

while(*(s2) != '\0')
    putchar(*(s2++));

s2 = s1;  //s2 now points to the array s1, P.S:it's only points to s1 , not stringcpy. Please,use strncpy();

but s1 = s2 // illeagal construction , because x=3; ,but 3=x; is wrong.

And then,we discuss how to chang the content of "string".

s1[5]='A';
*(s1+5)='A';
s2[1]='A' // it can be compiler, but may crash.
          //char *s2  = "Hello World";

Next topic, we discuss dynamic link char array

char *buf = (char *)malloc(10* sizeof(char)); // char buf[10];  char *buf;
        if (buf==NULL) exit (1);              // Don`t forget free(buf);

the "buf" can be regarded as char buf[10];  or char *buf;

 malloc() generates data is stored in heap section.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

char encrypt[]="\x9f\x76\x42\xb4\x45\xbe\x42\xa6\x37\xd5\x77\x2d\xc6\x7c\xbe\xf4"
               "\x45\xa5\x33\xb9\xf4\x8d\x9b\x8b\x8b\x9a\x36\x0\x1c\x4\x1d\x54\x3c"
               "\x10\x1d\x0\x58\x45\x21\x1\x1a\x44\x79";

char * decoder(char *pw , char *encrypt)   //return a "string",so use char *
{
    int i;
    char *text=(char *)malloc(sizeof(char)*43);
    for(i=0;i<43;i++)
    text[i] = encrypt[i]^pw[i % strlen(pw)];
    return text;          
}

int main()
{
int i; char *pw="test"; //put the password int (*ret)(); //function pointer ret =(int (*)()) decoder(pw,encrypt); (int)(*ret)(); free(decoder(pw,encrypt)); exit(1);
}
posted @ 2012-10-27 11:34  jeremyatchina  阅读(261)  评论(0编辑  收藏  举报