|
91
|
Programación / Programación C/C++ / manipulación de un objeto multidimensional
|
en: 3 Abril 2012, 03:49 am
|
Un ejemplo que muestra varias cosas, uso de punteros, manipulación de un objeto multidimensional, uso de static en el objeto, y lo que sea, que puede ayudar a iniciados en el lenguaje C/C++. Como siempre, trato de loguear cierta información que permita saber el comportamiento del programa. //////////////////////////////////////////////////////////////////
// // UTN FRGP // 2012 // david_BS // EMAIL: david_bs@live.com //
//////////////////////////////////////////////////
#include <windows.h> #include <stdio.h>
struct somestruct{
int index; };
#define MAX 8
typedef float tMatrix[MAX][3][4];
float**** Inicializar( void ){
static float mmf[8][3][4];// para que no cambie de dirección
// inicializamos el objeto tridimensional for(int i=0; i<8; i++) for(int j=0; j<3; j++){
for(int k=0; k<4; k++){
switch(i){ case 0: { switch(j){
case 0: {
switch(k){ case 0: {mmf[i][j][k]=0.02f;break;} case 1: {mmf[i][j][k]=0.022f;break;} case 2: {mmf[i][j][k]=0.0222f;break;} case 3: {mmf[i][j][k]=0.02222f;break;} } break; } case 1: {mmf[i][j][k]=0.03f;break;} case 2: {mmf[i][j][k]=0.04f;break;} } break; }
case 1: {mmf[i][j][k]=0.05f;break;} case 2: {mmf[i][j][k]=0.7f;break;} case 3: {mmf[i][j][k]=99;break;} case 4: {mmf[i][j][k]=0.11f;break;} case 5: {mmf[i][j][k]=88;break;} case 6: {mmf[i][j][k]=33;break;} case 7: {mmf[i][j][k]=100;break;} } } }
return (float****)&mmf;// retornamos la dirección del objeto }
void Mostrar (float m[3][4]){
for(int i=0; i<3; i++) for(int j=0; j<4; j++) printf("%f\n",m[i][j]); } int main(){
// pB va a ser un puntero a un objeto de 3 dimensiones tMatrix *pB = ( tMatrix* )Inicializar( );
struct somestruct vS[8]; vS[0].index=0; vS[1].index=1; vS[2].index=2; vS[3].index=3; vS[4].index=4; vS[5].index=5; vS[6].index=6; vS[7].index=7;
struct somestruct* pS;
pS=vS;
Mostrar((*pB)[pS[0].index]);// dentro de pB hay una matriz de 3x4
system("pause"); return 0; }
Proyecto MSVC++ 6.0
|
|
|
92
|
Programación / Programación C/C++ / manipulación de punteros (ejemplo con float)
|
en: 3 Abril 2012, 03:26 am
|
Hola, dejo un código en el que utilizo algunas de las manipulaciones diferentes de punteros, para este ejemplo uso el tipo 'float'. Esto puede ayudar a ciertos iniciados a entender el manejo de punteros, al menos para tipos de datos como int o float. También se remarca la diferencia entre un vector de punteros y un puntero a vector. //////////////////////////////////////////////////////////////////
// // UTN FRGP // 2012 // david_BS // EMAIL: david_bs@live.com //
//////////////////////////////////////////////////
#include <windows.h> #include <stdio.h>
int main(){
float vec1[5]={ 0.5f, 0.2f, 0.22f, 0.01f, 0.0f }; float vec2[5]={ 0.5f, 0.2f, 0.22f, 0.01f, 0.0f }; float vec3[5]={ 0.5f, 0.2f, 0.22f, 0.01f, 0.0f }; float (*vec4)[5];// puntero a vector de floats float (*vec5)[5];// puntero a vector de floats float (*vec6)[5];// puntero a vector de floats vec4=&vec1; vec5=&vec2; vec6=&vec3;
float* pf1[3]; //vector de punteros a vectores de float pf1[0]=&vec1[0]; pf1[1]=&vec2[0]; pf1[2]=&vec3[0];
float* pf2[3]; //vector de punteros a vectores de float pf2[0]=*vec4; pf2[1]=*vec5; pf2[2]=*vec6;
float** ppf1; ppf1 = (float**)&pf1;//se le asigna la direccion de un vector de punteros a vectores de float
float** ppf2; ppf2 = (float**)&pf2;//se le asigna la direccion de un vector de punteros a vectores de float
printf("vec1: %x\n",vec1); printf("vec4: %x\n",vec4); printf("pf1: %x\n",pf1); printf("pf1[0]: %x\n",pf1[0]); printf("ppf1: %x\n",ppf1); printf("*ppf1: %x\n",*ppf1);
printf("vec3: %x\n",vec3); printf("ppf1[2]: %x\n",ppf1[2]);
printf("*ppf1[0]: %f\n",*ppf1[0]); printf("*ppf1[1]: %f\n",*ppf1[1]); printf("*ppf1[2]: %f\n",*ppf1[2]); printf("*(ppf1[0]+1): %f\n",*(ppf1[0]+1)); printf("*(ppf1[1]+1): %f\n",*(ppf1[1]+1)); printf("*(ppf1[2]+1): %f\n",*(ppf1[2]+1));
system("pause"); return 0; }
Proyecto en MSVC++ 6.0
|
|
|
93
|
Programación / Programación C/C++ / ejemplo de ordenamientos básicos
|
en: 2 Abril 2012, 02:30 am
|
Un par de ejemplos de ordenamientos, uno para enteros que deben ordenarse de menor a mayor, y otro para cadenas que deban ordenarse alfabéticamente. // // UTN FRGP // 2012 // David_BS // david_bs@live.com
///////////////////////////////////////////////////
#include <windows.h> #include <stdio.h>
void TratarVectorDeInt(){//de menor a mayor
printf("\n");
int vec[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
int aux;
for(int i=0; i< (11-1); i++){
for(int j=(i+1); j< 11; j++){
if(vec[j]<vec[i]){
aux=vec[i]; vec[i]=vec[j]; vec[j]=aux; }}}
for(int k=0;k<11;k++) printf("%d\n",vec[k]);
system("pause"); }
int ComparaDosCadenas(const char* str1, const char* str2);
void TratarVectorDeStrings(){//orden alfabético
printf("\n");
char vec[][16] = { "Guatemala\0", "Brasil\0", "Estados Unidos\0", "Paraguay\0", "Argentina\0", "Chile\0", "Peru\0", "Mexico\0", "Cuba\0", "Honduras\0" };
char aux[16];
for(int i=0;i<(10-1);i++){
for(int j=(i+1); j< 10; j++){
if(ComparaDosCadenas(vec[j],vec[i])>0){
memset(aux,0,sizeof(aux)); strcpy(aux,vec[i]); strcpy(vec[i],vec[j]); strcpy(vec[j],aux); }}}
for(int k=0;k<10;k++) printf("%s\n",vec[k]);
system("pause"); }
int main() {
// 1: ordenar un vector de enteros TratarVectorDeInt();
// 2: ordenar una matriz de char (vector de strings) TratarVectorDeStrings();
return 0; }
int ComparaDosCadenas(const char* str1, const char* str2){//si la 1 es menor a la 2
// printf("str1: %s ; str2: %s\n",str1,str2); int l1=strlen(str1);//brasil int l2=strlen(str2);//guatemala char aux1[16];strcpy(aux1,str1); char aux2[16];strcpy(aux2,str2); strlwr(aux1); strlwr(aux2); // printf("str1: %s ; str2: %s\n",aux1,aux2);
int len=l1; if(l2<l1) len=l2;
for(int i=0; i<len; i++){
// printf("str1: %c ; str2: %c\n",aux1[i],aux2[i]); if(aux1[i]<aux2[i]) return 1; else if(aux1[i]>aux2[i]) return 0; }
if(l1>l2) return 1; return 0; }
Proyectohttp://www.mediafire.com/?r42y1f6l6yoeju9
|
|
|
96
|
Programación / Programación C/C++ / Ejemplo de programa WinApi32 GUI
|
en: 2 Abril 2012, 00:08 am
|
Un proyecto de un programa básico con interfáz gráfica de Windows. Está hecho con MSVC++ 6.0 proyectohttp://www.mediafire.com/?yd4vpb42j4p1pi6winmain.cpp// // UTN FRGP // 2011 // david_BS // EMAIL: david_bs@live.com //
//////////////////////////////////////////////////
//#define WINVER 0x0500 //WINVER as 0x0500 enables features specific to Win 98 and 2000 //#define VC_EXTRALEAN
#include <windows.h> //gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib
///////////////////////// // Globales
HWND EditControl1; HWND EditControl2; HWND EditControl3; HWND StaticControl1;
const int ID_EDIT1=1, ID_EDIT2=2, ID_EDIT3=3, ID_EDIT4=4, ID_EDIT5=5; const int ID_OK = 6; const int ID_CANCEL = 7; const int ID_LABEL1 = 0;
/////////////////////////////
void getCentradoGlobal(int vXY[2], int h, int w);
/////////////// // Controles de ventana
void RegistrarControlesDeVentanaPrincipal(HWND hWin) { static char* t1 = TEXT("Ingrese 3 numeros");
unsigned long EstiloHijo1 = WS_VISIBLE | WS_CHILD; unsigned long EstiloHijo2 = WS_CHILD | WS_VISIBLE | WS_BORDER; unsigned long EstiloHijo3 = WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON; unsigned long EstiloHijo4 = WS_CHILD | WS_VISIBLE | LBS_NOTIFY | LBS_SORT | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP;
long editstyle =WS_CHILD|WS_VISIBLE|WS_BORDER|WS_TABSTOP;//|ES_AUTOHSCROLL;//|WS_TABSTOP;
int offs = 30; int X=20; int Y=10; int W=80; int H=25;
StaticControl1 = CreateWindow( TEXT("static"), t1, EstiloHijo1, 20,10,180,20, hWin, (HMENU)ID_LABEL1, NULL, NULL);
EditControl1 = CreateWindow( TEXT("Edit"), NULL, editstyle, X, Y+20, W, H, hWin, (HMENU)ID_EDIT1, NULL, NULL);
EditControl2 = CreateWindow( TEXT("Edit"), NULL, editstyle, X, Y+20+(offs*1), W, H, hWin, (HMENU)ID_EDIT2, NULL, NULL);
EditControl2 = CreateWindow( TEXT("Edit"), NULL, editstyle, X, Y+20+(offs*2), W, H, hWin, (HMENU)ID_EDIT3, NULL, NULL);
CreateWindow( TEXT("button"), TEXT("Sumar"), EstiloHijo1, X,130,60,H, hWin, (HMENU) ID_OK, NULL, NULL);
CreateWindow( TEXT("button"), TEXT("Salir"), EstiloHijo1, X+70,130,50,H, hWin, (HMENU)ID_CANCEL, NULL, NULL); }
////////// // CallBack
INT_PTR CALLBACK WinProc(HWND hWin, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg) { case WM_CREATE: { RegistrarControlesDeVentanaPrincipal(hWin); } break;
case WM_KEYDOWN: { if(wParam==VK_TAB){ } } break;
case WM_COMMAND: { switch(LOWORD(wParam)) { case ID_OK: { char chBuffer1[128]; memset(chBuffer1,0,sizeof(chBuffer1)); GetDlgItemText( hWin,ID_EDIT1, chBuffer1, sizeof( chBuffer1 ) ); char chBuffer2[128]; memset(chBuffer2,0,sizeof(chBuffer2)); GetDlgItemText( hWin,ID_EDIT2, chBuffer2, sizeof( chBuffer2 ) ); int i_res = atoi(chBuffer1)+atoi(chBuffer2); char ch_res[128]; itoa(i_res,ch_res,10); HWND Edit3 = GetDlgItem(hWin,ID_EDIT3); SendMessage(Edit3 , WM_SETTEXT, 0, (LPARAM)ch_res); } break;
case ID_CANCEL: { SendMessage(hWin, WM_CLOSE, 0, 0); return TRUE; } break; } } break;
case WM_CLOSE: { DestroyWindow(hWin); return TRUE; } ///////////////////////////// case WM_DESTROY: { PostQuitMessage(0); return TRUE; }
default: return DefWindowProc(hWin,uMsg,wParam,lParam);
}
return 0; //return DefWindowProc(hWin,uMsg,wParam,lParam); }
//////////// // Clase de ventana
void RegistrarClaseVentana(WNDCLASS* wc) { // HICON hIconImg = (HICON)LoadImage(NULL, "BS.ico", IMAGE_ICON, 542, 449, LR_LOADFROMFILE);
wc->lpszClassName = TEXT("Window"); wc->hInstance = GetModuleHandle(NULL); //wc->hbrBackground = GetSysColorBrush(COLOR_3DFACE); wc->hbrBackground = (HBRUSH)(COLOR_BTNFACE+1); wc->lpfnWndProc = (WNDPROC)WinProc; wc->style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc->cbClsExtra = 0; wc->cbWndExtra = 0; //wc->hIcon = LoadIcon(NULL,"IDI_ICON1"); wc->hIcon = LoadIcon(NULL,"IDI_WINLOGO"); wc->hCursor = LoadCursor(NULL,IDC_ARROW); wc->lpszMenuName = NULL; RegisterClass((struct tagWNDCLASSA *)wc); }
////////////// // Punto de entrada ('WinMain' : must be '__stdcall')
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE h0, LPSTR lpCmdLine, int nCmdShow){
HWND hWin; WNDCLASS wc = {0};
RegistrarClaseVentana(&wc);
int ancho=250; int alto=200; int dim[2]; getCentradoGlobal(dim, ancho, alto);
unsigned long Estilo1 = WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
hWin = CreateWindow( wc.lpszClassName, "GUI32", Estilo1, dim[0], dim[1], ancho, alto, NULL, NULL, hInst, NULL);
// ShowWindow(hWin,nCmdShow); ShowWindow(hWin, SW_SHOWDEFAULT);
//UpdateWindow(hWin);
MSG msg; while(GetMessage(&msg, NULL, 0, 0)>0) { TranslateMessage(&msg); DispatchMessage(&msg); }
return msg.wParam; }
////////
void getCentradoGlobal(int vXY[2], int h, int w) { RECT rcP; GetWindowRect(GetDesktopWindow(), &rcP); int centerX = (rcP.right/2)-(w/2)-(w/4); int centerY = (rcP.bottom/2)-(h/2)+(h/6); vXY[0]=centerX; vXY[1]=centerY; }
|
|
|
98
|
Programación / Programación C/C++ / Re: Problema con Cast en Visual C
|
en: 31 Marzo 2012, 17:57 pm
|
Karman XD k raro encontrarte por ak sólo agarré tu code y lo puse en el visual c y lo compilé así, sólo un cambio hice, pasa que lo hice en el Visual Studio 6. vos seguro usás el 2010, lo tengo para instalar todavia :/ class XX{ public: }; class XY{ public: }; //typedef void (XX::* pfun)(void); typedef int (XX::* pfun)(int);
class X:public XX,XY{ public: int ff(int a){ return a; } static pfun f; static struct _t{ pfun f; }t; }; pfun X::f= pfun(&X::ff); struct X::_t X::t={pfun(&X::ff)};
int main(){
//ilegal dentro de este ámbito //pfun X::f=pfun(&X::ff); //struct X::_t X::t={pfun(&X::ff)};
return 0;
}
|
|
|
100
|
Programación / Programación C/C++ / uso de llaves para poder declarar variables del mismo nombre
|
en: 31 Marzo 2012, 17:43 pm
|
Esto es algo que muchos iniciados no saben, y es que las llaves de c/c++ son para marcar ámbitos, por ejemplo el ámbito de una función es lo que está dentro de sus llaves. por ejemplo, si quisiera crear dos FOR que utilicen una misma variable llamada 'i', y quiero declararla dos veces, esto normalmente no se puede hacer dentro de una función, pero si lo hacemos dentro de otro ámbito separado por llaves es posible. void Funcion_Dummy() { { for(int i=0; i<5; i++) { } }
/* vuelvo a declarar 'i' pero dentro de otro ámbito de llaves */
{ for(int i=0; i<5; i++) { } } } parece ser un pequeño truquillo, pero es muy útil si les gusta usar los mismos nombres de variables, por ejemplo en los FOR siempre nos gusta usar i,j,k, etc La consigna es tener consciencia del ámbito en el que estamos. Que estén bien ;-D
|
|
|
|
|
|
|