Skip to main content

Cách khai báo mảng 1 chiều trong C/C++

Cách định nghĩa mảng trong lập trình căn bản C/C++
1. Khai báo cấp phát cố định


int a[100];
 // khai báo xin cấp phát 1 mảng 1 chiều gồm có 100 phần tử
Nên #define số luợng phần tử truớc để dễ quản lý
#define ARRAY_SIZE 5
int anArray[ARRAY_SIZE]; 
Đối với cách này đòi hỏi phải "luờng" truơc đuợc số phần sử khi chuơng trình sử dụng.
Hạn chế sử dụng cách này vì sẽ phí bộ nhớ
/* malloc example: random string generator*/
#include <stdio.h>      /* printf, scanf, NULL */
#include <stdlib.h>     /* malloc, free, rand */

int main ()
{
  int i,n;
  char * buffer;

  printf ("How long do you want the string? ");
  scanf ("%d", &i);

  buffer = (char*) malloc (i+1);
  if (buffer==NULL) exit (1);

  for (n=0; n<i; n++)
    buffer[n]=rand()%26+'a';
  buffer[i]='\0';

  printf ("Random string: %s\n",buffer);
  free (buffer);

  return 0;
}

2. Khai báo cấp phát động
Đối với ngôn ngữ C ta sử dụng toán tử malloc
int *myArray;
myArray = (int*)malloc(n*sizeof(int));
Đỗi với C++ ta sử dụng toán tử new

#define ARRAY_SIZE 5
int *myArray;
myArray = new int[ARRAY_SIZE];
Lưu ý: Đối với dạng sử dụng con trỏ sau khi sử dụng nhớ sử dụng toán tử delete để hủy nó khi không còn sử dụng.

#include <iostream>
#include <new>
using namespace std;

int main ()
{
  int i,n;
  int * p;
  cout << "How many numbers would you like to type? ";
  cin >> i;
  p= new (nothrow) int[i];
  if (p == nullptr)
    cout << "Error: memory could not be allocated";
  else
  {
    for (n=0; n<i; n++)
    {
      cout << "Enter number: ";
      cin >> p[n];
    }
    cout << "You have entered: ";
    for (n=0; n<i; n++)
      cout << p[n] << ", ";
    delete[] p;
  }
  return 0;
}
Tham khảo thêm ở:

Comments

Popular posts from this blog

Socket Android Client to PC Server C#

Using AsynCallback C# Android Client connect Server C# Source code:  http://ow.ly/OlXj309O1mj c# socket multi client, socket c# example, socket server c#, socket c# tutorial, asynchronous socket in c#, c# socket multiple clients, c# socket server multiple clients, Download source code:  Click Here

Bài tập thuật toán C/C++ Và Tuyển tập đề thi olympic

Gồm: +  Các thuật toán của Lê Minh Hoàng + Tuyển tập các đề thi olympic tin học sinh viên Link down: Tại đây

Cross Platform Mobile App: Demo shop with flutter

Cross Platform Mobile App: Demo shop with flutter So cool framework from google <3  Demo:  Demo Code console.print("hello")