我以为我解决了这个问题,但显然我错了。问题是......我错过了什么?
作业说明:
您要创建一个用整数填充整数数组的C程序,然后将其转换为字符串并将其打印出来。字符串的输出应该是您的第一个和最后一个具有适当大写,间距和标点符号的名称。您的程序应具有类似于以下的结构:
main()
{
int A[100];
char *S;
A[0]=XXXX;
A[1]=YYYY;
...
A[n]=0; -- because C strings are terminated with NULL
...
printf("My name is %s\n",S);
}
回复我提交的内容:
您仍然将内存单元格复制到其他内容,这是不期望的。您对整数数组使用不同的空格作为不符合要求的字符串。请在下次仔细按照说明操作。
我的提交
请注意,我第一次提交时,我只是在S上使用malloc,并将已转换的值从A复制到S. 响应是我无法使用malloc或分配新空间。 此要求不在上面的问题描述中。
以下是我的第二次也是最后一次提交,即上面提交的回复中提到的提交。
#include <stdio.h>
/* Main Program*/
int main (int arga, char **argb){
int A[100];
char *S;
A[0] = 68;
A[1] = 117;
/** etc. etc. etc. **/
A[13] = 115;
A[14] = 0;
// Point a char pointer to the first integer
S = (char *) A;
// For generality, in C, [charSize == 1 <= intSize]
// This is the ratio of intSize over charSize
int ratio = sizeof(int);
// Copy the i'th (char sized) set of bytes into
// consecutive locations in memory.
int i = 0;
// Using the char pointer as our reference, each set of
// bits is then i*ratio positions away from the i'th
// consecutive position in which it belongs for a string.
while (S[i*ratio] != 0){
S[i] = S[i*ratio];
i++;
}
// a sentinel for the 'S string'
S[i] = 0;
printf("My name is %s\n", S);
return 0;
}// end main
答案 0 :(得分:2)
看起来你有一个核心思想:一个整数的空间将容纳许多字符。我相信你只需要“手动”而不是在for循环中打包整数数组。假设在小端机器上有一个4字节的整数,请给它一个镜头。
#include <stdio.h>
int main()
{
int x[50];
x[0] = 'D' | 'u' << 8 | 's' << 16 | 't' << 24;
x[1] = 0;
char *s = (char*)x;
printf("Name: %s\n", s);
return 0;
}
答案 1 :(得分:2)
听起来你的教授希望你把4个字节放到每个int
而不是一个n
“1字节”整数的数组中,你后来使用它来压缩成4 / sizeof(int)
个字节while循环。根据Hurkyl的评论,这项任务的解决方案将取决于平台,这意味着它将因机器而异。我假设你的教练有类ssh并使用特定的机器?
在任何情况下,假设你在一台小端机器上,说你想输入字符串:“嗨爸爸!”。然后解决方案的片段看起来像这样:
// Precursor stuff
A[0] = 0x44206948; // Hi D
A[1] = 0x216461; // ad!
A[2] = 0; // Null terminated
char *S = (char *)A;
printf("My string: %s\n", S);
// Other stuff