C语言万花03 - static variables, local pointers

今天要玩耍的是static variable还有 local pointers
先来看一个例子
header1.h

void set_i(int i);

int get_i();
int print_mychar();
int set_mychar(char *a);
char *get_mychar();
char *get_thischar();
char *get_thatchar();

header1.c

#include 
#include 
#include 

int i = 3;
char my_char[4];

void set_i(int n) {
    i = n;
}

int get_i() {
    return i;
}

int set_mychar(char *a) {
    strcpy(my_char, a);
    return 0;
}

int print_mychar() {
    puts(my_char);
    return 0;
}

char *get_mychar() {
    return my_char;
}

char *get_thischar() {
    return "654";
}

char *get_thatchar() {
    static char b[3] = "321";
    return b;
}

test.c

#include 
#include 
#include 

int main(int argc, char **argv) {
    set_i(10);
    printf("i = %d\n", get_i());
    char a[4]="123";
    set_mychar(a);
    print_mychar();
    puts(get_mychar());
    puts(get_thischar());
    puts(get_thatchar());
    return 0;
}

Makefile

CLFAGS=-I. -c -g -Wall

.SUFFIXES: .c .o

.c.o:
    cc $(CLFAGS) -o $@ $<

OBJ=    test.o \
        header1.o

all: test

test: $(OBJ)
    cc -g $(OBJ) -o $@

clean:
    rm -f test $(OBJ)

make
./test

./test 
i = 10
123
123
654
321

这现在是跑出来了,但是如果改两个地方就编译不出来。
改过的header1.h

#include 
#include 
#include 

int i = 3;
char my_char[i];

void set_i(int n) {
    i = n;
}

int get_i() {
    return i;
}

int set_mychar(char *a) {
    strcpy(my_char, a);
    return 0;
}

int print_mychar() {
    puts(my_char);
    return 0;
}

char *get_mychar() {
    return my_char;
}

char *get_thischar() {
    return "654";
}

char *get_thatchar() {
    char b[3] = "321";
    return b;
}

char my_char[4] -> char my_char[i]
static char b[3] = "321"; -> char b[3] = "321";
make

make
cc -I. -c -g -Wall -o header1.o header1.c
header1.c:6:6: error: variably modified ‘my_char’ at file scope
 char my_char[i];
      ^~~~~~~
header1.c: In function ‘get_thatchar’:
header1.c:36:12: warning: function returns address of local variable [-Wreturn-local-addr]
     return b;
            ^
Makefile:6: recipe for target 'header1.o' failed
make: *** [header1.o] Error 1

local variable的pointer无法被return,但是static variable可以。在function以外initialize的variable应该都是static的。
还有就是static的string的大小必须是一个constant,variable不行。

你可能感兴趣的:(C语言万花03 - static variables, local pointers)