主頁 > 移動端開發 > 宣告矩陣c的不同方式

宣告矩陣c的不同方式

2021-11-24 02:35:07 移動端開發

我真的不明白為什么方法 1 有效但方法 2 無效。我真的不明白為什么它適用于字符而不是 int。

#include <stdlib.h>
#include <stdio.h>
int main(void)
{
    ///  WORK (METHODE 1)
    char **string_array = malloc(sizeof(char **) * 10);
    string_array[0] = "Hi there";
    printf("%s\n", string_array[0]); /// -> Hi there
    
    /// DOES NOT WORK (METHODE 2)
    int **int_matrix = malloc(sizeof(int **) * 10);
    int_matrix[0][0] = 1;  // -> Segmentation fault
    
    /// WORK (METHODE 3)
    int **int_matrix2 = malloc(sizeof(int *));
    for (int i = 0; i < 10; i  )
    {
        int_matrix2[i] = malloc(sizeof(int));
    }
    int_matrix2[0][0] = 42;
    printf("%d\n", int_matrix2[0][0]); // -> 42
}

uj5u.com熱心網友回復:

就型別而言,您希望從分配給它的指標為“上一級”型別分配記憶體。例如,一個int指標 (an int*) 指向一個或多個ints。這意味著,當你為它分配空間時,你應該根據int型別進行分配

#define NUM_INTS 10
...
int* intPtr = malloc(NUM_INTS * sizeof(int));
//                                      ^^ // we want ints, so allocate for sizeof(int)

在您的一種情況下,您有一個雙int指標 (an int**)。這必須指向一個或多個int指標(int*),所以這就是你需要為分配空間型別:

#define NUM_INT_PTRS 5
...
int** myDblIntPtr = malloc(NUM_INT_PTRS * sizeof(int*));
//                                               ^^ "one level up" from int** is int*

但是,還有一種更好的方法可以做到這一點。您可以指定它指向物件的大小而不是型別:

int* intPtr = malloc(NUM_INTS * sizeof(*intPtr));

這里,intPtr是一個int*型別,它指向的物件是 an int,這正是*intPtr給我們的。這具有減少維護的額外好處。假裝一段時間后,int* intPtr更改為int** intPtr. 對于第一種處理方式,您必須在兩個地方更改代碼:

int** intPtr = malloc(NUM_INTS * sizeof(int*));
// ^^ here                              ^^ and here

但是,使用第二種方式,您只需要更改宣告:

int** intPtr = malloc(NUM_INTS * sizeof(*intPtr));
// ^^ still changed here                 ^^ nothing to change here

隨著宣告從int*的變化int***intPtr也“自動”變成了,從intint*這意味著范式:

T* myPtr = malloc(NUM_ITEMS * sizeof(*myPtr));

是首選,因為*myPtr無論是什么型別都將始終參考我們需要為正確記憶體量調整大小的正確物件T

uj5u.com熱心網友回復:

其他人已經回答了大部分問題,但我想我會添加一些插圖......

當您想要一個類似陣列的物件,即給定型別的一系列連續元素時T,您可以使用指向T,的指標T *,但您想要指向型別為 的物件T,這就是您必須分配記憶體的目的。

如果要分配 10 個T物件,則應使用malloc(10 * sizeof(T)). 如果您有一個將陣列分配給的指標,則可以從中獲取大小

T * ptr = malloc(10 * sizeof *ptr);

Here*ptr具有型別T,因此sizeof *ptr與 相同sizeof(T),但由于其他答案中解釋的原因,此語法更安全。

當你使用

T * ptr = malloc(10 * sizeof(T *));

您不會為 10 個T物件獲得記憶體,而是為 10 個T *物件獲得記憶體如果sizeof(T*) >= sizeof(T)你很好,除了你浪費了一些記憶體,但如果sizeof(T*) < sizeof(T)你的記憶體比你需要的少。

宣告矩陣 c 的不同方式

您是否遇到此問題取決于您的物件和您所在的系統。在我的系統上,所有指標都具有相同的大小,即 8 個位元組,所以我是否分配并不重要

  char **string_array = malloc(sizeof(char **) * 10);

