在此次代码中,需要用到指针数组,二级指针,malloc函数申请空间。
该函数功能实现必须要注意的是:malloc函数具体的申请的大小,即sizeof()的使用。
第一种方法只是普通的将字符串常量的首地址初始化给字符指针数组,注意字符指针数组是一个数组,只是里面存的是指向字符串的地址而已,数组里面存储的并不是具体的字符串,而是它们的各自的首地址。
但是第一种方法中的求指针数组的大小有点瑕疵,可以不用封装函数,直接求出。可以进行如下修改:
char *ptr[]={"nihao","my","name","is","wm","dege","hh"};//不用知道数组大小
int n=sizeof(ptr)/sizeof(ptr[0]); //只把指针数组看作一个存储指针的普通数组,就可以求未知数组的大小了。
第二种方法就明显高端一点,需要注意的是自己输入的时候,采用的到底是gets()还是scanf()函数,因为其中使用gets输入导致传入的值中,比如我需要输入逆序的字符串数量3个,但是只能手写输入2个字符串,也就是输入第二个后回车就完成了输入,无法输入第三个字符串,打印指针数组发现存储在第一位的值是NULL,其后依次为先前存储的2个字符串。
注意以下注释
//特别注意此处的大小申请,为指针数组申请内存
char **p=(char **)malloc(n*sizeof(char *));
if (p== NULL) {
printf("Memory allocation failed.\n");
return 1;
}
for (int i = 0; i <n; i++)
{//此处是在为指针数组的成员申请内存
p[i]=(char *)malloc(sizeof(char));
scanf("%s",p[i]);
}//以上申请的空间都要进行释放。p与p[i]都必须手动释放。
#include<stdio.h>
#include<stdlib.h>
void strNX(char **,int);
void print_ptr(char**,int);
//这里没必要封装一个计数的函数。
int num(char **);
//第一种方式,普通的设置初始化字符串,使用指针数组进行存储
// int main()
// {
// char *ptr[10]={"nihao","my","name","is","wm","dege","hh"};
// int n=num(ptr);
// print_ptr(ptr,n);
// strNX(ptr,n);
// print_ptr(ptr,n);
// return 0;
// }
//第二种需要自己输入
int main()
{
printf("输入的字符串个数\n");
int n=0;
scanf("%d",&n);
char **p=(char **)malloc(n*sizeof(char *));
if (p== NULL) {
printf("Memory allocation failed.\n");
return 1;
}
for (int i = 0; i <n; i++)
{
p[i]=(char *)malloc(sizeof(char));
scanf("%s",p[i]);
}
print_ptr(p,n);
strNX(p,n);
print_ptr(p,n);
for (int i = 0; i < n; i++)
{
free(p[i]);
}
free(p);
return 0;
}
void strNX(char **str,int n)
{
for (int i = 0; i < n/2; i++)
{
char *a=str[i];
str[i]=str[n-1-i];
str[n-1-i]=a;
}
}
void print_ptr(char** str,int n)
{
for (int i = 0; i < n; i++)
{
printf("%s ",str[i]);
}
puts("");
}
int num(char **str1)
{
int i=0;
while (*str1)
{
i++;
str1++;
}
return i;
}
这是chatgpt4写的方法二
- 动态地为一个指针数组分配内存,其中每个指针元素都指向一个动态分配的整数。
- 为每个动态分配的整数赋值,值为其索引的平方。
- 打印每个指针指向的整数值。
- 释放每个动态分配的整数的内存。
- 释放指针数组的内存。
#include <stdio.h>
#include <stdlib.h>
int main() {
int size; // 定义指针数组的大小
printf("Enter the size of the array: ");
scanf("%d", &size);
int **ptrArray; // 声明一个指向指针的指针,即一个指针数组
ptrArray = (int **)malloc(size * sizeof(int *)); // 为指针数组分配内存
if (ptrArray == NULL) {
printf("Memory allocation failed\n");
return 1;
}
for (int i = 0; i < size; i++) {
ptrArray[i] = (int *)malloc(sizeof(int)); // 为每个指针分配内存
if (ptrArray[i] == NULL) {
printf("Memory allocation for ptrArray[%d] failed\n", i);
return 1;
}
*(ptrArray[i]) = i * i; // 为每个动态分配的整数赋值
}
printf("Values stored in the dynamically created pointer array:\n");
for (int i = 0; i < size; i++) {
printf("ptrArray[%d] = %d\n", i, *(ptrArray[i]));
free(ptrArray[i]); // 释放每个动态分配的整数的内存
}
free(ptrArray); // 释放指针数组的内存
return 0;
}