Ç - 阵列不能使用变量索引 [英] C - Array cant use variable for index

查看:119
本文介绍了Ç - 阵列不能使用变量索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用一个变量作为数组的索引有问题。在code基本上是这样的:

I'm having a problem using a variable as an index for an array. The code is basically this:

int index;
void main() {
    index = 1;
    doStuff();
}
void doStuff() {
    char** myArray;
    myArray[0] = (char*)"Foo";
    myArray[1] = (char*)"Bar";
    print("%s", myArray[index]);
}

现在,如果我做的:

print("%s", myArray[1]);

它工作正常。谁能帮助我?

It works fine. Could anyone help me out?

这应该只是C code,但在它的问题的情况下,其对视差芯片,并且我用简单的IDE。

It should just be C code, but in the event that it matters, its for a Parallax chip, and I'm using Simple IDE.

推荐答案

您阵列

char** myArray;

是不是一个真正的数组。它是一个指针。直到你分配给它,它指向无处。它的任何指针引用产生不确定的行为。

is not really an array. It is a pointer. Until you assign it, it points nowhere. Any dereferences of it produce undefined behavior.

解引用未定义的指针为precisely你在这里做的:

Dereferencing the undefined pointer is precisely what you do here:

myArray[0] = (char*)"Foo";

由于指针没有指向的内存块有效,这是行不通的。你需要做的,使其工作什么是分配 myArray的第一。例如,你可以用做的malloc

Since the pointer does not point to a valid block of memory, this does not work. What you need to do to make it work is assign myArray first. For example, you could do it with malloc:

char** myArray = malloc(2 * sizeof(char*));

您code会现在的工作。为了避免内存泄漏,添加免费(myarray的) doStuff年底功能。

Your code is going to work now. In order to avoid memory leaks, add free(myArray) to the end of doStuff function.

这篇关于Ç - 阵列不能使用变量索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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