指向数组的指针数组。在 PIC18 MPLAB IDE 中打印字符串
我正在使用 MPLAB IDE 编写在 PIC 18 微控制器中使用的 C 代码。 我有 5 个字符串,我希望能够使用指针。 这个想法是拥有一个包含指向字符串数组的指针的数组。并将它们打印在控制台上。 下面的代码编译时没有错误或警告,但我在控制台上得到的都是垃圾。
有人能指出我正确的方向吗?非常感谢。 抱歉,如果我的代码格式不正确。
#include <stdio.h>
#include <p18f4520.h>
#include <stdlib.h>
#pragma config WDT = OFF
#define size 64
#pragma romdata s1=0x300 //specific ROM addresses for the data
rom char *s1[] = "Hello";
#pragma romdata s2 = 0x307
rom char *s2 = "Welcome to C programming";
#pragma romdata s3=0x31A
rom char *s3= "My name is ";
#pragma romdata s4=0x32C
rom char *s4 = "Pic18 program";
#pragma romdata s5=0x33A
rom char *s5 ="Goodbye, I hope this works!";
void printString(const char*);
void main (void)
{
int i=0;
char stringArray [] = {*s1, *s2, *s3, *s4, *s5};
char *ptr=stringArray;
while(i<5)
{
printString(&ptr[i]);
i++;
}
}
void printString( const char *strPtr)
{
while(*strPtr !='\0')
{
printf("%c", strPtr);
strPtr++;
}
}
`
I am writing a C-code to use in PIC 18 micro-controller using MPLAB IDE.
I have 5 strings and I want to be able to use pointers.
The idea is having an array containing the pointers to the string arrays. and have them print on the console.
The code below compiles with No errors or warnings, but all I get on the console is garbage.
Can someone point me to the right direction. many thanks.
sorry if my formatting of the code is not right.
#include <stdio.h>
#include <p18f4520.h>
#include <stdlib.h>
#pragma config WDT = OFF
#define size 64
#pragma romdata s1=0x300 //specific ROM addresses for the data
rom char *s1[] = "Hello";
#pragma romdata s2 = 0x307
rom char *s2 = "Welcome to C programming";
#pragma romdata s3=0x31A
rom char *s3= "My name is ";
#pragma romdata s4=0x32C
rom char *s4 = "Pic18 program";
#pragma romdata s5=0x33A
rom char *s5 ="Goodbye, I hope this works!";
void printString(const char*);
void main (void)
{
int i=0;
char stringArray [] = {*s1, *s2, *s3, *s4, *s5};
char *ptr=stringArray;
while(i<5)
{
printString(&ptr[i]);
i++;
}
}
void printString( const char *strPtr)
{
while(*strPtr !='\0')
{
printf("%c", strPtr);
strPtr++;
}
}
`
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
嗯,这就是答案。
Well This is the answer.
问题是在您的代码中, stringArray 代表存储每个字符串的第一个字符的内存块,而不是它们的地址,请尝试以下操作:
The problem is that in your code, stringArray stands for a memory block that stores the first character of each string, not the address of them, try this:
该代码中有几个基本错误。就用这个吧。
There are several fundamental errors in that code. Use this one instead.
试试这个:
它简化并进行了多项修复,修复问题最重要的是消除了
stringArray
中每个字符串名称之前的*
。其他更改是按惯例的 C 编码进行的。Try this instead:
It simplifies and makes several fixes, the most significant to fix the problem was eliminating the
*
before each string name instringArray
. Other changes are made to be customary C coding.