将 char 数组传递给函数并在函数中提供每个索引内存(使用 malloc()),然后使用 gets() 从键盘插入内容,我做错了什么。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
void test(char *arr[]);
int main(){
char *arr[2];//2 is the rows
/* arr[0] = malloc(80);//This commented code works
arr[1] = malloc(80);
strcpy(arr[0], "hey");
strcpy(arr[1], "whats up");
*/
test(*arr);
printf("in array[0]: %s", arr[0]);
printf("in array[1]: %s", arr[1]);
return 0;
}
void test(char *arr[]){
int index;
char *input = malloc(80);
for(index = 0; index < 2; index++){
arr[index] = malloc(80);
gets(input);
strcpy(arr[index], input);
//arr[0] = input;
}
}
只是一个非常基本的程序,出于某种原因我遇到了麻烦。还有一个问题当我声明一个数组时,这些形式有什么区别
char *array
反对
char *array[size]
或
char **array
谢谢, 凯文
最佳答案
您将 arr
声明为 char *arr[2]
。然后传入 *arr
,它的类型为 char*
以进行测试。但是测试需要一个 char *[]
。所以那是行不通的。您应该按原样简单地传入 arr
,即 test(arr)
。
char * array
是指向字符的指针,通常用于指向字符数组(即字符串)中的第一个字符。
char **array
是指向字符的指针。通常用于表示字符串数组。
char *array[size]
大部分等同于上面的那个,但它不像那个,顶级指针已经指向一个有效的数组,所以数组不需要 malloc
ed.
顺便说一下,您的test
函数可以简化一点:strcopy
是不必要的。
void test(char *arr[])
{
int i;
for(i=0;i<2;i++)
{
arr[i] = malloc(80);
gets(arr[i]);
}
}
关于c - 通过引用传递字符串数组以在 C 中运行和修改内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13169215/