传递一个字符串数组在C函数 [英] Passing a string array to a function in C

查看:260
本文介绍了传递一个字符串数组在C函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚学C,有人能解释为什么以下code印花数组的第一个元素后产生分段故障?

I am just learning C, Could someone explain why the following code produces a Segmentation fault after printing the first element of an array?

会有什么工作code样子?

what would working code look like?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define ELEMENTS 8

void make(char ***array) {

*array = malloc(ELEMENTS * sizeof(char *));


    (*array)[0] = "test0";
    (*array)[1] = "test1";
    (*array)[2] = "test2";
    (*array)[3] = "test3";
    (*array)[4] = "test4";
    (*array)[5] = "test5";
    (*array)[6] = "test6";
    (*array)[7] = "test7";
    (*array)[8] = "test8";

}

int main(int argc, char **argv) 
{
char **array;
make(&array);

int i;
for (i = 0; i < ELEMENTS; ++i) {
    printf("%s\n", array[i]);
    free(array[i]);
}
free(array);
return 0;

}

推荐答案

当你把C ++如<$ ​​C $ C>TEST0,它实际上是存储在一个特殊的文本字符串存储器位置,它不能被修改。在行

When you put a literal string in C++ like "test0", it is actually stored in a special memory location where it cannot be modified. In the line

(*array)[0] = "test0";

你的指点的char * 该内存的位置,这是好的做。不过,后来,当你调用免费(数组[我]); ,您试图释放相同的内存,这是一个禁忌。一般情况下,只使用免费()如果你有previously使用的malloc()在同一个变量。

you're pointing your char* to that memory location, which is alright to do. However, later, when you call free(array[i]);, you are attempting to free the same memory, which is a no-no. In general, only use free() if you have previously used malloc() on the same variable.

此外,正如其他人所说,你需要分配大小9的数组,由于您使用的9个元素。

Also, as others have said, you need to allocate an array of size 9, since you're using 9 elements.

这篇关于传递一个字符串数组在C函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