或者

  char **string_array = malloc(sizeof(char *) * 10);

或者如果我分配

  int **int_matrix = malloc(sizeof(int **) * 10);

或者

  int **int_matrix = malloc(sizeof(int *) * 10);

但它可能在其他架構上。

對于您的第三個解決方案,您遇到了不同的問題。當你分配

  int **int_matrix2 = malloc(sizeof(int *));

您為單個int指標分配空間,但您立即將該記憶體視為有 10 個

    for (int i = 0; i < 10; i  )
    {
        int_matrix2[i] = malloc(sizeof(int));
    }

您可以安全地分配給第一個元素,int_matrix2[0](但是我的方法存在問題);您寫入的以下 9 個地址不是您可以修改的。

宣告矩陣 c 的不同方式

下一個問題是,一旦你分配了矩陣的第一維,你就有了一個指標陣列。這些指標未初始化,大概指向記憶體中的隨機位置。

宣告矩陣 c 的不同方式

That isn't a problem yet; it doesn't do any harm that these pointers are pointing into the void. You can just point them to somewhere else. This is what you do with your char ** array. You point the first pointer in the array to a string, and it is happy to point there instead.

宣告矩陣 c 的不同方式

Once you have pointed the arrays somewhere safe, you can access the memory there. But you cannot safely dereference the pointers when they are not initialised. That is what you try to do with your integer array. At int_matrix[0] you have an uninitialised pointer. The type-system doesn't warn you about that, it can't, so you can easily compile code that modifies int_matrix[0][0], but if int_matrix[0] is pointing into the void, int_matrix[0][0] is not an address you can safely read or write. What happens if you try is undefined, but undefined is generally was way of saying that something bad will happen.

宣告矩陣 c 的不同方式

You can get what you want in several ways. The closest to what it looks like you are trying is to implement matrices as arrays of pointers to arrays of values.

宣告矩陣 c 的不同方式

There, you just have to remember to allocate the arrays for each row in your matrix as well.

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

int **new_matrix(int n, int m)
{
    int **matrix = malloc(n * sizeof *matrix);
    for (int i = 0; i < n; i  )
    {
        matrix[i] = malloc(m * sizeof *matrix[i]);
    }
    return matrix;
}

void init_matrix(int n, int m, int **matrix)
{
    for (int i = 0; i < n; i  )
    {
        for (int j = 0; j < m; j  )
        {
            matrix[i][j] = 10 * i   j   1;
        }
    }
}

