动态内存分配 [英] Dynamic Memory Allocation

查看:189
本文介绍了动态内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法为数组动态分配内存。我已经调试好几个小时,任何指针?

我张贴的code的其余部分。它只是应该与第二,第三与第四交换交换的第一行。我得到了奇怪的结果,如:

输入字符串:你好

输入字符串:你怎么样

输入字符串:我很好谢谢

输入字符串:再见

输入字符串:李白

输入字符串:XX

=========================

你怎么样

!我很好谢谢

您好

!你怎么样

再见

!李白

我很好谢谢

再见了

!XX

 诠释计数= 0;
    的char *线[MAX_LINES]
    字符* TMP [50];
    的printf(请输入字符串:);
    与fgets(TMP,50,标准输入);
    行[统计] =(字符*)malloc的((strlen的(TMP)+1)* sizeof的(炭));
    的strcpy(行[计数],TMP);    而(STRCMP(XX \\ n,行[计数])){
            算上++;
            的printf(请输入字符串:);
            与fgets(TMP,50,标准输入);
            行[统计] =(字符*)malloc的((strlen的(TMP)+1)* sizeof的(炭));            的strcpy(行[计数],TMP);
    }无效交换(字符*记录[])
{
    字符*温度;
    TEMP =记录[0];
    记录[0] =记录[1];
    记录[1] =温度;    TEMP =记录[2];
    记录[2] =记录[3];
    记录[3] =温度;}无效printArray(字符*输入[],诠释行,诠释山口)
{
    INT I,J;    对于(i = 0; I<排;我++){
        为(J = 0; J<西; J ++){
            的printf(%C,输入[I] [J]);
        }    }
}


解决方案

这code似乎工作:

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&string.h中GT;枚举{MAX_LINES = 50};
静态无效printArray(字符*输入[],诠释行);
静态INT的readLine(字符*缓冲区,为size_t buflen);INT主要(无效)
{
    诠释计数= 0;
    的char *线[MAX_LINES]
    TMP的char [50];    为(计数= 0; COUNT< MAX_LINES;计数++)
    {
        如果(的readLine(TMP,的sizeof(TMP))== EOF)
            打破;
        行[统计] =(字符*)malloc的((strlen的(TMP)+1)* sizeof的(炭));
        如果(行[计数] == 0)
            打破;
        的strcpy(行[计数],TMP);
    }    的putchar('\\ n');
    printArray(线,计数);    返回(0);
}静态INT read_line(字符*缓冲区,为size_t buflen)
{
    的printf(请输入字符串:);
    如果(与fgets(缓冲,buflen,标准输入)== 0 || STRCMP(XX \\ n,缓冲区)== 0)
        返回EOF;
    返回0;
}静态无效printArray(字符*输入[],诠释行)
{
    的for(int i = 0; I<行;我++)
        的printf(%d个:%S,我输入[I]);
}

样运行1(使用EOF):

  $ ./rl
输入字符串:阿比西尼亚
输入字符串:温布尔登网球公开赛共同
输入字符串:^ D
0:阿比西尼亚
1:温网通用
$

样运行2(用 XX ')

  $ ./rl
输入字符串:阿比西尼亚
输入字符串:温布尔登网球公开赛共同
输入字符串:草莓柠檬水
输入字符串:XX0:阿比西尼亚
1:温网通用
2:草莓柠檬水
$

有什么不同?我固定在 TMP 的类型在评论中指出的。我创建了一个功能的readLine()来管理及时和阅读并XX \\ N过程比较避免重复。我避免使用的strdup()但检查的malloc()使用指针返回之前成功。我保证不会有太多的行读取(在循环)。在 printArray() code只需要行的数目,因为字符串是变长的。我删除了交换()函数,因为没有使用它,我看不出它应该如何使用。在code是完整的,可编译(所以它是一个SSCCE - 短的,独立的,正确的示例)。

I'm having trouble dynamically allocating memory for an array. I've been debugging for hours, any pointers?

I posted the rest of the code. It is simply supposed to exchange the swap the first row with the second, and the third with the forth. I am getting strange results like:

Enter string: hello

Enter string: how are you

Enter string: i'm good thanks

Enter string: bye

Enter string: bai

Enter string: xx

=========================

how are you

!i'm good thanks

hello

!how are you

bye

!bai

i'm good thanks

!bye

bai

!xx

    int count = 0;
    char *lines[MAX_LINES];
    char *tmp[50]; 


    printf("Enter string: ");
    fgets(tmp, 50, stdin);
    lines[count] = (char *) malloc((strlen(tmp)+1) * sizeof(char));
    strcpy(lines[count], tmp); 

    while(strcmp("xx\n", lines[count])){
            count++;
            printf("Enter string: ");
            fgets(tmp, 50, stdin); 
            lines[count] = (char *) malloc((strlen(tmp)+1)* sizeof(char));

            strcpy(lines[count], tmp); 
    }

void exchange(char * records[])
{
    char * temp;
    temp = records[0];
    records[0] = records[1];
    records[1] = temp;

    temp = records[2];
    records[2] = records[3];
    records[3] = temp; 

}

void printArray(char * inputs[], int row, int col)
{
    int i, j;

    for(i = 0; i < row; i++){
        for(j = 0; j < col; j++){
            printf("%c", inputs[i][j]);
        }

    }
}   

解决方案

This code seems to work:

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

enum { MAX_LINES = 50 };
static void printArray(char *inputs[], int rows);
static int readLine(char *buffer, size_t buflen);

int main(void)
{
    int count = 0;
    char *lines[MAX_LINES];
    char  tmp[50]; 

    for (count = 0; count < MAX_LINES; count++)
    {
        if (readLine(tmp, sizeof(tmp)) == EOF)
            break;
        lines[count] = (char *) malloc((strlen(tmp)+1)* sizeof(char));
        if (lines[count] == 0)
            break;
        strcpy(lines[count], tmp); 
    }

    putchar('\n');
    printArray(lines, count);

    return(0);
}

static int read_line(char *buffer, size_t buflen)
{
    printf("Enter string: ");
    if (fgets(buffer, buflen, stdin) == 0 || strcmp("xx\n", buffer) == 0)
        return EOF;
    return 0;
}

static void printArray(char *inputs[], int rows)
{
    for (int i = 0; i < rows; i++)
        printf("%d: %s", i, inputs[i]);
}  

Sample run 1 (using EOF):

$ ./rl
Enter string: Abyssinia
Enter string: Wimbledon Common
Enter string: ^D
0: Abyssinia
1: Wimbledon Common
$

Sample run 2 (using 'xx'):

$ ./rl
Enter string: Abyssinia
Enter string: Wimbledon Common
Enter string: Strawberry Lemonade
Enter string: xx

0: Abyssinia
1: Wimbledon Common
2: Strawberry Lemonade
$

What's different? I fixed the type on tmp as noted in a comment. I created a function readLine() to manage the prompt and read and compare with "xx\n" process to avoid repetition. I avoided using strdup() but do check that malloc() succeeds before using the pointer returned. I ensure that there are not too many lines read in (the for loop). The printArray() code only takes the number of rows because the strings are of varying length. I removed the exchange() function since it was not being used and I couldn't see how it was supposed to be used. The code is complete and compilable (so it is an SSCCE — Short, Self-Contained, Correct Example).

这篇关于动态内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