我正在處理C中的矢量類,並且我在使用getchar()
時遇到了一些問題。雖然我知道getchar()
將返回一個整數/無符號字符,但它似乎行爲有所不同,當從getchar()
的值分配給c中的一個動態創建的數組。我有一些代碼,我測試表明:C - getchar和動態創建的數組
#include <stdio.h>
#include <stdlib.h>
int main(){
char **ptr;
ptr=calloc(10,sizeof(char));
unsigned char c = getchar();
printf("%c\n", c); //this prints a normal value
ptr[0] = &c; //dereference the value to assign it to the dynamic array
printf("%s",ptr[0]); // This prints an odd value
}
這裏是從該代碼輸出得出:
[[email protected]] hw4 $ ./hw4Test
g
g
g▒▒[[email protected]] hw4 $ ./hw4Test
j
j
j▒~[[email protected]] hw4 $ ./hw4Test
q
q
q▒[[email protected]] hw4 $ ./hw4Test
r
r
r0▒
,當我試圖實現這個代碼到我的代碼,以便far,它表現更加不規律:
[[email protected]] hw4 $ ./hw4
Enter the Name : kl
flag
flag
ptr[2] = (null)
ptr[2] = (null)
[[email protected]] hw4 $ ./hw4
Enter the Name : jkla
flag
flag
flag
flag
ptr[4] = (null)
ptr[4] = (null)
ptr[4] = (null)
ptr[4] = (null)
*** glibc detected *** ./hw4: free(): invalid next size (fast): 0x0000000000705010 ***
======= Backtrace: =========
/lib64/libc.so.6[0x33cae75e66]
/lib64/libc.so.6[0x33cae789b3]
./hw4[0x400691]
/lib64/libc.so.6(__libc_start_main+0xfd)[0x33cae1ed5d]
./hw4[0x400529]
======= Memory map: ========
00400000-00401000 r-xp 00000000 00:13 7473045 /home/jlongar/Desktop/cStuff/hw4/hw4
00600000-00601000 rw-p 00000000 00:13 7473045 /home/jlongar/Desktop/cStuff/hw4/hw4
00705000-00726000 rw-p 00000000 00:00 0 [heap]
33ca600000-33ca620000 r-xp 00000000 fd:00 130889 /lib64/ld-2.12.so
33ca81f000-33ca820000 r--p 0001f000 fd:00 130889 /lib64/ld-2.12.so
33ca820000-33ca821000 rw-p 00020000 fd:00 130889 /lib64/ld-2.12.so
33ca821000-33ca822000 rw-p 00000000 00:00 0
33cae00000-33caf8a000 r-xp 00000000 fd:00 130934 /lib64/libc-2.12.so
33caf8a000-33cb18a000 ---p 0018a000 fd:00 130934 /lib64/libc-2.12.so
33cb18a000-33cb18e000 r--p 0018a000 fd:00 130934 /lib64/libc-2.12.so
33cb18e000-33cb18f000 rw-p 0018e000 fd:00 130934 /lib64/libc-2.12.so
33cb18f000-33cb194000 rw-p 00000000 00:00 0
33cca00000-33cca16000 r-xp 00000000 fd:00 131173 /lib64/libgcc_s-4.4.7-20120601.so.1
33cca16000-33ccc15000 ---p 00016000 fd:00 131173 /lib64/libgcc_s-4.4.7-20120601.so.1
33ccc15000-33ccc16000 rw-p 00015000 fd:00 131173 /lib64/libgcc_s-4.4.7-20120601.so.1
7f816bdde000-7f816bde1000 rw-p 00000000 00:00 0
7f816bdf5000-7f816bdf9000 rw-p 00000000 00:00 0
7fff85e61000-7fff85e76000 rw-p 00000000 00:00 0 [stack]
7fff85f62000-7fff85f63000 r-xp 00000000 00:00 0 [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 [vsyscall]
Aborted (core dumped)
我怎麼能做出的getchar在C動態創建的陣列中發揮很好?
'getchar' ** **沒有很好地發揮。這是你的負責任的類型。你爲什麼用指針指向char_? – Olaf
而不是'char ** ptr; ptr = calloc(10,sizeof(char));',我會使用'char ** ptr; ptr = calloc(10,sizeof * ptr);''sizeof(char)'錯誤或者'ptr'類型錯誤'。 – chux
似乎有些誤解。 'C'沒有'class'es。它具有「功能」。 – user3629249