[英]C, char** strange output
#include <stdio.h>
char** StringArray ( int n_size )
{
char* astr_allocate[ n_size ];
char** pstr_string_array = astr_allocate;
int n_count;
for ( n_count = 0; n_count < n_size; n_count++ )
*(pstr_string_array + n_count) = " ";
*(pstr_string_array + n_size) = "\0";
return pstr_string_array;
}
char* String ( int n_size )
{
char ach_allocate[ n_size ];
char* str_string = ach_allocate;
int n_count;
for ( n_count = 0; n_count < n_size; n_count++ )
*(str_string + n_count) = ' ';
*(str_string + n_size) = '\0';
return str_string;
}
void main ()
{
int n_size = 5;
int n_count ;
char* pch_string = String ( n_size );
char** pstr_string = StringArray ( n_size );
for ( n_count = 0; n_count < n_size; n_count++ )
printf ( "%c", *(pch_string + n_count) );
for ( n_count = 0; n_count < n_size; n_count++ )
printf ( "%s", *(pstr_string + n_count) );
printf ( "\n\n" );
}
This produces wonderful outputs of "???"这产生了“???”的精彩输出(Literal question marks) and random stuff like that. (字面问号)和诸如此类的随机内容。 I am just trying to understand pointers and string type stuff more, if someone could help out that would be great thankyou!我只是想更多地了解指针和字符串类型的东西,如果有人能帮忙,那就太好了,谢谢!
additionally: Been writing and compiling this in a linux terminal and nano, if that changes anything另外:在Linux终端和nano中编写和编译它,如果有任何改变
I would recommend that you study arrays, pointers and strings more.我建议你多研究数组、指针和字符串。
int main (void)
.由于此程序是用于常规托管系统 (Linux) 的程序,因此您必须将 main 声明为int main (void)
。int arr[2];
意思是给定一个数组int arr[2];
the items have index [0] and [1].项目具有索引 [0] 和 [1]。 Therefore you can't access it as arr[2] = ...
or *(arr + 2) = ...
, because that points past the end of the array.因此,您不能以arr[2] = ...
或*(arr + 2) = ...
访问它,因为它指向数组末尾。*(pstr_string_array + n_count) = " ";
给定一个指向字符的指针,它指向一个字符数组(C 字符串),您不能通过执行诸如*(pstr_string_array + n_count) = " ";
类的操作来为其分配数据*(pstr_string_array + n_count) = " ";
because that will only change where the pointer points at!因为那只会改变指针指向的位置! You copy nothing.你什么都不复制。 Instead, you must use strcpy(pointer, " ", 2)
.相反,您必须使用strcpy(pointer, " ", 2)
。" "
is the same as an array of characters char arr [2] = {' ', '\\0'}
.字符串文字" "
与字符数组char arr [2] = {' ', '\\0'}
。 So code like "\\0"
doesn't make any sense.所以像"\\0"
这样的代码没有任何意义。*(pointer + n)
is 100% equivalent to pointer[n]
.请注意*(pointer + n)
100% 等价于pointer[n]
。 The latter is easier to read, so use that form when possible.后者更易于阅读,因此请尽可能使用该形式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.