Hello everyone:

I'm having a problem with vector indexing. The following code results in a segmentation fault:

for (int i = 0; i < (rows * rows); i++)
{
   temperature[(i * rows) + (rows - 1)] = 0;                                            
}

And:

for (int i = 0; i < (rows * rows); i++)
{
   temperature[i * rows] =  3;                                           
}

According to my reading, it is possible to use expressions involving calculation as vector indices. I would very much appreciate it if someone could suggest what I'm doing wrong.

Thank you for any help.

Dani AI

Generated

Short version: the expressions you used are legal, but the loop bounds are wrong. As pointed out, your index math must produce values strictly less than temperature.size(). The code shown in the thread multiplies the loop counter by rows while running rows*rows iterations, so the computed indices run far past the end of the vector and cause the segfault.

A clear, correct pattern for a flattened 2‑D array (row-major) is index = row * cols + col. For a square matrix (cols == rows) you can set the first/last column like this:

std::vector<double> temperature(rows * cols);

// set first and last column (row-major)
for (std::size_t r = 0; r < rows; ++r) {
    temperature[r * cols + 0] = 3.0;             // first column
    temperature[r * cols + (cols - 1)] = 0.0;    // last column
}

If you prefer to scan the flat vector and compute which column an element belongs to, compute row/col from the flat index:

for (std::size_t idx = 0; idx < temperature.size(); ++idx) {
    std::size_t col = idx % cols;
    if (col == 0)                         temperature[idx] = 3.0;
    if (col == cols - 1)                  temperature[idx] = 0.0;
}

Quick tips: use std::size_t or vector<T>::size_type for indices to avoid signed/unsigned bugs; use temperature.at(index) or assert(index < temperature.size()) when debugging; and run with AddressSanitizer (-fsanitize=address) or valgrind to catch out‑of‑bounds access. For filling every element, prefer a range loop or std::fill instead of manual index arithmetic. This keeps intent clear and prevents the exact off‑by‑one/overrun that caused the crash.

Recommended Answers

All 2 Replies

It is legal, as long as the expression evaluates to a value within the acceptable range of indexes.

The range of i is zero (0) thru (rows^2)-1. When you multiply i by rows, you dramatically increase its value to a point where it is outside the limits of the vector. For your example situation, you are better off not using an expression as an index.

Thanks a lot. I'm an idiot!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.