zoukankan      html  css  js  c++  java
  • C语言 二维数组复制、清零及打印显示

    #include <stdlib.h> 
    #include <stdio.h>
    #include <string.h>
    
    //二维整型数组打印显示 
    void printarr2d(int (*a)[3],int row,int col)
    {
     int i,j;
     for(i=0; i<row; i++)  
        {  
            for(j=0; j<col; j++)  
            {  
                printf("%d  ", a[i][j]);  
            } 
             printf("
    ");    
        }  
    }

    main()
    {
        int i,j;
        int a[2][3]={{1,2,3},{4,5,6}};
        int b[2][3];
        //二维数组复制(第三个参数为数组总的字节数)
        memcpy(b,a, 2*3*sizeof(int) );//memcpy(&b[0][0],&a[0][0],24);
        //二维数组打印显示 (before zero)
        printarr2d(b,2,3);
        //二维数组清零
        memset(b,0, 2*3*sizeof(int) );
        //二维数组打印显示 (after zero)
        printarr2d(b,2,3);
        system("pause");
        return 0;
    }

     
    c语言中如何复制一个二维数组的所有元素的值到另外一个二维数
    使用for循环固然可以,但是总感觉非常麻烦
    #include"stdio.h"
    int main(void)
    { 
      int i,j;
      int a[2][5]={{1,2,3},{4,5,6,8}};  
      int b[2][5];
      for(i=0;i<2;i++)
      {
          for(j=0;j<5;j++)
          {
          b[i][j]=a[i][j];     
        }
      }   
      printf("%d",b[1][2]);
    }
    (1)
    mencpy的原型是void *memcpy(void *dest, const void *src, size_t n); 1 为什么*memcpy这里前面有个*号?? 2 为什么函数的参数里面void * src 前面有个修饰符const 答: 1: memcpy 返回值为void * 2:加 const 变为常量指针 防止在memcpy中对src指向的内容进行修改,函数的健壮性考虑

    自己做的时候,就在想,如何不适用二重for循环的办法,对二维数组进行复制操作

    看了下CSDN 的bbs结果真的有,非常感谢

    注:

      1)使用memcpy函数,memset函数都要引入库文件 #include <string.h>

      2)本来想对这个复制函数封装的,后来感觉没必要,直接使用,只不过要注意第三个参数为:数组整体内存所占bit数,要小心

    (2)

     memset(b,0, 2*3*sizeof(int) );
    第一个值是数组地址,第二个是你要把数组中的值赋为多少,第三个是你要赋多少个元素。

    总结版:

    二维数组复制:

    //二维数组复制(第三个参数为数组总的字节数) 
      memcpy(b,a, 2*3*sizeof(int) );//memcpy(&b[0][0],&a[0][0],24);

    二维数组清零:

     //二维数组清零
      memset(b,0, 2*3*sizeof(int) );
  • 相关阅读:
    系统按钮返回,一般都从缓存里直接取,现在想让他返回时重新加载
    添加分享
    模板常用模板
    常用正则表达式
    常用HTML5代码片段
    Files 的值“.mine”无效。路径中具有非法字符。
    C# Winform通过SynchronizationContext(提供在各种同步模型中传播同步上下文的基本功能)加载信息
    WebService 中操作 HttpRequest / HttpResponse (一)
    WebService 中操作 HttpRequest / HttpResponse (二)[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    C#调用Webservice的代码实现方式汇总
  • 原文地址:https://www.cnblogs.com/shuqingstudy/p/5162585.html
Copyright © 2011-2022 走看看