【问题标题】:copying matrixes in c在c中复制矩阵
【发布时间】:2011-11-05 19:17:05
【问题描述】:

所以我得到了这个: char table1[10^length][length]; char table2[10^length][length];

编译器不允许我添加这个: 表1=表2;

我的代码应该采用带有通配符的字符串(仅?)

并在输出中给出所有可能的字符串(这是一个更大项目的一部分,但可以说在终端打印它们 - 如果我这样做,我可以处理其余的)

这里是完整的代码:

int ** wildReplacement(char *wildAM,int length)
{
    length=7;
    char * temp;
    strcpy(wildAM,"123?23");
    //getchar();
    int i=0;
    int j=0;
    int k=0;
    int l=0;
    int limit=0;
    int wildCharsNum;
    char *nlptr= NULL;

    char table1[10^length][length];
    char table2[10^length][length];


    wildCharsNum=charOccurenciesInStr(wildAM,'?');
    strcpy(temp,wildAM);
    strcpy(table1[0],wildAM);

    printf("\n!!WildChars In wildAM:%d",wildCharsNum);


    while(k<wildCharsNum)
    {
        l=0;
        while(l<=limit)
        {
            strcpy(temp,table1[l]);
            i=0;
            nlptr = strchr(temp, '?');//ka8e fora vriskei to epomeno ?
            if (nlptr) 
            {
                for(j=1;j<10;j++)
                {
                    *nlptr = myItoc(j);//antikatastasi tou ? me digits sto temp
                    strcpy(table2[i],temp);
                    i++;
                }
            }
            l++;
        }
        table1=table2;
        limit=i;
    k++;
    }

    printf("\nWild Numbers out:");
    for(i=0;i<limit;i++)
    {
        printf("\n%s",table1[i]);
    }

}

我应该 malloc 喜欢吗:

char ** table1
char ** table2

table1=malloc(sizeof(char)*10^length*lenght)
table2=malloc(sizeof(char)*10^length*lenght)

程序如何知道每条记录何时结束

那么这意味着什么: 表 1[1] ?可能没什么...

提前致谢

【问题讨论】:

  • ^ 不表示取幂,表示按位异或。
  • 为什么length作为参数传入然后立即设置为7?
  • 谢谢你 K-ballo,你说得对,我把它改成了 pow(),一切正常

标签: c matrix copy malloc


【解决方案1】:

当您malloc 二维数组时,您无法构造与编译器为数组声明所做的相同的东西。 char a[100][50] 是一个连续的内存块,即 5000 char。当您为其下标时,编译器能够进行行/列数学运算,因为它在编译时就知道大小。当您malloc 一个等效的二维数组时,您必须提供一个行数组来索引行。这就是您回答问题“程序如何知道每条记录何时结束”的方式:

char **b;
int i;
int rows = 100;
int cols = 50;
/* using sizeof(*b) is a good habit because there's only */
/* one place where you have to change type information */
b = malloc(rows * sizeof(*b));
/* now create a bunch of rows */
for (i = 0; i < rows; ++i) {
    b[i] = malloc(cols * sizeof(**b));
}

请注意,由于rows 索引数组,这比声明的数组占用更多内存。

作为一种优化,您可以避免循环中重复的malloc,并从rows * cols * sizeof(**b) 的单个大分配中分配内存。

注意你写一个匹配函数到free你的数组。

【讨论】:

  • 如果在 C 中使用malloc(rows * cols * sizeof(T)) 完全可能,则以平面方式分配二维数组。该解决方案保留了引用的局部性并简化了释放/错误检查。
  • Larsmans,你建议如何取消引用它?我的印象是问题是关于将固定数组调整为动态数组。如果你想保留table[y][x] 的语法,你需要像我描述的那样。
  • 您可以使用指向char 数组的指针而不是仅仅指向char,例如char (*b)[50]; b = malloc(rows * sizeof(*b));,来分配一个数组数组而不是...然后你不需要指针数组。
  • 我认为 Ben 的代码应该是我要的,但是.. 这个宝贝也成功了 :D memcpy(table1,table2,sizeof(char)*(int)(pow(10,(k +1)))*(长度+1));不过必须修改代码,我会在系统允许时发布答案
猜你喜欢
  • 2012-09-22
  • 2018-07-31
  • 1970-01-01
  • 2012-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-12
  • 1970-01-01
相关资源
最近更新 更多