// vector is a template, the <int> means it is a vector of intsvector<int> numbers;
// push_back() puts a new value at the end (or back) of the vectorfor (int i = 0; i < 10; i++)numbers.push_back(i);
// Determine the size of the arraycout << numbers.size();
#include<stdio.h>#include<stdlib.h>int main(){
int a[10];
int *p;
printf("%p\n", (void *)a);printf("%p\n", (void *)(&a+1));printf("---- diff----\n");printf("%zu\n", sizeof(a[0]));printf("The size of array a is %zu\n", ((char *)(&a+1)-(char *)a)/(sizeof(a[0])));
return 0;};
这是示例输出
15492166721549216712---- diff----4The size of array a is 10
/* Absolutely no one should use this...By the time you're done implementing it you'll wish you just passed aroundan array and size to your functions *//* This is a static implementation. You can get a dynamic implementation andcut out the array in main by using the stdlib memory allocation methods,but it will work much slower since it will store your array on the heap */
#include <stdio.h>#include <string.h>/*#include "MyTypeArray.h"*//* MyTypeArray.h#ifndef MYTYPE_ARRAY#define MYTYPE_ARRAY*/typedef struct MyType{int age;char name[20];} MyType;typedef struct MyTypeArray{int size;MyType *arr;} MyTypeArray;
MyType new_MyType(int age, char *name);MyTypeArray newMyTypeArray(int size, MyType *first);/*#endifEnd MyTypeArray.h */
/* MyTypeArray.c */MyType new_MyType(int age, char *name){MyType d;d.age = age;strcpy(d.name, name);return d;}
MyTypeArray new_MyTypeArray(int size, MyType *first){MyTypeArray d;d.size = size;d.arr = first;return d;}/* End MyTypeArray.c */
void print_MyType_names(MyTypeArray d){int i;for (i = 0; i < d.size; i++){printf("Name: %s, Age: %d\n", d.arr[i].name, d.arr[i].age);}}
int main(){/* First create an array on the stack to store our elements in.Note we could create an empty array with a size instead andset the elements later. */MyType arr[] = {new_MyType(10, "Sam"), new_MyType(3, "Baxter")};/* Now create a "MyTypeArray" which will use the array we justcreated internally. Really it will just store the value of the pointer"arr". Here we are manually setting the size. You can use the sizeoftrick here instead if you're sure it will work with your compiler. */MyTypeArray array = new_MyTypeArray(2, arr);/* MyTypeArray array = new_MyTypeArray(sizeof(arr)/sizeof(arr[0]), arr); */print_MyType_names(array);return 0;}
int a[10];size_t size_of_array = sizeof(a); // Size of array aint n = sizeof (a) / sizeof (a[0]); // Number of elements in array asize_t size_of_element = sizeof(a[0]); // Size of each element in array a// Size of each element = size of type