簡體   English   中英

將int數組轉換為字符串,然后使用printf打印,而不分配新的內存

[英]Cast an int array to string, then print with printf, without allocating new memory

我以為我解決了這個問題,但是顯然我是不對的。 問題是...我想念什么?

作業說明:

您將創建一個用整數填充整數數組的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

看來您已經掌握了核心思想:一個整數的空間將容納許多字符。 我相信您只需要“手動”打包整數數組,而不是在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;
}

聽起來好像您的教授希望您將4個字節放入每個int而不要使用n “ 1個字節” int的數組,然后您使用while循環將其壓縮為4 / sizeof(int)字節。 根據Hurkyl的評論,此分配的解決方案將取決於平台,這意味着它因機器而異。 我假設您的講師將ssh放進了課堂並使用一台特定的機器?

無論如何,假設您使用的是小型Endian機器,請說您要輸入字符串:“嗨,爸爸!”。 然后,該解決方案的摘要如下所示:

// 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM