如何在C语言中分割二维数组的行?含跨行连续值计数需求
Got it, let's fix the issue where your code was incorrectly merging consecutive elements across rows. The key here is to process each row independently—so we never carry over counts from one row to the next, even if the last element of a row matches the first of the next.
Step 1: Clarify the Input Structure
First, let's convert your flat input list into the 4x6 2D array as specified:
width = 6 height = 4 input_elements = [0, 1, 2, 2, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0] # Split into 4 rows of 6 elements each matrix = [input_elements[i*width : (i+1)*width] for i in range(height)]
This gives us the clear 2D structure:
- Row 1:
[0, 1, 2, 2, 1, 0] - Row 2:
[1, 0, 0, 0, 0, 1] - Row 3:
[1, 0, 0, 0, 0, 1] - Row 4:
[0, 1, 1, 1, 1, 0]
Step 2: Per-Row Counting Function
We'll write a function that counts consecutive non-zero elements only within a single row, resetting the count at the start of each row:
def count_consecutive_non_zero(row): counts = [] current_streak = 0 for num in row: if num != 0: current_streak += 1 else: # When we hit a 0, save the streak if it's non-zero if current_streak > 0: counts.append(current_streak) current_streak = 0 # Don't forget to save the streak if the row ends with non-zero if current_streak > 0: counts.append(current_streak) return counts
Step 3: Generate the Desired Output
Loop through each row and apply the function:
for idx, row in enumerate(matrix, 1): result = count_consecutive_non_zero(row) # Format as space-separated string print(f"第{idx}行:{' '.join(map(str, result))}")
Final Output
Running this code will give you exactly what you're expecting:
- 第1行:1 2 1
- 第2行:1 1
- 第3行:1 1
- 第4行:4
Why This Fixes the Cross-Row Issue
The mistake in your original code was likely keeping the current_streak variable outside the row loop—so it would keep counting from the end of one row to the start of the next if the values matched. By initializing current_streak inside the function (per row), we ensure each row starts fresh, with no leftover counts from previous rows.
内容的提问来源于stack exchange,提问作者승기유

