2012-07-19 24 views
1

这里有新的东西,试图在你们的帮助下学习一块C,这可能是一个基本的问题......抱歉,你已经从基础开始。试图打印表单数组或数组地址...没有得到它?

void main() 
{ 

char* arr[3] = {"baba","tata","kaka"}; 

char* arr1[3] = {"baba1","tata1","kaka1"}; 

char* arr2[3] = {"baba2","tata2","kaka2"}; 

char** array_all[] = {arr,arr1,arr2}; 

printf("%s\n",*array_all[0]); 

//please guide me how to access individual entity(as arr[1], arr1[2],arr3[1])  //from each array using array_all 

} 

回答

3

我不确定这是不是你正在寻找..但这是我了解到目前为止。

你想要访问array_all的各个元素(元素arr,arr1和arr2)?如果是这样,那么你所做的只是...

array_all[0][i]; 

其中我是你想访问的元素。

原因是因为索引运算符([和])实际上取消引用了一个指针,并且偏移了指定的指针(如添加了某个整数,即在内存中向下移动)。如果你不知道如果你通过某个整数添加一个指针会发生什么,我建议读一下指针算术。

例如:

int x[] = { 1, 2, 3 }; 
// writing x[i] is the same as *(x + i) 
int i = 2; // the element you wish to access 
*(x + i) = 4; // set the ith (3rd) element to 4 
*(x + 1) = 43; // set the 2nd element to 43 

// Therefore... 
// x now stores these elements: 
// 1, 43, 4 

// proof: print out all the elements in the array 
for(int i = 0; i < 3; ++i) 
{ 
    printf("x[%i]=%i\n", i, x[i]); 
} 

此外,写入X [0]相同,书写* X中,由于阵列名称实际上指向该阵列的第一个元素。

OH和一件事,主要实际上应该返回一个整数结果。这主要用于程序中的错误检查,0通常表示没有错误发生,并且每个其他错误代码(0以外的数字)都是与您的程序相关的一些特定错误,您可以选择。 即

int main() 
{ 
    // e.g. for an error code 
    /* 
    if(someErrorOccured) 
    { 
     return SOME_ERROR_OCCURED_RETURN_VALUE; 
    } 
    */ 
    return 0; // this is at the end of the function, 0 means no error occured 
} 
+0

感谢miguel.martin ...你的努力表示感谢。我喜欢你解释它的方式。朋友,谢谢。 – studyembedded 2012-07-19 07:53:01

+0

@studyembedded你应该投票并接受这个答案,如果它对你最有帮助。 – 2012-07-19 15:15:57

+0

数组索引的优秀详细解释!然而,考虑到OP的用户名是“学习嵌入式”,最终的'一件事'可能不适用,因为没有OS返回。在这种情况下,使用'while(1);'(或在while(1)'循环中运行连续任务)来结束main通常更有用,以便调试器可以在任务之后检查系统的状态已经完成了。 – 2012-07-19 16:13:56

1

变化与此您的printf语句行..

printf("%s\n",array_all[i][j]); 

代替我的让您的序列号,并在地方k的给你所需的元素数量。有用。

+0

你的意思是“代替* j *”吗? – 2012-07-19 15:16:33