【问题标题】:Copying first half of dynamic array into second half failed in C?将动态数组的前半部分复制到后半部分在 C 中失败?
【发布时间】:2022-01-15 23:11:24
【问题描述】:

我想将我的动态数组的前半部分复制到同一数组的后半部分,但这里的输出是从 ptr[100] 到 ptr[200] 9.90。我想我编码的一切都很好,但我不知道问题出在哪里。你能帮帮我吗?


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

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
    int i;

    int j;
    
    double * ptr = calloc(100, sizeof(double));
    
    if (ptr == NULL)
        return 0;

        for(i = 0; i < 100; i++) {
            ptr [i] = i / 10.0;
        }
    
    
    for(i = 0; i < 100; i++) {
        printf("ptr[%d] = %.2f\n", i, ptr[i]);
        
        }
        
        if (realloc(ptr, 200) == NULL)
            return 0;


            for (i = 0; i < 100; i++) 
                for (j = 100; j < 201; j++) 
                    ptr [j] = ptr[i];
                
        
            
            
            for (j = 100; j < 201; j++) 
                    printf("ptr[%d] = %.2f\n", j, ptr[j]);
        
        
    return 0;
}

【问题讨论】:

  • realloc(ptr, 200) 应该是realloc(ptr, 200 * sizeof *ptr)
  • 我试过了。它不工作

标签: c memory dynamic allocation


【解决方案1】:

您在 realloc 上分配不足。您没有为 200 个双打腾出足够的空间,因此尝试访问 ptr[x] 对于 x > 99 的值是未定义的行为。此外,realloc 可能会移动内存,因此您需要将新值分配回 @987654323 @。例如:

ptr = realloc(ptr, 200 * sizeof *ptr);
if( ptr == NULL ){
    perror("realloc");
    exit(1);
}

在此之后,访问ptr[200] 是未定义的行为。您需要将循环索引的范围缩小到for( j = 100; j &lt; 200; j++ )

【讨论】:

    【解决方案2】:

    你正在覆盖每个副本

    for (i = 0; i < 100; i++) // for every item in the first half
        for (j = 100; j < 201; j++)  // into every cell
            ptr [j] = ptr[i];
    

    应该是

    for (i = 0; i < 100; i++) 
            ptr [i+100] = ptr[i];
    

    第 2 期:

    您没有分配足够的内存:将 realloc(ptr, 200) 更改为 realloc(ptr, 200 * sizeof(double))

    【讨论】:

    • 非常感谢。它现在正在工作,但我不明白为什么要覆盖它。
    • 您对它们不同步但嵌套的循环感到困惑,因此对于 i 的每一步,j 都在 100 到 199 的整个范围内
    猜你喜欢
    • 2020-09-21
    • 2013-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    相关资源
    最近更新 更多