#include <bits/stdc++.h> #include <stdlib.h> #include <stdio.h> using namespace std; #define maxn 10005 #define M 105 char *getLine(void){ const size_t sizeIncrement = 10; char* buffer = (char*)malloc(sizeIncrement); printf("%d\n",buffer); char* currentPosition = buffer; size_t maximumLength = sizeIncrement; size_t length = 0; int character; if(currentPosition ==NULL){ return NULL; } while(1){ character = fgetc(stdin); if(character == '\n'){ break; } if(++length >= maximumLength){ char *newBuffer = (char*)realloc(buffer,maximumLength += sizeIncrement); printf("%d\n",newBuffer); if(newBuffer == NULL){ free(buffer); return NULL; } currentPosition = newBuffer +(currentPosition - buffer); buffer = newBuffer; } *currentPosition++ = character; printf("%d\n",currentPosition); } *currentPosition = '\0'; return buffer; } int main(){ getLine(); system("pause"); return 0; }
能夠看出realloc後返回的仍是一開始的地址:10882360c++
#include <bits/stdc++.h> #include <stdlib.h> #include <stdio.h> using namespace std; #define maxn 10005 #define M 105 int main(){ int* arr[5]; for(int i=0;i<5;++i){ *(arr+i) = (int*)malloc(sizeof(int)); **(arr+i) = i; printf("%d\n",**(arr+i)); } system("pause"); return 0; }
#include <bits/stdc++.h> #include <stdlib.h> #include <stdio.h> using namespace std; #define maxn 10005 #define M 105 int main(){ int matrix[2][5] = {{1,2,3,4,5},{6,7,8,9,10}}; for(int i=0;i<2;++i){ for(int j=0;j<5;++j){ printf("matrix[%d][%d] Address: %p Value: %d\n", i,j,&matrix[i][j],matrix[i][j]); } } system("pause"); return 0; }
#include <bits/stdc++.h> #include <stdlib.h> #include <stdio.h> using namespace std; #define maxn 10005 #define M 105 int main(){ char command[16]; printf("Enter a Command: "); scanf("%s",command); if(strcmp(command,"Quit")==0){ printf("The command was Quit"); }else{ printf("The command was not Quit"); } system("pause"); return 0; }
#include <bits/stdc++.h> #include <stdlib.h> #include <stdio.h> using namespace std; #define maxn 10005 #define M 105 int main(){ char* error = "ERROR: "; char* errorMessage = "Not enought memory"; char* buffer = (char*)malloc(strlen(error)+strlen(errorMessage)+1); strcpy(buffer,error); strcat(buffer,errorMessage); printf("%s\n",buffer); printf("%s\n",error); printf("%s\n",errorMessage); system("pause"); return 0; }