Sunteți pe pagina 1din 2

#include <stdio.

h> //scanf , printf

#include <stdlib.h>//needed for exit(0)


#include <string.h>
//compile with gcc -std=c99 filename.c
//compile with newer c standart gcc -std=c11 filename.c

void main(){

//each var will consume 4 bytes in memory


int rand1=12,rand2=15;

//print addresses for variables with %p in hex


//get memory address for var with &
printf("rand1 = %p : rand2 = %p \n",&rand1,&rand2 );

//print address in decimal with %d

printf("rand1 = %d : rand2 = %d \n",&rand1,&rand2 );


printf("size of int %d\n",sizeof(rand1));

//to save memory address of variable we use pointer variable

int *pRand1=&rand1;
printf("\n");
printf("Pointer %p \n",pRand1 );
printf("Pointer %d \n",pRand1 );

//get data from a pointer is called dereferencing


//to get data use *
printf("Value in memory address %d is %d\n",pRand1, *pRand1);

//***arrays and pointers


//array name is a pointer to array itself, it points to first item
int primeNumbers[]={2,3,5,7};
printf("First number : %d\n",primeNumbers[0]);
//get first array item by dereferencing pointer
printf("First number : %d\n",*primeNumbers);

//increment the pointer and dereference result and get second item
printf("Second number : %d\n",*(primeNumbers+1));

int * pToSecond=primeNumbers+1;
printf("Second number : %d\n",*pToSecond);
printf("\n");
//*** arrays of string
//create array of pointers
char * students[5]={"lolis","petras","jake","asfdasdfsad","bubu"};
//this also works
//char * students[]={"lolis","petras","jake","asfdasdfsad","bubu"};

for(int i=0; i<5;i++){


printf("%s : mem_address %d\n",students[i],&students[i]);
}

printf("\n");
for(int i=0; i<5;i++){
printf("%s : mem_address %d\n",*(students+i),students+i);
}

printf("\n");

char word[]="Test";

printf("%c address is %d\n",*(word+1),word+1);//prints e


printf("%s address is %d\n",word,word);//prints whole word Test
printf("\n");
*(word+1)='B';
printf("%c address is %d\n",*(word+1),word+1);//prints B
printf("%s address is %d\n",word,word);//prints whole word TBst
printf("\n");
//safely overwrite word
strncpy(word,"abcdefghjklm",sizeof(word)-1);//dont touch '\0'
printf("%c address is %d\n",*(word+1),word+1);//prints b
printf("%s address is %d\n",word,word);//prints abcd
printf("\n");

//THIS WAY IS NOT POSSIBLE TO MODIFY


char *text="Test";//constant read only and cannot be modified
printf("%s address is %d\n",text,&text);
//*(text+1)='B';//this will throw error
//strncpy(text,"abcdefghjklm",sizeof(text)-1);//this will throw error
printf("%s address is %d\n",text,&text);
}

S-ar putea să vă placă și