创建矩阵和free()问题 - c

时间:2017-05-16 06:34:39

标签: c

我的代码中似乎有一些问题。第一个是我无法正确使用免费功能:“检测到堆损坏”。 在我的工作的第二部分,我想创建一个矩阵:它在j下面放一个红色标记然后编译器说下标需要数组和指针类型。 我只想创建一个二维矩阵。 谢谢你的帮助!!!

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include <math.h>
void main()
{
char *word[1000] = { 0 }, letter[1000], *temparr, *originalarr;
int i = 0, j = 0, counter = 0, k = 0, w = 0, anagram = 0, size = 0, *mat;
for (i = 0; letter[i] != '\n'; i++)
{
    letter[i] = getchar();
    counter++;
    if (letter[i] == ' ' || letter[i] == '\n')
    {
        if (letter[i] == 10)
        {
            letter[i] = 0;
            word[j] = malloc(sizeof(char*)*(counter - 1));
            strcpy_s(word[j], (counter - 1) * sizeof(char*), &letter[i - (--counter)]);
            break;
        }
        if (letter[i - 1] == ' ')
            continue;
        letter[i] = '\0';
        word[j] = malloc(sizeof(char*)*counter);
        strcpy_s(word[j], (counter - 1) * sizeof(char*), &letter[i - (--counter)]);
        letter[i] = ' ';
        counter = 0;
        j++;
    }
}
while (j > 0)
{
    printf_s("%s ", word[j--]);
    if (j == 0)
        printf_s("%s", word[j]);
}
for (j = 0; word[j] != 0; j++)
{
    originalarr = (char*)malloc((sizeof(char) * strlen(word[j])));
    strcpy_s(originalarr, strlen(word[j]) + 1, word[j]);
    for (i = 0; word[i] != 0; i++)
    {
        temparr = (char*)malloc((sizeof(char) * strlen(word[i])));
        strcpy_s(temparr, strlen(word[i]) + 1, word[i]);
        counter = 0;
        if (strlen(originalarr) != strlen(temparr))
            continue;
        for (k = 0; originalarr[k] != 0; k++)
        {
            for (w = 0; w < strlen(temparr); w++)
            {
                printf_s("temparr - %c  ", temparr[w]);
                printf_s("original - %c\n", originalarr[k]);
                if (originalarr[k] == temparr[w])
                {
                    temparr[w] = '0';//problem, but cant be equal to 0
                    counter++;
                    printf_s("counter- %d\n", counter);
                }
            }
        }
        if (counter == strlen(originalarr))
            anagram++;
        free(temparr);//problem
    }
}
k = 0;
size = ceil(sqrt(strlen(letter)));
mat = (int*)malloc((sizeof(int) * size));
for (i = 0; i < size; i++)
{
    mat[i] = (int)malloc((sizeof(int) * size));
    for (j = 0; j < size; j++)
        mat[i][j] = '\0';
}
for (i = 0; i < size; i++)
    for (j = 0; j < size; j++)
    {
        mat[i][j] = letter[k];
        k++;
    }
}

1 个答案:

答案 0 :(得分:1)

对于问题的第二部分,您需要声明指向指针mat的指针,而不是像您所做的那样声明指针。然后如图所示进行分配。

int ** mat;
mat = malloc((sizeof(int*) * size));
for (i=0; i<size; i++)
    mat[i] = malloc( sizeof(int) * size));

您可以将此数组mat用作2D数组mat[i][j]