iT邦幫忙

0

c語言:多印的1041???記憶體位址?

c
  • 分享至 

  • xImage

c語言入門的語法↓
請使用者使入5個數值,再倒印回來。
倒印前會多印一個1041,請問是哪裡來的???
自己腦袋轉3遍還是想不透。
註:在線上compile的 https://www.onlinegdb.com/

    int i=0, n=0, *p=NULL;	
	
	p=(int *)malloc(sizeof(int));	

	for (i=1; i<=5; i++) { 
		p=(int *)realloc(p, i*sizeof(int)); 	    
	    printf("number %d : ", i);
        scanf("%d", &n);	    
	    *(p+(i))=n; // 此行不能與上行合併,會收到scanf()的返回值,而非變數n的值。
	}
	
	for (i-1; i>0; i--)
		printf("%d\n", *(p+i));	// 倒印回來。
		
	free(p); 
看更多先前的討論...收起先前的討論...
淺水員 iT邦大師 6 級 ‧ 2023-07-27 20:31:34 檢舉
for(i-1
不會變動i值
樓上,會變動啊。初始值 i -1而已,後面會一直減。
淺水員 iT邦大師 6 級 ‧ 2023-07-28 00:45:22 檢舉
初始值不是 i-1
你初始值要 i-1 的話要寫 i=i-1 或 i--
frogsoul iT邦研究生 5 級 ‧ 2023-07-28 08:15:24 檢舉
for的第一個參數,不是初始"值",而是初始"陳述式(statement)"
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
pickuse
iT邦新手 4 級 ‧ 2023-07-27 17:57:02

我看起來正常呢?

https://ithelp.ithome.com.tw/upload/images/20230727/20155998s2h9jFKXMx.jpg

#include <stdio.h>
#include <stdlib.h>

int main() {
    int i, n, *p;

    p = (int*)malloc(sizeof(int));

    for (i = 1; i <= 5; i++) {
        p = (int*)realloc(p, i * sizeof(int));
        printf("number %d : ", i);
        scanf("%d", &n);
        *(p + i) = n;
    }

    for (i = 5; i > 0; i--)
        printf("%d\n", *(p + i));

    free(p);

    return 0;
}

使用 g++ (Apple clang version 14.0.0 (clang-1400.0.29.202))

謝謝樓上。m(__)m

0

要改這裡

        for(i = 5; i>= 1; i--)
                printf("%d \n", *(p+i));

結果圖
https://ithelp.ithome.com.tw/upload/images/20230728/20126723vNE1hMnP2o.jpg

我剛有去測試程式,是變數 i 位移的問題。

以下是完整程式:
我先 去 印出 i 目前的數字是6,
所以,我有在下圖中,把 「正序」跟「反序」都印出來。

#include<stdio.h>
#include<stdlib.h>

void main(){
        int i = 0, n = 0, *p = NULL;
        p = (int *) malloc(sizeof(int));

        for(i = 1; i <= 5; i++){
                p = (int *)realloc(p, i * sizeof(int));
                printf("number %d:", i);
                scanf("%d", &n);
                *(p+(i)) = n;
        }


        printf("i = %d \n", i);
        for(i=1; i <=5; i++)
                printf("%d \n", *(p+i));

        for(i = 5; i>= 1; i--)
                printf("%d \n", *(p+i));
        free(p);
    }

原本的程式會多印出"1041"
https://ithelp.ithome.com.tw/upload/images/20230728/20126723TYzRTu9v4O.jpg

作業系統 : Ubuntu 22.04
gcc

我要發表回答

立即登入回答