Learn point C language (36): function

Source: Internet
Author: User
Tags printf

The array parameter belongs to the pointer parameter.

Pointer parameter immediate address parameter (or reference parameter), this is the only way to modify the value of a parameter in a function.

If you take an array as an argument, whether you like it or not, it's a pointer to a pointer to the first value.

1. An array parameter is a pointer to the first element:

#include <stdio.h>

void getArr(int p[], int si);

int main(void)
{
  int ns[] = {1,2,3,4,5};

  getArr(ns, sizeof(ns)/sizeof(ns[0]));

  getchar();
  return 0;
}

void getArr(int p[], int si) {
  int i;
  for (i = 0; i < si; i++) {
    printf("%d\n", p[i]);
  }
}

2. Simply declare it directly as a pointer:

#include <stdio.h>

void getArr(int *p, int si);

int main(void)
{
  int ns[] = {1,2,3,4,5};

  getArr(ns, sizeof(ns)/sizeof(ns[0]));

  getchar();
  return 0;
}

void getArr(int *p, int si) {
  int i;
  for (i = 0; i < si; i++) {
    printf("%d\n", p[i]);
  }
}

3. Even if you specify a dimension in the parameter, it does not work:

#include <stdio.h>

void getArr(int p[2], int si);

int main(void)
{
  int ns[] = {1,2,3,4,5};

  getArr(ns, sizeof(ns)/sizeof(ns[0]));

  getchar();
  return 0;
}

void getArr(int p[2], int si) {
  int i;
  for (i = 0; i < si; i++) {
    printf("%d\n", p[i]);
  }
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.