LeetCode做题笔记(4)——error: variable-sized object may not be initialized|

This article summarizes the problems encountered when doing LeetCode topic 645, mainly the initialization of variable-length arrays.

645. Wrong collection

Question type

Array

Summary

  1. Each traversal can do multiple things at the same time. For example, when searching for duplicates, this question also finds the loss, that is, if-if-if type in the for loop, not if-elseif-else type.
  2. A set of algorithms may not be able to solve the problem directly. There are special situations that need to be specifically addressed, such as the situation where the 1 missing or n missing in this problem causes the algorithm to find the missing value.
  3. When using a variable to define the capacity of an array, it cannot be initialized at the same time! ! ! If you want to define an array to count the number of occurrences of each number, you need to determine the capacity of the array according to the parameter numsSize, but int counts[numsSize + 1] = { 0 };when using it, the system reports an error: error: variable-sized object may not be initializedthat variable-sized array may not be initialized! In fact int counts[numsSize + 1];, there is no problem with the declaration , the problem is the simultaneous initialization! This question belongs to the C language regulation, if you want to initialize, you must do it after the declaration. In fact, it is better to use dynamic memory allocation:
int *counts = (int *) malloc( (numsSize + 1) * sizeof(int) );
memset( counts, 0, (numsSize + 1)*sizeof(int) );

Guess you like

Origin www.cnblogs.com/uestcliming666/p/12751229.html