void print_matrix(int n, int m, int **matrix)
{
    for (int i = 0; i < n; i  )
    {
        for (int j = 0; j < m; j  )
        {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }
}

int main(void)
{
    int n = 3, m = 5;
    int **matrix = new_matrix(n, m);
    init_matrix(n, m, matrix);
    print_matrix(n, m, matrix);

    return 0;
}

Here, each row can lie somewhere random in memory, but you can also put the row in contiguous memory, so you allocate all the memory in a single malloc and compute indices to get at the two-dimensional matrix structure.

宣告矩陣 c 的不同方式

Row i will start at offset i*m into this flat array, and index matrix[i,j] is at index matrix[i * m j].

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

int *new_matrix(int n, int m)
{
    int *matrix = malloc(n * m * sizeof *matrix);
    return matrix;
}

void init_matrix(int n, int m, int *matrix)
{
    for (int i = 0; i < n; i  )
    {
        for (int j = 0; j < m; j  )
        {
            matrix[m * i   j] = 10 * i   j   1;
        }
    }
}

void print_matrix(int n, int m, int *matrix)
{
    for (int i = 0; i < n; i  )
    {
        for (int j = 0; j < m; j  )
        {
            printf("%d ", matrix[m * i   j]);
        }
        printf("\n");
    }
}

int main(void)
{
    int n = 3, m = 5;
    int *matrix = new_matrix(n, m);
    init_matrix(n, m, matrix);
    print_matrix(n, m, matrix);

    return 0;
}

With the exact same memory layout, you can also use multidimensional arrays. If you declare a matrix as int matrix[n][m] you will get what amounts to an array of length n where the objects in the arrays are integer arrays of length m, exactly as on the figure above.

If you just write that expression, you are putting the matrix on the stack (it has auto scope), but you can allocate such matrices as well if you use a pointer to int [m] arrays.

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

void *new_matrix(int n, int m)
{
    int(*matrix)[n][m] = malloc(sizeof *matrix);
    return matrix;
}

void init_matrix(int n, int m, int matrix[static n][m])
{
    for (int i = 0; i < n; i  )
    {
        for (int j = 0; j < m; j  )
        {
            matrix[i][j] = 10 * i   j   1;
        }
    }
}

void print_matrix(int n, int m, int matrix[static n][m])
{
    for (int i = 0; i < n; i  )
    {
        for (int j = 0; j < m; j  )
        {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }
}

int main(void)
{
    int n = 3, m = 5;
    int(*matrix)[m] = new_matrix(n, m);
    init_matrix(n, m, matrix);
    print_matrix(n, m, matrix);

    int(*matrix2)[m] = new_matrix(2 * n, 3 * m);
    init_matrix(2 * n, 3 * m, matrix2);
    print_matrix(2 * n, 3 * m, matrix2);

    return 0;
}

The new_matrix() function returns a void * because the return type cannot depend on the runtime arguments n and m, so I cannot return the right type.

Don't let the function types fool you, here. The functions that take a matrix[n][m] argument do not check if the matrix has the right dimensions. You can get a little type checking with pointers to arrays, but pointer decay will generally limit the checking. The last solution is really only different syntax for the previous one, and the arguments n and m determines how the (flat) memory that matrix points to is interpreted.

uj5u.com熱心網友回復:

方法 1 之所以有效,只是因為您使用字串文字“Hi there”的參考來分配char *陣列元素string_array字串文字只是一個字符陣列。

嘗試:string_array[0][0] = 'a';它會失敗,并且您將取消參考未初始化的指標。

同樣發生在method 2.

方法 3. 為一個int分配記憶體并將對它的參考存盤在陣列的 [0] 元素中。當指標參考有效物件時,您可以取消參考它 ( int_matrix2[0][0] = 42;)

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364036.html

標籤:C 指针

上一篇:在C中使用a b作為printf的引數

下一篇:C套接字服務器和Python套接字客戶端“資源暫時不可用”

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【從零開始擼一個App】Dagger2

    Dagger2是一個IOC框架,一般用于Android平臺,第一次接觸的朋友,一定會被搞得暈頭轉向。它延續了Java平臺Spring框架代碼碎片化,注解滿天飛的傳統。嘗試將各處代碼片段串聯起來,理清思緒,真不是件容易的事。更不用說還有各版本細微的差別。 與Spring不同的是,Spring是通過反射 ......

    uj5u.com 2020-09-10 06:57:59 more
  • Flutter Weekly Issue 66

    新聞 Flutter 季度調研結果分享 教程 Flutter+FaaS一體化任務編排的思考與設計 詳解Dart中如何通過注解生成代碼 GitHub 用對了嗎?Flutter 團隊分享如何管理大型開源專案 插件 flutter-bubble-tab-indicator A Flutter librar ......

    uj5u.com 2020-09-10 06:58:52 more
  • Proguard 常用規則

    介紹 Proguard 入口,如何查看輸出,如何使用 keep 設定入口以及使用實體,如何配置壓縮,混淆,校驗等規則。

    ......

    uj5u.com 2020-09-10 06:59:00 more
  • Android 開發技術周報 Issue#292

    新聞 Android即將獲得類AirDrop功能:可向附近設備快速分享檔案 谷歌為安卓檔案管理應用引入可安全隱藏資料的Safe Folder功能 Android TV新主界面將顯示電影、電視節目和應用推薦內容 泄露的Android檔案暗示了傳說中的谷歌Pixel 5a與折疊屏新機 谷歌發布Andro ......

    uj5u.com 2020-09-10 07:00:37 more
  • AutoFitTextureView Error inflating class

    報錯: Binary XML file line #0: Binary XML file line #0: Error inflating class xxx.AutoFitTextureView 解決: <com.example.testy2.AutoFitTextureView android: ......

    uj5u.com 2020-09-10 07:00:41 more
  • 根據Uri,Cursor沒有獲取到對應的屬性

    Android: 背景:呼叫攝像頭,拍攝視頻,指定保存的地址,但是回傳的Cursor檔案,只有名稱和大小的屬性,沒有其他諸如時長,連ID屬性都沒有 使用 cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATIO ......

    uj5u.com 2020-09-10 07:00:44 more
  • Android連載29-持久化技術

    一、持久化技術 我們平時所使用的APP產生的資料,在記憶體中都是瞬時的,會隨著斷電、關機等丟失資料,因此android系統采用了持久化技術,用于存盤這些“瞬時”資料 持久化技術包括:檔案存盤、SharedPreference存盤以及資料庫存盤,還有更復雜的SD卡記憶體儲。 二、檔案存盤 最基本存盤方式, ......

    uj5u.com 2020-09-10 07:00:47 more
  • Android Camera2Video整合到自己專案里

    背景: Android專案里呼叫攝像頭拍攝視頻,原本使用的 MediaStore.ACTION_VIDEO_CAPTURE, 后來因專案需要,改成了camera2 1.Camera2Video 官方demo有點問題,下載后,不能直接整合到專案 問題1.多次拍攝視頻崩潰 問題2.雙擊record按鈕, ......

    uj5u.com 2020-09-10 07:00:50 more
  • Android 開發技術周報 Issue#293

    新聞 谷歌為Android TV開發者提供多種新功能 Android 11將自動填表功能整合到鍵盤輸入建議中 谷歌宣布Android Auto即將支持更多的導航和數字停車應用 谷歌Pixel 5只有XL版本 搭載驍龍765G且將比Pixel 4更便宜 [圖]Wear OS將迎來重磅更新:應用啟動時間 ......

    uj5u.com 2020-09-10 07:01:38 more
  • 海豚星空掃碼投屏 Android 接收端 SDK 集成 六步驟

    掃碼投屏,開放網路,獨占設備,不需要額外下載軟體,微信掃碼,發現設備。支持標準DLNA協議,支持倍速播放。視頻,音頻,圖片投屏。好點意思。還支持自定義基于 DLNA 擴展的操作動作。好像要收費,沒體驗。 這里簡單記錄一下集成程序。 一 跟目錄的build.gradle添加私有mevan倉庫 mave ......

    uj5u.com 2020-09-10 07:01:43 more
最新发布
  • 歡迎頁輪播影片

    如圖,引導開始,球從上落下,同時淡入文字,然后文字開始輪播,最后一頁時停止,點擊進入首頁。 在來看看效果圖。 重力球先不講,主要歡迎輪播簡單實作 首先新建一個類 TextTranslationXGuideView,用于影片展示 文本是類似的,最后會有個圖片箭頭影片,布局很簡單,就是一個 TextVi ......

    uj5u.com 2023-04-20 08:40:31 more
  • 【FAQ】關于華為推送服務因營銷訊息頻次管控導致服務通訊類訊息

    一. 問題描述 使用華為推送服務下發IM訊息時,下發訊息請求成功且code碼為80000000,但是手機總是收不到訊息; 在華為推送自助分析(Beta)平臺查看發現,訊息發送觸發了頻控。 二. 問題原因及背景 2023年1月05日起,華為推送服務對咨詢營銷類訊息做了單個設備每日推送數量上限管理,具體 ......

    uj5u.com 2023-04-20 08:40:11 more
  • 歡迎頁輪播影片

    如圖,引導開始,球從上落下,同時淡入文字,然后文字開始輪播,最后一頁時停止,點擊進入首頁。 在來看看效果圖。 重力球先不講,主要歡迎輪播簡單實作 首先新建一個類 TextTranslationXGuideView,用于影片展示 文本是類似的,最后會有個圖片箭頭影片,布局很簡單,就是一個 TextVi ......

    uj5u.com 2023-04-20 08:39:36 more
  • 【FAQ】關于華為推送服務因營銷訊息頻次管控導致服務通訊類訊息

    一. 問題描述 使用華為推送服務下發IM訊息時,下發訊息請求成功且code碼為80000000,但是手機總是收不到訊息; 在華為推送自助分析(Beta)平臺查看發現,訊息發送觸發了頻控。 二. 問題原因及背景 2023年1月05日起,華為推送服務對咨詢營銷類訊息做了單個設備每日推送數量上限管理,具體 ......

    uj5u.com 2023-04-20 08:39:13 more
  • iOS從UI記憶體地址到讀取成員變數(oc/swift)

    開發除錯時,我們發現bug時常首先是從UI顯示發現例外,下一步才會去定位UI相關連的資料的。XCode有給我們提供一系列debug工具,但是很多人可能還沒有形成一套穩定的除錯流程,因此本文嘗試解決這個問題,順便提出一個暴論:UI顯示例外問題只需要兩個步驟就能完成定位作業的80%: 定位例外 UI 組 ......

    uj5u.com 2023-04-19 09:16:23 more
  • FIDE重磅更新!性能飛躍!體驗有禮!

    FIDE 開發者工具重構升級啦!實作500%性能提升,誠邀體驗! 一直以來不少開發者朋友在社區反饋,在使用 FIDE 工具的程序中,時常會遇到諸如加載不及時、代碼預覽/渲染性能不如意的情況,十分影響開發體驗。 作為技術團隊,我們深知一件趁手的開發工具對開發者的重要性,因此,在2023年開年,FinC ......

    uj5u.com 2023-04-19 09:16:15 more
  • 游戲內嵌社區服務開放,助力開發者提升玩家互動與留存

    華為 HMS Core 游戲內嵌社區服務提供快速訪問華為游戲中心論壇能力,支持玩家直接在游戲內瀏覽帖子和交流互動,助力開發者擴展內容生產和觸達的場景。 一、為什么要游戲內嵌社區? 二、游戲內嵌社區的典型使用場景 1、游戲內打開論壇 您可以在游戲內繪制論壇入口,為玩家提供沉浸式發帖、瀏覽、點贊、回帖、 ......

    uj5u.com 2023-04-19 09:15:46 more
  • iOS從UI記憶體地址到讀取成員變數(oc/swift)

    開發除錯時,我們發現bug時常首先是從UI顯示發現例外,下一步才會去定位UI相關連的資料的。XCode有給我們提供一系列debug工具,但是很多人可能還沒有形成一套穩定的除錯流程,因此本文嘗試解決這個問題,順便提出一個暴論:UI顯示例外問題只需要兩個步驟就能完成定位作業的80%: 定位例外 UI 組 ......

    uj5u.com 2023-04-19 09:14:53 more
  • FIDE重磅更新!性能飛躍!體驗有禮!

    FIDE 開發者工具重構升級啦!實作500%性能提升,誠邀體驗! 一直以來不少開發者朋友在社區反饋,在使用 FIDE 工具的程序中,時常會遇到諸如加載不及時、代碼預覽/渲染性能不如意的情況,十分影響開發體驗。 作為技術團隊,我們深知一件趁手的開發工具對開發者的重要性,因此,在2023年開年,FinC ......

    uj5u.com 2023-04-19 09:14:08 more
  • 游戲內嵌社區服務開放,助力開發者提升玩家互動與留存

    華為 HMS Core 游戲內嵌社區服務提供快速訪問華為游戲中心論壇能力,支持玩家直接在游戲內瀏覽帖子和交流互動,助力開發者擴展內容生產和觸達的場景。 一、為什么要游戲內嵌社區? 二、游戲內嵌社區的典型使用場景 1、游戲內打開論壇 您可以在游戲內繪制論壇入口,為玩家提供沉浸式發帖、瀏覽、點贊、回帖、 ......

    uj5u.com 2023-04-19 09:08:34 more