问题在于访问指针数组的每个地址都将我的数据合并到后续数据中
答案 0 :(得分:1)
如前所述,您的数组没有以空字符终止,这就是为什么 printf 在它们之后继续的原因。
之所以会得到这个结果,是因为编译器将数组一个接一个地放置在内存中,并且由于其他原因最终会出现一个空字符
所以最小的变化是
unsigned char mydata1[] = {0x41,0x42,0x43, 0};
unsigned char mydata2[] = {0x44,0x45,0x46, 0};
unsigned char mydata3[] = {0x47,0x48,0x49,0x4A, 0}
但是这样做的方式假定您的编译器使用ASCII代码,并且这是不可读的,最好这样做
unsigned char mydata1[] = {'A', 'B', 'C', 0};
unsigned char mydata2[] = {'D', 'E', 'F', 0};
unsigned char mydata3[] = {'G','H','I','J', 0};
或更简单:
unsigned char mydata1[] = "ABC";
unsigned char mydata2[] = "DEF";
unsigned char mydata3[] = "GHIJ";
除此之外
for(i = 0; i < 3; i++)
是危险,因为如果您将元素数量修改为 charPtr ,则还需要修改 for ,一种方法是添加一个NULL指针以标记指针列表的末尾并迭代一个NULL指针,另一种方法是在i < (sizeof(charPtr)/sizeof(charPtr[0]))
时进行迭代。 size_t
,因为这是索引的自然类型答案 1 :(得分:0)
#include <stdio.h>
#include <string.h>
/* String are NULL terminated, you might have read comments in question */
unsigned char mydata1[] = {0x41, 0x42, 0x43, 0x00};
unsigned char mydata2[] = {0x44, 0x45, 0x46, 0x00};
unsigned char mydata3[] = {0x47, 0x48, 0x49, 0x4A, 0x00};
/* Here I have used a NULL terminated array so that we can traverse
* even if we do not know the length of array
*/
unsigned char *charPtr[] =
{
mydata1,
mydata2,
mydata3,
NULL
};
int main()
{
int i;
for (i = 0; charPtr[i] != NULL; i++) {
printf("%s\n", charPtr[i]);
}
return 0;
}