[英]Passing Array of String as Argument to Function
I am trying to pass an array of strings to a function and then the print it there.我正在尝试将字符串数组传递给 function 然后在那里打印。 But it is giving segmentation fault.
但它给出了分段错误。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char *str[2];
for(int i=0;i<2;i++) {
scanf("%s",(str+i));
}
display(str);
}
void display(char **p)
{
for(int i=0;i<2;i++) {
printf("%s \n",p[i]);
}
}
I think the problem is that you are not allocating memory for your list.我认为问题在于您没有为您的列表分配 memory 。 Here is a sample code that i made.
这是我制作的示例代码。
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#define LIST_SIZE 2
#define MAX_WORD 100
void display(char**);
int main() {
char buffer[100];
char** list;
int i;
int n;
// allocate
list = (char**)malloc(sizeof(char*) * LIST_SIZE);
for(i = 0; i < LIST_SIZE; i++) {
scanf("%99s",buffer);
n = strlen(buffer);
list[i] = (char*)malloc(sizeof(char) * n);
strcpy(list[i], buffer);
}
display(list);
return 0;
}
void display(char** str) {
int i;
printf("-- output ---\n");
for(i = 0; i < LIST_SIZE; i++) {
printf("%s\n", str[i]);
}
}
I made the list only allocate the space necessary for the word.我使列表仅分配单词所需的空间。 If you want fixed you dont need a buffer and the strcpy.
如果要修复,则不需要缓冲区和 strcpy。
For starters, you need to make the following change in the "display" function....对于初学者,您需要在“显示”function...中进行以下更改。
printf("%s \n",p+i);
In addition, the "display" function needs to be placed above "main" or you need to declare a prototype for the function.此外,“显示”function 需要放在“主”上方,或者您需要为 function 声明原型。
What about this:那这个呢:
void display(char * p[])
This way you can pass the argument这样你就可以传递参数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.