糖逗 发表于 2019-12-2 14:33:43

带你学C26课后题

原问题动手0:https://fishc.com.cn/forum.php?mod=viewthread&tid=74415&extra=page%3D1%26filter%3Dtypeid%26typeid%3D570

不太明白为什么要记录字符串位置,生成1024个字符串数组后再向其中添加字符串,字符串是怎么存储的?是连续的从头存储,还是不连续存储呢?

比如我申请char string   然后我存储“sdffdfdf”这样的字符,它会怎么存储呢?

windows 发表于 2019-12-3 16:57:14

数组是一段连续空间,不明白你想要问什么

糖逗 发表于 2019-12-4 13:28:02

windows 发表于 2019-12-3 16:57
数组是一段连续空间,不明白你想要问什么

不太明白那道题为什么要记录地址。不记录地址,用指针顺序访问的时候出错了。
这个是我当时写得代码,就是得不到准确答案,但也不知道错在哪{:10_324:}
#include <stdio.h>
#include <stdlib.h>

#define MAX 1024


int main(void)
{
        char string;
        char* stringP = string;
        int len = 0;
        int space_count = 0;
        int max_len = 0, word_len = 0;
       
        printf("请输入一个英文句子:");
       
        while((string = getchar()) != '\n');
        string = '\0';//关键点!!!!!!!!!!!!!!!!!!
       
        //计算空格数
        for(int i = 0; i < len; i++)
        {
                if(string == ' ' || string == '\0')
                {
                        space_count++;
                        while(string != ' ');
                        max_len = (max_len > word_len)? max_len : word_len;
                        word_len = 0;
                }
                else
                {
                        word_len++;
                }
        }
        printf("分割的结果存放到result[%d][%d]的二维数组中\n", space_count, max_len);
       
        char(*matrix) = (char(*))malloc(sizeof(char) * space_count * (max_len+1));
        //存放数组中
        for(int i = 0; i < space_count; i++)
        {
                for(int j = 0; j < max_len+1; j++)//这里面列加1因为要存储'\0'
                {
                        if(*stringP != ' ' && *stringP != '\0')
                        {
                                matrix = *stringP++;
                                continue;
                        }
                        else if(*stringP == ' ')
                        {
                                matrix = '\0';
                                //指针指向下一个不为空的
                                while(*stringP++ != ' ');
                                break;
                        }
                        else if(*stringP == '\0')
                        {
                                matrix = '\0';
                                break;
                        }
                }
                matrix = '\0';       
        }
       
        //计算最大字符串的长度
        printf("打印二维数组中的数据:\n");
       
        for(int i = 0; i < space_count; i++)
        {
                for(int j = 0; j < max_len; j++)
                {
                        printf("%c", matrix);
                }
                printf("\n");
        }
       
        return 0;
}
页: [1]
查看完整版本: 带你学C26课后题