第十一章编程题

2.在这个题目中,我的设计的不人性化在于,我必须要求用户给输入自己要输入整数的大小,然后我再给他分配内存,这分明是通过折磨用户来使自己的程序变得简单,而guide's answer则是只需要用户输入你该输入的数即可。程序设计的思路如下:

1.先预设一定大小(宏定义)的内存分配;

2.然后在读入数字时进行计数,并进行与之前定义了的内存大小进行比较,若小于无作为,大于的话则重新进行内存分配(分配的内存比之前的大一倍);与此同时,把输入的数赋值给该内存空间;

3.对内存进行压缩。

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

int *read(void)
{
    int values;
    int *p = NULL;
    int i = 1;

    scanf("%d", &values);
    p = malloc(sizeof(int) * values);
    *p = values;

    if (p == NULL)
    {
        printf("failure of malloc\n");
        exit(EXIT_FAILURE);
    }

    while (scanf("d", &values) == 1)
    {
        p[i] = values;
        i++;
    }
    return p;
}
#include <stdio.h>
#include <stdlib.h>

#define     DELTA   100

int *
readints()
{
    int *array;
    int size;
    int count;
    int value;

    size = DELTA;
    array = malloc((size + 1) * sizeof(int));
    if (array == NULL)
        return NULL;

    count = 0;
    while (scanf("%d", &value) == 1)
    {
        count += 1;
        if (count > size)
        {
            size += DELTA;
            array = realloc(array, (size+1) * sizeof (int));
            if (array == NULL)
                return NULL;
        }
        array[count] = value;
    }

    if (count < size)
    {
        array = realloc(array, (count+1) * sizeof(int));
        if (array == NULL);
            return NULL;
    }
    array[0] = count;
    return array;
}

 

3.

#include <stdio.h>
#include <stdlib.h>
#define     DELTA   100

char *readchar()
{
    int size = DELTA;
    int len = 0;

    char *buf = malloc(size * (sizeof(char)));
    if (buf == NULL)
        return NULL;

    char ch = getchar();
    while (ch != '\0')
    {
        if (len > size)
        {
            size += DELTA;
            buf = realloc(buf, size*(sizeof(char)));
            if (buf == NULL)
                return NULL;
        }
        buf[len] = ch;
        ch = getchar();
        len += 1;
    }

    if (len < size)
        buf = realloc(buf, len*(sizeof(char)));
    if (buf == NULL)
        return NULL;

    return buf;


}

 

4.

#include <stdlib.h>
struct list{
    int data;
    struct list *next;
};

struct list *node_func(int data)
{
    struct list *node = malloc(sizeof(struct list));
    node->data = data;
    return node;
}

main()
{
    struct list *head = node_func(5);
    head->next = node_func(10);
    head->next->next = node_func(15);
    head->next->next->data = 0;

}
posted @ 2013-05-08 20:50  frechei  阅读(181)  评论(0)    收藏  举报