二级指针做函数输出特性
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getMem(char ** p) {
if (p == NULL)
{
return -1;
}
char *tmp = (char *)malloc(sizeof(char) * 100);
if (tmp == NULL)
{
return -2;
}
strcpy(tmp, "hello world");
*p = tmp;
return 0;
}
int main() {
char * p = NULL;
int ret = 0;
ret = getMem(&p);
if (ret != 0)
{
printf("getMem error..\n");
return ret;
}
printf("p = %s\n", p); //p = hello world
if (p != NULL)
{
free(p);
}
return 0;
}
指针数组的使用
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char * p1 = "aaaaa";
char * p2 = "bbbbb";
char * p3 = "ccccc";
char * p4 = "ddddd";
//指针数组,每个元素都是一个char * 类型
char *arr[] = {"aaaaa", "bbbbb", "ccccc", "ddddd"};
int n = sizeof(arr) / sizeof(arr[0]);
for (size_t i = 0; i < n; i++)
{
printf("%s\n", arr[i]);
}
return 0;
}
一维数组
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int a[] = {1, 2, 3, 4}; // 4个元素
int b[100] = {1, 2, 3, 4}; //没有赋值的都是0
int n = sizeof(a) / sizeof(a[0]);
for (size_t i = 0; i < n; i++)
{
// printf("%d ", a[i]);
// a+i代表第i个元素的地址
printf("%d ", *(a+i)); //1 2 3 4
}
return 0;
}
网友评论