2017-02-25 11 views
0

malloc()を使用して割り当てたバイトに書き込もうとしています。私は本当にビットと値を正しく印刷するのに苦労しています。バイト単位での印刷と書き込み

int main(){ 

    unsigned char *heap = (unsigned char *) malloc(2 * sizeof(char)); //allocate two bytes 

    int n= 2, i =0; 
    unsigned char* byte_array = heap; 

    while (i < 2) //trying to write over the first byte then print out to verify 
    { 
     printf("%016X\n", heap[i]); 
     heap[i] = "AAA"; 
     printf("%p\n", heap[i]); 
     i++; 
    } 
} 

これは私がこのコードを試してみてくださいC.で "文字列" と 'C' の文字の違いを理解するには

0000000000000000 
0xc7 
0000000000000000 
0xc7 
+4

'heap [i] =" AAA "'は何をすると思いますか? '' AAA ''は' 'unsigned char'ではありません。 – Ryan

+0

どこから始めますか?あなたのコンパイラは、 'heap [i] =" AAA ";' - 'unsigned char'に' char * 'を代入しようとしています。それは問題があることを示しています。 'heap [i]'をポインタとして出力しようとしていますが、ポインタではありません。 'unsigned char'です。あなたのコンパイラが警告を無視する余裕はありません - あなたのキャリアのこの段階では、あなたのコードのすべての誤り(またはあなたのコードの理解)です。後で、彼らは誤りです。彼らはもうこれ以上の質問を引き起こさないでしょう。 –

+0

この投稿に 'byte_array'を保存するというポイントがありましたか? – WhozCraig

答えて

0

を取得しています出力されます。

#include <stdio.h> 

int main(){ 

    /* Usual way */ 
    char *a = "A"; 
    char *b = "B"; 
    char *c = "C"; 

    printf("Address of a = 0x%x\n",a); 
    printf("Address of b = 0x%x\n",b); 
    printf("Address of c = 0x%x\n",c); 

    /* Explicit way - Because you asked above question */ 
    printf("This is Base Address of String A = 0x%x\n","A"); 
    printf("This is Base Address of string B = 0x%x\n","B"); 
    printf("This is Base Address of string C = 0x%x\n","C"); 

    /* Now, let us print content - The usual way */ 
    printf("Pointer value a has %x\n",*a); 
    printf("Pointer value b has %x\n",*b); 
    printf("Pointer value c has %x\n",*c); 

    /* The unusual way */ 
    printf("Value of String A %x\n",*"A"); 
    printf("Value of String B %x\n",*"B"); 
    printf("Value of String C %x\n",*"C"); 

} 

上記のchar *はunsigned intとしてフォーマットされているのでコンパイラの警告が生成されますが、例を理解するために無視します。

出力は次のようになります。すべての

Address of a = 0xedfce4a 
Address of b = 0xedfce4c 
Address of c = 0xedfce4e 
This is Base Address of String A = 0xedfce4a 
This is Base Address of string B = 0xedfce4c 
This is Base Address of string C = 0xedfce4e 
Pointer value a has 41 
Pointer value b has 42 
Pointer value c has 43 
Value of String A 41 
Value of String B 42 
Value of String C 43 
0

まず、あなたが本当に意味を知らなくても、いくつかの操作を行っている:Cのcharは1つだけの文字を含めることができます

while (i < 2) 
{ 
    printf("%016X\n", heap[i]); // You're printing the value of heap[i] in hexadecimal that 
           // is not even setted 
    heap[i] = "AAA";   // This operation has no sense, 'cause a 
           // "char" can only contain 1 character 


    printf("%p\n", heap[i]); // You are printing a pointer, why? 
    i++; 
} 

。これは意味があります:

char a = 'b'; 

、あなたがcharの配列を必要とする文字列を持つようにしたい場合は:続きを読むhere

について

char * a = "AAA"; 

をだから私は、コードを書き換えます次のようにします:

while (i < 2){ 
    printf("First: %c\n",heap[i]); 
    heap[i] = 'a'; 
    printf("After: %c\n",heap[i]); 
    i++; 
} 
関連する問題