[英]Pointers and char arrays from strings
Hi I have been reading for hours and still can't grasp the conversions between嗨,我已经阅读了几个小时,但仍然无法掌握之间的转换
{
char i ="adf";
char foo[];
char bar[256];
}
and adding *
and &
makes it more confusing并添加
*
和&
使其更加混乱
I have some code that is working.我有一些正在运行的代码。
int TX_SEND(char send[])
{
unsigned char *p_tx_buffer;
p_tx_buffer = &send[0];
strcat(send, "\r");
// Write to the port
int n = write(fd,&send[0],3);
if (n < 0) {
perror("Write failed - ");
return -1;
}
return(0);
}
code is working but I need help with 2 parts.代码正在运行,但我需要两部分的帮助。
printf IE TX_SEND("AT+CGMSD=STUFF");
printf IE TX_SEND("AT+CGMSD=STUFF");
一样运行这个函数printf IE TX_SEND("AT+CGMSD=STUFF");
but I am stuckbut before hand I do this alot.但在此之前,我经常这样做。
char txsend[] = "at";
TX_SEND(txsend);
TX_WRITE()
I am using write(fd,&send[0],3)
, but it is hardcoded to send 3 bytes from send[]
.TX_WRITE()
我正在使用write(fd,&send[0],3)
,但它被硬编码为从send[]
发送 3 个字节。 I want this to be dynamic so I can just send strings at any length (realistically they will be less than 300 ASCII chars always).*p_tx_buffer
was my beginning attempt).*p_tx_buffer
是我的开始尝试)。i think you want我想你想要
int TX_SEND(char *send)
{
int n = write(fd,send,strlen(send));
if (n < 0) {
perror("Write failed - ");
return -1;
}
return(0);
}
you cannot tack on \\n to send with strcat.你不能加上 \\n 用 strcat 发送。 I would add it in the calling function, or declare an intermediate buffer and sprintf to it
我会将它添加到调用函数中,或者声明一个中间缓冲区和 sprintf 到它
like this像这样
int TX_SEND(char *send)
{
char buff[50]; // i dont know a good max size
snprintf(buff, sizeof(buff), "%s\n", send);
int n = write(fd,buff,strlen(buff));
if (n < 0) {
perror("Write failed - ");
return -1;
}
return(0);
}
I'm not going to go through your code line-by-line, but I urge you to focus on these facts:我不会逐行检查您的代码,但我敦促您关注以下事实:
'\\0'
).'\\0'
结尾)。&
in front of something, what you get is a pointer to that something.&
放在某物前面时,你得到的是一个指向那个东西的指针。*
in front of a pointer, what you get is the thing that the pointer points to.*
时,你得到的是指针指向的东西。 Putting this together, we could write把这些放在一起,我们可以写
char str[] = "xyz";
char *p = str; /* per rule 5, this is fine, and p gets a pointer to str's first element */
char c = *p; /* per rule 7, c gets the first character of str, which is 'x' */
printf("%c\n", c);
If you're just starting with C, you may not have come across rule 5 yet.如果您刚开始使用 C,您可能还没有遇到规则 5。 It will probably surprise you at first.
一开始可能会让你大吃一惊。 Learn it well, though: you'll never understand arrays and pointers in C without it.
但是,好好学习它:没有它,您将永远无法理解 C 中的数组和指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.