Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to pointer function parameter

The function should simply read a matrix. Why does it freeze after I enter the first character?

#include "stdafx.h"
#include <iostream>

using namespace std;

void as(char **p,int n,int m)
{
    int i, j;
    for (i = 0; i < n; i++)
        for (j = 0; j < m; j++)
        {
            cout << "p[" << i << "][" << j << "]=";
            cin >> p[i][j];
        }
}

int main()
{
    char *a[100];
    as(a, 3, 3);
    return 0;
}
like image 723
Beach Williams Avatar asked Nov 23 '25 22:11

Beach Williams


1 Answers

This is undefined behavior: your array is an array of 100 pointers to char. But you've never initialized them. So when you address p[i] it gets an uninitialized pointer that could point anywhere, and when you dereference it with p[i][j] you might then freeze or suffer of anyother symptom of undefined behavior.

If you want to learn to use pointers and arrays:

Solution 1: define your array as char a[100][100];

Solution 2: in the outer loop of as(), start to allocate the chars with p[i] = new char[m];

If you want to learn modern C++:

Solution 3: Forget about memory allocation and deallocation and use vectors instead. The vectors are totally dynamic, so no maximum of 100 rows anymore:

void as(vector<vector<char>> &p, int n, int m)
{
    p.resize(n); 
    int i, j;
    for (i = 0; i < n; i++) {
        p[i].resize(m); 
        for (j = 0; j < m; j++)
        {
            cout << "p[" << i << "][" << j << "]=";
            cin >> p[i][j];
        }
    }
}

int main()
{
    vector<vector<char>>a;
    as(a, 3, 3);
    return 0;
}

If you want to try online...

Solution 4: you want modern C++, but you'd like to use your the elements in a[] as they were a string, for easy output and manipulation, just use the same code as above but replace vector<vector<char>> with vector<string>

And here you can look online the slightly simplified code.

like image 178
Christophe Avatar answered Nov 25 '25 12:11

Christophe